<?php

namespace Modules\Project\Services;

use Modules\Project\Interfaces\ProjectRepositoryInterface;
use Modules\Project\Models\Project;
use Modules\Project\Models\ProjectPhoto;

class ProjectService
{
    public function __construct(private ProjectRepositoryInterface $projectRepository)
    {
    }

    public function get(array $request = [])
    {
        $builder = $this->projectRepository->get($request);

        // Eager load photos for web display
        $builder->with('photos');

        if (!empty($request['title'])) {
            $builder->where('pd.title', 'LIKE', '%' . $request['title'] . '%');
        }
        if (!empty($request['category_id'])) {
            $builder->where('projects.category_id', $request['category_id']);
        }
        if (!empty($request['city_id'])) {
            $builder->where('projects.city_id', $request['city_id']);
        }
        if (!empty($request['area_id'])) {
            $builder->where('projects.area_id', $request['area_id']);
        }
        if (!empty($request['date_from'])) {
            $builder->whereDate('projects.created_at', '>=', $request['date_from']);
        }
        if (!empty($request['date_to'])) {
            $builder->whereDate('projects.created_at', '<=', $request['date_to']);
        }
        if (!empty($request['project_date'])) {
            $builder->whereDate('projects.project_date', $request['project_date']);
        }
        if (isset($request['status']) && (int) $request['status'] === 0) {
            $builder->onlyTrashed();
        }

        if (!empty($request['orderBy'])) {
            $orderKey = $request['orderBy']['key'];
            if (!str_contains($orderKey, '.')) {
                $orderKey = 'projects.' . $orderKey;
            }
            $builder->orderBy($orderKey, $request['orderBy']['value']);
        } else {
            $builder->orderBy('projects.id', 'DESC');
        }

        return !empty($request['paginate']) ? $builder->paginate(50) : $builder->cursor();
    }

    public function checkItem(int $id)
    {
        return $this->projectRepository->checkItem($id);
    }

    public function getItem(int $id)
    {
        $project = $this->checkItem($id);
        if (!$project) {
            return null;
        }

        $descriptions = $this->projectRepository->getItem($id);
        foreach ($descriptions as $row) {
            $project[$row->local] = $row;
        }

        return $project;
    }

    public function getItemTrashed(int $id)
    {
        return $this->projectRepository->getItemTrashed($id);
    }

    public function create(array $request): Project
    {
        $project = $this->projectRepository->create($request);
        $this->projectRepository->saveData($request, $project->id);

        // Handle photos upload
        if (isset($request['photos']) && is_array($request['photos'])) {
            $this->handlePhotosUpload($project->id, $request['photos']);
        }

        return $project;
    }

    public function update(array $request, int $id): ?Project
    {
        $project = $this->checkItem($id);
        if (!$project) {
            return null;
        }

        $project = $this->projectRepository->update($request, $project);
        $this->projectRepository->saveData($request, $project->id);

        // Handle photos deletion
        if (isset($request['photos_to_delete']) && is_array($request['photos_to_delete'])) {
            $this->handlePhotosDeletion($request['photos_to_delete']);
        }

        // Handle photos upload
        if (isset($request['photos']) && is_array($request['photos'])) {
            $this->handlePhotosUpload($project->id, $request['photos']);
        }

        return $project;
    }

    public function destroy(int $id): void
    {
        $project = $this->checkItem($id);
        if ($project) {
            $this->projectRepository->destroy($project);
            return;
        }

        $trashed = $this->getItemTrashed($id);
        if ($trashed) {
            $this->projectRepository->restore($trashed);
        }
    }

    public function destroyAll(array $request): void
    {
        if ($request['status'] == 1) {
            $this->projectRepository->destroyAll($request['ids']);
        } else {
            $this->projectRepository->restoreAll($request['ids']);
        }

    }

    /**
     * Handle photos upload for a project
     */
    private function handlePhotosUpload(int $projectId, array $photos): void
    {
        $sortOrder = ProjectPhoto::where('project_id', $projectId)->max('sort_order') ?? 0;

        foreach ($photos as $photo) {
            $sortOrder++;
            ProjectPhoto::create([
                'project_id' => $projectId,
                'image' => $photo,
                'sort_order' => $sortOrder,
            ]);
        }
    }

    /**
     * Handle photos deletion
     */
    private function handlePhotosDeletion(array $photoIds): void
    {
        ProjectPhoto::whereIn('id', $photoIds)->delete();
    }
}
