<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Database;
use Throwable;

final class AlertTask
{
    public static function unreadCount(int $userId): int
    {
        try {
            $q=Database::connection()->prepare("SELECT COUNT(*) FROM cda_alert_tasks WHERE assigned_user_id=? AND status='open'");
            $q->execute([$userId]);
            return (int)$q->fetchColumn();
        } catch (Throwable) {
            return 0;
        }
    }

    public static function listing(int $organisationId,int $userId,bool $all): array
    {
        $sql="SELECT a.*,u.nom assigned_nom,u.prenom assigned_prenom,u.email assigned_email
              FROM cda_alert_tasks a JOIN utilisateurs u ON u.id=a.assigned_user_id
              WHERE a.organisation_id=?".($all?'':' AND a.assigned_user_id=?')."
              ORDER BY a.status='open' DESC,FIELD(a.priority,'urgent','high','normal','low'),a.due_at IS NULL,a.due_at,a.created_at DESC";
        $q=Database::connection()->prepare($sql);
        $q->execute($all?[$organisationId]:[$organisationId,$userId]);
        return $q->fetchAll()?:[];
    }

    public static function preference(int $userId): array
    {
        $q=Database::connection()->prepare('SELECT * FROM cda_alert_preferences WHERE user_id=?');
        $q->execute([$userId]);
        return $q->fetch()?:['user_id'=>$userId,'daily_email_enabled'=>1,'digest_hour'=>8];
    }

    public static function savePreference(int $userId,bool $enabled,int $hour): void
    {
        $hour=max(0,min(23,$hour));
        Database::connection()->prepare('INSERT INTO cda_alert_preferences(user_id,daily_email_enabled,digest_hour) VALUES(?,?,?) ON DUPLICATE KEY UPDATE daily_email_enabled=VALUES(daily_email_enabled),digest_hour=VALUES(digest_hour)')->execute([$userId,$enabled?1:0,$hour]);
    }

    public static function complete(int $id,int $organisationId,int $userId,bool $canManage): void
    {
        $sql="UPDATE cda_alert_tasks SET status='completed',completed_at=NOW(),completed_by=? WHERE id=? AND organisation_id=? AND status='open'".($canManage?'':' AND assigned_user_id=?');
        $args=[$userId,$id,$organisationId];if(!$canManage)$args[]=$userId;
        $q=Database::connection()->prepare($sql);$q->execute($args);
        if($q->rowCount()===0)throw new \RuntimeException('Alerte introuvable, déjà terminée ou non autorisée.');
    }
}
