<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\BaseModel;

final class TaskModel extends BaseModel
{
    protected string $table = 'lead_tasks';
    protected array $fillable = ['lead_id', 'title', 'due_at', 'assigned_to', 'is_completed', 'completed_at'];
    protected bool $timestamps = true;
    protected bool $softDeletes = false;
    protected bool $auditStamps = false;

    public function forLead(int $leadId): array
    {
        $stmt = $this->db->prepare(
            "SELECT t.*, CONCAT(u.first_name, ' ', u.last_name) AS assigned_to_name
             FROM lead_tasks t
             LEFT JOIN users u ON u.id = t.assigned_to
             WHERE t.lead_id = :id
             ORDER BY t.is_completed, t.due_at IS NULL, t.due_at"
        );
        $stmt->execute(['id' => $leadId]);

        return $stmt->fetchAll();
    }

    public function toggleComplete(int $taskId, bool $completed): bool
    {
        $stmt = $this->db->prepare(
            'UPDATE lead_tasks SET is_completed = :done, completed_at = :completed_at WHERE id = :id'
        );

        return $stmt->execute([
            'done' => $completed ? 1 : 0,
            'completed_at' => $completed ? date('Y-m-d H:i:s') : null,
            'id' => $taskId,
        ]);
    }

    /** Tasks due within the next N hours, not yet completed — for a "My Tasks" widget. */
    public function upcomingFor(int $userId, int $withinHours = 48): array
    {
        $stmt = $this->db->prepare(
            "SELECT t.*, CONCAT(l.first_name, ' ', l.last_name) AS lead_name
             FROM lead_tasks t
             JOIN leads l ON l.id = t.lead_id AND l.deleted_at IS NULL
             WHERE t.assigned_to = :user AND t.is_completed = 0
               AND (t.due_at IS NULL OR t.due_at <= DATE_ADD(NOW(), INTERVAL :hours HOUR))
             ORDER BY t.due_at IS NULL, t.due_at"
        );
        $stmt->execute(['user' => $userId, 'hours' => $withinHours]);

        return $stmt->fetchAll();
    }
}
