<?php

namespace Modules\Unit\Services;

use App\Services\Upload\UploadService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Unit\Interfaces\UnitRepositoryInterface;
use Modules\Unit\Models\Unit;

class UnitService
{

    public function __construct(private UnitRepositoryInterface $unitRepository)
    {}

    public function get(array $request)
    {
        $builder = $this->unitRepository->get($request);

        if (@$request['title'])
        {
            $builder->where('sd.title', 'LIKE', '%'.$request['title'].'%');
        }

        if (@$request['user_id'])
        {
            $builder->where('units.user_id', $request['user_id']);
        }
        elseif (@$request['user_code'])
        {
            $builder->whereHas('user', function ($query) use ($request) {
                $query->where('code', $request['user_code']);
            });
        }

        if (@$request['area_id'])
        {
            $builder->where('units.area_id', $request['area_id']);
        }
        elseif (@$request['city_id'])
        {
            $builder->whereHas('area', function ($query) use ($request) {
                $query->where('city_id', $request['city_id']);
            });
        }

        if (@$request['type_id'])
        {
            $builder->where('units.type_id', $request['type_id']);
        }

        if (@$request['unit_status'])
        {
            $builder->where('units.status', $request['unit_status']);
        }

        if (@$request['sold_status'])
        {
            $builder->where('units.sold_status', $request['sold_status']);
        }

        if (@$request['price'])
        {
            $builder->where('units.price', $request['price']);
        }

        if (@$request['baths'])
        {
            $builder->where('units.baths', $request['baths']);
        }

        if (@$request['date_from'])
        {
            $builder->whereDate('units.created_at', '>=', $request['date_from']);
        }

        if (@$request['date_to'])
        {
            $builder->whereDate('units.created_at', '<=', $request['date_to']);
        }

        if (isset($request['status']))
        {
            if (@$request['status'] == 0)
            {
                $builder->onlyTrashed();
            }
        }

        if (@$request['orderBy'])
        {
            $builder->orderBy($request['orderBy']['key'],$request['orderBy']['value']);
        }
        else
        {
            $builder->orderBy('id','DESC');
        }

        if (@$request['paginate']) {
            $units= $builder->paginate(50);
        }else{
            $units=$builder->cursor();
        }
        return $units;
    }
    public function checkItem($id)
    {
        $unit = $this->unitRepository->checkItem($id);
        return $unit;
    }

    public function getItemByCode($code)
    {
        $unit = $this->unitRepository->getItemByCode($code);
        $unitDescription = $this->unitRepository->getItem($unit->id);
        foreach ($unitDescription as $row) {
            $unit[$row->local]= $row;
        }
        return $unit;
    }

    public function getItem($id)
    {
        $unit = $this->checkItem($id);
        $unitDescription = $this->unitRepository->getItem($id);
        foreach ($unitDescription as $row) {
            $unit[$row->local]= $row;
        }
        return $unit;
    }

    public function getItemTrashed($id)
    {
        $unit = $this->unitRepository->getItemTrashed($id);
        return $unit;
    }

    public function create(array $request): Unit
    {
        $unit = $this->unitRepository->create($request);
        $this->unitRepository->saveData($request,$unit->id);
        $this->saveImages($request,$unit->id);
        return $unit;
    }
    public function update(array $request,int $id): Unit
    {
        // DB::enableQueryLog();
        $unit = $this->checkItem($id);
        $this->saveImages($request,$unit->id);
        $unit = $this->unitRepository->update($request,$unit);
        $this->unitRepository->saveData($request,$unit->id);
        // dd(DB::getQueryLog());
        return $unit;
    }
    public function destroy(string $code): void
    {
        $unit = $this->unitRepository->getItemByCode($code);
        if ($unit)
        {
            $this->unitRepository->destroy($unit);
        }
        else
        {
            $unit = $this->getItemTrashed($code);
            $this->unitRepository->restore($unit);
        }
    }
    public function destroyAll(array $request): void
    {
        if ($request['status'] == 1)
        {
            $this->unitRepository->destroyAll($request['ids']);
        }
        else
        {
            $this->unitRepository->restoreAll($request['ids']);
        }
    }

    public function saveImages(array $request, $unitId)
    {
        $this->deleteAllImages($request['old_images'] ?? [], $unitId);
        if ($request['images'] ?? []) {
            $data= [];
            foreach($request['images'] as $imageFile)
            {
                $image= UploadService::upload($imageFile, null, 'units');
                $data[]= [
                    'image'=> $image,
                    'unit_id'=> $unitId,
                ];
            }
            // INSERT IMAGES
            $this->unitRepository->insertImages($data);
        }
        // dd(DB::getQueryLog());
    }

    public function deleteAllImages($oldImages= [], $unitId):void
    {
        // DELETE OLD IMAGES
        $oldRecords= $this->unitRepository->getAllImages($unitId);
        // dd($oldRecords, $oldImages);
        if ($oldRecords) {
            $ids= [];
            foreach ($oldRecords as $row) {
                if (($row->image ?? null) && !in_array($row->image, $oldImages)) {
                    $ids[]= $row->id;
                    UploadService::delete($row->image);
                }elseif(!$row->image){
                    $ids[]= $row->id;
                }
            }
            // dd($ids);
            if ($ids) {
                // DELETE records
                $this->unitRepository->deleteAllImages($ids);
            }
        }
    }
}
