<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Permission;
use App\Models\AlertTask;
use App\Services\AlertTaskService;

final class AlertController extends Controller
{
    private function org():int{return (int)(Auth::user()['organisation_id']??1);}
    private function manage():bool{return Permission::canAny('alerts.manage','utilisateurs.view','professeurs.pro.view');}

    public function index():void
    {
        Auth::requireLogin();(new AlertTaskService())->synchronize($this->org());$user=(int)Auth::id();
        $this->view('alerts/index',['pageTitle'=>'Alertes et tâches','tasks'=>AlertTask::listing($this->org(),$user,$this->manage()),'preference'=>AlertTask::preference($user),'canManage'=>$this->manage()]);
    }

    public function complete():void
    {
        Auth::requireLogin();Csrf::verify($_POST['_csrf']??null);AlertTask::complete((int)($_POST['id']??0),$this->org(),(int)Auth::id(),$this->manage());$_SESSION['success']='Tâche marquée comme terminée.';$this->redirect('/alertes');
    }

    public function preference():void
    {
        Auth::requireLogin();Csrf::verify($_POST['_csrf']??null);AlertTask::savePreference((int)Auth::id(),isset($_POST['daily_email_enabled']),(int)($_POST['digest_hour']??8));$_SESSION['success']='Préférences de rappel enregistrées.';$this->redirect('/alertes');
    }

    public function cron():void
    {
        $expected=(string)($_ENV['ALERT_CRON_TOKEN']??'');$provided=(string)($_GET['token']??'');
        if($expected===''||!hash_equals($expected,$provided)){http_response_code(403);exit('Accès refusé.');}
        $service=new AlertTaskService();
        $organisations=\App\Core\Database::connection()->query('SELECT id FROM organisations')->fetchAll(\PDO::FETCH_COLUMN)?:[];
        foreach($organisations as $org)$service->synchronize((int)$org);
        header('Content-Type: application/json; charset=UTF-8');echo json_encode(['status'=>'ok','digests'=>$service->sendDailyDigests()],JSON_UNESCAPED_UNICODE);exit;
    }
}
