<?php

namespace App\Repositories;

use App\Models\Task;
use App\Support\IdFormatter;

class TaskRepository extends BaseRepository
{
    protected $model;

    public function __construct()
    {
        $this->model = new Task();
    }

    public function getAllByOrganization(?string $orgHex)
    {
        $query = $this->model->query()->with(['createdBy', 'assignedTo']);
        return $this->applyOrganizationScope($query, $orgHex)->orderByDesc('created_at')->get();
    }

    public function getByIdInOrganization(string $id, ?string $orgHex)
    {
        $query = $this->model->where('id', $this->normalizeId($id));
        return $this->applyOrganizationScope($query, $orgHex)->first();
    }

    public function create(array $data)
    {
        return $this->model->create($data);
    }

    public function updateInOrganization(string $id, array $data, ?string $orgHex)
    {
        $query = $this->model->where('id', $this->normalizeId($id));
        $task = $this->applyOrganizationScope($query, $orgHex)->first();

        if ($task) {
            $task->update($data);
        }

        return $task;
    }

    public function deleteInOrganization(string $id, ?string $orgHex)
    {
        $query = $this->model->where('id', $this->normalizeId($id));
        return $this->applyOrganizationScope($query, $orgHex)->delete();
    }

    public function paginateByOrganization(?string $orgHex, array $filters = [], int $perPage = 10)
    {
        $safePerPage = max(1, min(100, $perPage));

        $query = $this->model->query()->with(['createdBy', 'assignedTo']);
        $query = $this->applyOrganizationScope($query, $orgHex);

        $status = $filters['status'] ?? null;
        if ($status && in_array($status, ['todo', 'in_progress', 'done', 'cancelled'])) {
            $query->where('status', $status);
        }

        $priority = $filters['priority'] ?? null;
        if ($priority && in_array($priority, ['low', 'medium', 'high'])) {
            $query->where('priority', $priority);
        }

        $assignedTo = $filters['assigned_to'] ?? null;
        if ($assignedTo) {
            $query->where('assigned_to', $this->normalizeId($assignedTo));
        }

        $keyword = trim((string)($filters['keyword'] ?? ''));
        if ($keyword !== '') {
            $like = '%' . $keyword . '%';
            $query->where(function ($q) use ($like) {
                $q->where('title', 'LIKE', $like)
                    ->orWhere('description', 'LIKE', $like);
            });
        }

        $createdBy = $filters['created_by'] ?? null;
        if ($createdBy) {
            $query->where('created_by', $this->normalizeId($createdBy));
        }

        $createdAt = $filters['created_at'] ?? null;
        if ($createdAt) {
            $query->whereDate('created_at', '>=', $createdAt);
        }

        $dueAt = $filters['due_at'] ?? null;
        if ($dueAt) {
            $query->whereDate('due_at', '>=', $dueAt);
        }

        // Lọc theo quyền xem: nếu task có access = 'assigned',
        // chỉ hiển thị cho người tạo và người được giao
        $currentUser = auth()->user();
        if ($currentUser && !$currentUser->hasRole('owner')) {
            $query->where(function ($q) use ($currentUser) {
                $q->where('access', 'organization')
                    ->orWhere(function ($q) use ($currentUser) {
                        $q->where('access', 'assigned')
                            ->where(function ($q) use ($currentUser) {
                                $q->where('created_by', $currentUser->id)
                                    ->orWhere('assigned_to', $currentUser->id);
                            });
                    });
            });
        }

        $query->orderByDesc('created_at');

        return $query->paginate($safePerPage);
    }
}
