<?php

namespace App\Services;

use App\Http\Resources\BranchOfficeResource;
use App\Models\BranchOffice;
use App\Models\BranchOfficeType;
use App\Models\Store;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class BranchOfficeService
{
    use HasResponse;

    public function list($params, $withPagination)
    {
        $branchOffices = BranchOffice::where('status', 1)->orderBy('id', 'desc');

        $search = isset($params['search']) ? $params['search'] : '';
        if($search){
            $branchOffices->where(function ($query) use ($search) {
                $query->where('name', 'like', "%$search%")
                    ->orWhere('code', 'like', "%$search%");
            });
        }

        $branchOffices = !empty($withPagination)
            ? $branchOffices->paginate($withPagination['perPage'], page: $withPagination['page'])
            : $branchOffices->get();

        $branchOffices = BranchOfficeResource::collection($branchOffices->load('company', 'typeOffice', 'country', 'department', 'province', 'district'));

        return $this->successResponse('Lectura exitosa.', $branchOffices);
    }

    public function listByCompany($params, $withPagination)
    {
        $branchOffices = BranchOffice::where('status', 1)->orderBy('id', 'desc');

        $idcompany = isset($params['idcompany']) ? $params['idcompany'] : '';
        if($idcompany) {
            $branchOffices->where(function ($query) use ($idcompany) {
                $query->where('idcompany', $idcompany);
            });
        }

        $search = isset($params['search']) ? $params['search'] : '';
        if($search){
            $branchOffices->where(function ($query) use ($search) {
                $query->where('name', 'like', "%$search%")
                    ->orWhere('code', 'like', "%$search%");
            });
        }

        $branchOffices = !empty($withPagination)
            ? $branchOffices->paginate($withPagination['perPage'], page: $withPagination['page'])
            : $branchOffices->get();

        $branchOffices = BranchOfficeResource::collection($branchOffices->load('company', 'typeOffice', 'country', 'department', 'province', 'district'));

        return $this->successResponse('Lectura exitosa.', $branchOffices);
    }

    public function listTypesBranches($withPagination)
    {
        $types = BranchOfficeType::where('status', 1)->orderBy('id', 'desc');

        $types = !empty($withPagination)
            ? $types->paginate($withPagination['perPage'], page: $withPagination['page'])
            : $types->get();

        return $this->successResponse('Lectura exitosa.', $types);
    }

    public function register($params)
    {
        DB::beginTransaction();
        try {

            $codeExisting = BranchOffice::where('code', $params['code'])->where('idcompany', $params['idcompany'])->where('status', 1)->first();
            if ($codeExisting) return $this->errorResponse('El código ya se encuentra registrado.', 400);
        
            $nameExisting = BranchOffice::where('name', $params['name'])->where('idcompany', $params['idcompany'])->where('status', 1)->first();
            if ($nameExisting) return $this->errorResponse('El nombre ya se encuentra registrado.', 400);

            $addresExisting = BranchOffice::where('address', $params['address'])->where('idcompany', $params['idcompany'])->where('status', 1)->first();
            if ($addresExisting) return $this->errorResponse('La dirección ya se encuentra registrada.', 400);

            // if($params['assignmenttype'] == 1 && !$params['idproductlist']) return $this->errorResponse('Debe enviar una lista de precios.', 400);

            $branchOffice = BranchOffice::create([
                'code' => $params['code'],
                'name' => $params['name'],
                'phone' => $params['phone'],
                'address' => $params['address'],
                // 'assignmenttype' => $params['assignmenttype'],
                // 'idproductlist' => $params['idproductlist'] && $params['assignmenttype'] == 1 ? $params['idproductlist'] : null,
                'idofficetype' => $params['idofficetype'],
                'idcountry' => $params['idcountry'],
                'iddepartment' => $params['iddepartment'],
                'idprovince' => $params['idprovince'],
                'iddistrict' => $params['iddistrict'],
                'idcompany' => isset($params['idcompany']) ? $params['idcompany'] : null,
            ]);
            $branchOffice->save();

            DB::commit();
            return $this->successResponse('Sucursal creada satisfactoriamente.', $branchOffice);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la creación de una sucursal.', $th->getMessage());
        }
    }

    public function update($id, $params)
    {
        DB::beginTransaction();
        try {
            # Verificar validez de la sucursal
            $validate = $this->verifyBranchOffice($id);
            if (!$validate->original['status']) return $validate;

            $codeExisting = BranchOffice::where('code', $params['code'])->where('id','!=', $id)->where('idcompany', $params['idcompany'])->where('status', 1)->first();
            if ($codeExisting) return $this->errorResponse('El código ya se encuentra registrado.', 400);
        
            $nameExisting = BranchOffice::where('name', $params['name'])->where('id','!=', $id)->where('idcompany', $params['idcompany'])->where('status', 1)->first();
            if ($nameExisting) return $this->errorResponse('El nombre ya se encuentra registrado.', 400);

            $addresExisting = BranchOffice::where('address', $params['address'])->where('id','!=', $id)->where('idcompany', $params['idcompany'])->where('status', 1)->first();
            if ($addresExisting) return $this->errorResponse('La dirección ya se encuentra registrada.', 400);

            // if($params['assignmenttype'] == 1 && !$params['idproductlist']) return $this->errorResponse('Debe enviar una lista de precios.', 400);

            $branchOffice = BranchOffice::find($id);
            $branchOffice->code = $params['code'];
            $branchOffice->name = $params['name'];
            $branchOffice->phone = $params['phone'];
            $branchOffice->address = $params['address'];
            // $branchOffice->assignmenttype = $params['assignmenttype'];
            // $branchOffice->idproductlist = $params['idproductlist'] && $params['assignmenttype'] == 1 ? $params['idproductlist'] : null;
            $branchOffice->idofficetype = $params['idofficetype'];
            $branchOffice->idcountry = $params['idcountry'];
            $branchOffice->iddepartment = $params['iddepartment'];
            $branchOffice->idprovince = $params['idprovince'];
            $branchOffice->iddistrict = $params['iddistrict'];
            $branchOffice->save();

            DB::commit();
            return $this->successResponse('Sucursal actualizada satisfactoriamente.', $branchOffice);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la actualización de una sucursal.', $th->getMessage());
        }
    }

    public function delete($id)
    {
        DB::beginTransaction();
        try {
            # Verificar validez de la sucursal
            $validate = $this->verifyBranchOffice($id);
            if (!$validate->original['status']) return $validate;

            $branchOffice = BranchOffice::find($id);
            $branchOffice->status = 2;
            $branchOffice->save();

            DB::commit();
            return $this->successResponse('Sucursal eliminada satisfactoriamente.', $branchOffice);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la eliminación de una sucursal.', $th->getMessage());
        }
    }

    private function verifyBranchOffice($idbranchOffice)
    {
        $branchOffice = BranchOffice::where('id', $idbranchOffice)->where('status', 1)->first();
        if (!$branchOffice) return $this->errorResponse('No se encontró la sucursal.', 400);

        return $this->successResponse('OK');
    }
}
