<?php

namespace App\Services;

use App\Http\Resources\StoreResource;
use App\Models\Store;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

class StoreService
{
    use HasResponse;

    public function list($params, $withPagination)
    {
        $stores = Store::where('status', '!=', 2)->where('idcompany', $params['idcompany'])->orderBy('id', 'desc');

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

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

        $stores = StoreResource::collection($stores->load('company', 'branchOffice', 'country', 'department', 'province', 'district',));

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

    public function register($params)
    {
        DB::beginTransaction();
        try {
            // return $params;
            $codeExisting = Store::where('code', $params['code'])->where('status', 1)->first();
            if ($codeExisting) return $this->errorResponse('El código ya se encuentra registrado.', 400);

            $nameExisting = Store::where('name', $params['name'])->where('status', 1)->first();
            if ($nameExisting) return $this->errorResponse('El nombre ya se encuentra registrado.', 400);

            $store = Store::create([
                'code' => $params['code'],
                'name' => $params['name'],
                'description' => $params['description'],
                'address' => $params['address'],
                'idbranchoffice' => $params['idbranchoffice'],
                'idcountry' => $params['idcountry'],
                'iddepartment' => $params['iddepartment'],
                'idprovince' => $params['idprovince'],
                'iddistrict' => $params['iddistrict'],
                'idcompany' => $params['idcompany'],
                'status' => isset($params['status']) ? $params['status'] : 1,
            ]);
            $store->save();

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

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

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

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

            $store = Store::find($id);
            $store->name = $params['name'];
            $store->code = $params['code'];
            $store->address = $params['address'];
            $store->idbranchoffice = $params['idbranchoffice'];
            $store->idcountry = $params['idcountry'];
            $store->iddepartment = $params['iddepartment'];
            $store->idprovince = $params['idprovince'];
            $store->iddistrict = $params['iddistrict'];
            $store->description = isset($params['description'] ) ? $params['description'] : null;
            $store->save();

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

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

            if($params['status'] == '2') return $this->successResponse('Solo se puede habilitar o deshabilitar.');

            $store = Store::find($id);
            $store->status = $params['status'];
            $store->save();

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

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

            $store = Store::find($id);
            $store->status = 2;
            $store->save();

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

    private function verifyStore($idStore)
    {
        $store = Store::where('id', $idStore)->first();
        if (!$store) return $this->errorResponse('No se encontró la bodega.', 400);

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