<?php
namespace EasyChat\Model;

class ManagerNoticeState extends Base {

    public function get(int $manager_id, string $notice_key): array {
        $query = $this->db->query(
            "SELECT `notice_key`, `subject`, `snoozed_until`, `dismissed_at`, `updated_at`,
                    (`snoozed_until` IS NOT NULL AND `snoozed_until` > NOW()) AS `is_snoozed`
             FROM `{$this->prefix}manager_notice_state`
             WHERE `manager_id` = " . (int)$manager_id . "
               AND `notice_key` = '" . $this->db->escape($this->normalizeKey($notice_key)) . "'
             LIMIT 1"
        );
        return $query->row ?: [];
    }

    public function snooze(int $manager_id, string $notice_key, string $subject, int $days = 7): void {
        $days = max(1, min(30, $days));
        $this->upsert($manager_id, $notice_key, $subject, "DATE_ADD(NOW(), INTERVAL {$days} DAY)", 'NULL');
    }

    public function dismissRelease(int $manager_id, string $notice_key, string $subject): void {
        $this->upsert($manager_id, $notice_key, $subject, 'NULL', 'NOW()');
    }

    private function upsert(int $manager_id, string $notice_key, string $subject, string $snoozed_until_sql, string $dismissed_at_sql): void {
        $notice_key = $this->normalizeKey($notice_key);
        $subject = mb_substr(trim($subject), 0, 64, 'UTF-8');
        $this->db->query(
            "INSERT INTO `{$this->prefix}manager_notice_state`
             SET `manager_id` = " . (int)$manager_id . ",
                 `notice_key` = '" . $this->db->escape($notice_key) . "',
                 `subject` = '" . $this->db->escape($subject) . "',
                 `snoozed_until` = {$snoozed_until_sql},
                 `dismissed_at` = {$dismissed_at_sql},
                 `updated_at` = NOW()
             ON DUPLICATE KEY UPDATE
                 `subject` = VALUES(`subject`),
                 `snoozed_until` = VALUES(`snoozed_until`),
                 `dismissed_at` = VALUES(`dismissed_at`),
                 `updated_at` = NOW()"
        );
    }

    private function normalizeKey(string $notice_key): string {
        $notice_key = strtolower(trim($notice_key));
        return preg_match('/^[a-z0-9_.-]{1,64}$/D', $notice_key) ? $notice_key : 'invalid';
    }
}
