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

class Reminder extends Model
{
    public function upcoming(int $limit = 25): array
    {
        $stmt = $this->db->prepare('SELECT r.*, c.first_name, c.last_name, u.name AS assigned_user_name FROM reminders r LEFT JOIN contacts c ON c.id = r.contact_id LEFT JOIN users u ON u.id = r.assigned_user_id WHERE r.status = "open" ORDER BY r.remind_at IS NULL, r.remind_at ASC, r.id DESC LIMIT ?');
        $stmt->bindValue(1, $limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public function forContact(int $contactId): array
    {
        $stmt = $this->db->prepare('SELECT r.*, u.name AS assigned_user_name FROM reminders r LEFT JOIN users u ON u.id = r.assigned_user_id WHERE r.contact_id = ? ORDER BY r.status = "done", r.remind_at IS NULL, r.remind_at ASC, r.id DESC');
        $stmt->execute([$contactId]);
        return $stmt->fetchAll();
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare('INSERT INTO reminders (contact_id, title, remind_at, status, assigned_user_id, created_by) VALUES (?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            (int)($data['contact_id'] ?? 0),
            trim((string)($data['title'] ?? 'Reminder')),
            trim((string)($data['remind_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 reminders SET status = "done" WHERE id = ?');
        $stmt->execute([$id]);
    }
}
