<?php
require_once '../../autoload.php';
header('Content-Type: application/json; charset=utf-8');
$conn = get_dbconnection();
$use_id = $_SESSION['id'];
$out = array();
$out['status'] = 'KO';
if($conn)
{
    // Validation stricte : stu_id doit être un entier positif
    $raw_stuid = $_REQUEST['stuid'] ?? '';
    if(!preg_match('/^\d+$/', $raw_stuid) || intval($raw_stuid) <= 0)
    {
        echo json_encode($out);
        exit();
    }
    $stu_id = intval($raw_stuid);

    // Validation de use_id (issu de la session, mais défense en profondeur)
    $use_id = intval($use_id);
    if($use_id <= 0)
    {
        echo json_encode($out);
        exit();
    }

    $comment = $_REQUEST['comment'] ?? '';

    if($comment != '')
    {
        // Insertion du commentaire avec paramètres liés
        $query = pg_query_params($conn,
            "INSERT INTO ackalert(comment, user_id, validated, stu_id) VALUES ($1, $2, true, $3) RETURNING id",
            array($comment, $use_id, $stu_id)
        );

        if($query && $row = pg_fetch_row($query))
        {
            $ack_id = intval($row[0]);

            // Désactivation des anciens acks
            $q1 = pg_query_params($conn,
                "UPDATE ackalert SET removed = true WHERE id IN (SELECT ack_id FROM alertwarning WHERE stu_id = $1 AND removed = false)",
                array($stu_id)
            );

            // Rattachement du nouvel ack
            $q2 = pg_query_params($conn,
                "UPDATE alertwarning SET ack_id = $1 WHERE stu_id = $2 AND removed = false",
                array($ack_id, $stu_id)
            );

            if($q1 && $q2)
            {
                pg_query($conn, "COMMIT");
                $out['status'] = 'OK';
            }
        }
    }
    else
    {
        // Suppression de l'ack existant
        $q1 = pg_query_params($conn,
            "UPDATE ackalert SET removed = true WHERE id IN (SELECT ack_id FROM alertwarning WHERE stu_id = $1 AND removed = false)",
            array($stu_id)
        );

        $q2 = pg_query_params($conn,
            "UPDATE alertwarning SET ack_id = null WHERE stu_id = $1 AND removed = false",
            array($stu_id)
        );

        if($q1 && $q2)
        {
            pg_query($conn, "COMMIT");
            $out['status'] = 'OK';
        }
    }
}
echo json_encode($out);
?>