<?php  

namespace App\Admin\Account;

use App\Admin\Survey\SurveyGetter;
use App\Admin\GasStation\GasStationGetter;
use App\Admin\Survey\SurveyService;
use App\Admin\Users\UsersGetter;
use App\Admin\Users\UsersServices;
use App\Models\Admin\Account;
use App\Models\Entities\AccountType;
use App\Models\Entities\ActiveStatus;
use App\Models\GasStation;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\DB;

class AccountService
{
    public static function createAcount($request){
        
        try {
            if ($request->user != 0) {
                if (UsersGetter::hasUserAccount($request->user))
                    throw new Exception("El usuario seleccionado ya tiene asignada una cuenta", 1);
            } 

            $userAdmin = auth('admin')->user();
            $account = null;
            DB::transaction(function () use ($userAdmin, $request, &$account) {
                $account = Account::create([
                    'name' => $request->name,
                    'type' => AccountType::Free->value,
                    'is_active' => ActiveStatus::Active->value,
                    'created_by_user_id' => $userAdmin->id,
                    'max_stations' => env('APP_MAX_STATIONS')
                ]);
        //         return response()->json($request->user);
        // exit;

                $survey = SurveyService::createDefualtSurvey($userAdmin->id, $account->id);

                if ($request->user != 0) {
                    UsersServices::addAccountToUser($request->user, $account->id);
                }

                if (count($request->stations) > 0) {
                    foreach ($request->stations as  $station) {
                        self::createStation(
                            $account->id,
                            $survey,
                            $station['name'],
                            $station['pl'],
                            $station['manager'],
                            $station['phone_number']
                        );
                    }
                }
            });
            return $account;
        } catch (Exception $e) {
            throw new Exception($e->getMessage() , 1);
            
        }
    }

    public static function disableEnableAccount($accountId, $status){
        try {
            $account = AccountGetter::getAccountById($accountId);
            $account->is_active = $status;
            $account->save();
        } catch (Exception $e) {
            throw new Exception("Error al " . ActiveStatus::from($status)->action() . " la cuenta", 1);
            
        }
    }

    public static function enableAccount($accountId)
    {
        try {
            $account = AccountGetter::getAccountById($accountId);
            $account->type = ActiveStatus::Active->value;
            $account->save();
        } catch (Exception $e) {
            throw new Exception("Error al desactivar la cuenta", 1);
        }
    }

    public static function AccountType($accountId, $type){
        try {
            $account = AccountGetter::getAccountById($accountId);
            $account->type = $type;
            $account->save();
        } catch (Exception $e) {
            throw new Exception("Error al cambiar el typo de cuenta la cuenta", 1);
        }
    }

    public static function createStation($account, $name, $pl, $manager, $phone){
        try {
            $survey = SurveyGetter::getDefaultSurveyByAccount($account);
            if($survey == null) throw new Exception("Cuenta sin encuesta disponible ", 1);
            
            $station = GasStation::create([
                'account_id' => $account,
                'survey_id' => $survey,
                'name' => $name,
                'pl' => $pl,
                'qr_token' => str()->random(100),
                'manager' => $manager,
                'phone_contact' => $phone
            ]);
            return $station;
        } catch (Exception $e) {
            throw new Exception("Error al generar la estación. {{$e->getMessage()}}", 1);
        }
    }
}
