<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * Contact Model
 *
 * Handles contact form submissions with unread tracking
 * and recent message retrieval for the admin panel.
 */
class Contact extends Model
{
    /**
     * The database table associated with the model.
     */
    protected string $table = 'contacts';

    /**
     * Get all unread contact messages.
     *
     * @return array<int, array<string, mixed>> Array of unread contact records
     */
    public function getUnread(): array
    {
        $sql = sprintf(
            'SELECT * FROM `%s` WHERE `is_read` = :is_read ORDER BY `created_at` DESC',
            $this->table
        );

        $stmt = $this->db->prepare($sql);
        $stmt->execute([':is_read' => 0]);

        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    /**
     * Mark a contact message as read.
     *
     * @param int $id The contact message ID
     * @return bool True if the update affected at least one row
     */
    public function markRead(int $id): bool
    {
        return $this->update($id, ['is_read' => 1]);
    }

    /**
     * Get the most recent contact messages.
     *
     * @param int $limit Maximum number of messages to return
     * @return array<int, array<string, mixed>> Array of recent contact records
     */
    public function getRecent(int $limit = 5): array
    {
        $sql = sprintf(
            'SELECT * FROM `%s` ORDER BY `created_at` DESC LIMIT :limit',
            $this->table
        );

        $stmt = $this->db->prepare($sql);
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
}
