<?php
require_once __DIR__ . '/../Core.php';

class ContactTask extends Model
{
    public function forContact(int $contactId): array
    {
        $stmt = $this->db->prepare('SELECT t.*, u.name AS assigned_user_name, cu.name AS created_by_name FROM contact_tasks t LEFT JOIN users u ON u.id = t.assigned_user_id LEFT JOIN users cu ON cu.id = t.created_by WHERE t.contact_id = ? ORDER BY FIELD(t.status, "open", "done"), t.due_at IS NULL, t.due_at ASC, t.id DESC');
        $stmt->execute([$contactId]);
        return $stmt->fetchAll();
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare('INSERT INTO contact_tasks (contact_id, title, due_at, status, assigned_user_id, created_by) VALUES (?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            (int)$data['contact_id'],
            trim((string)($data['title'] ?? 'Follow up')),
            trim((string)($data['due_at'] ?? '')) ?: null,
            $data['status'] ?? 'open',
            (int)($data['assigned_user_id'] ?? 0) ?: null,
            current_user()['id'] ?? null,
        ]);
        return (int)$this->db->lastInsertId();
    }

    public function markDone(int $id): void
    {
        $stmt = $this->db->prepare('UPDATE contact_tasks SET status = "done" WHERE id = ?');
        $stmt->execute([$id]);
    }
}
