<?php

ini_set('display_errors', 0);
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);

session_start();

require_once __DIR__ . '/../core/functions.php';
require_once __DIR__ . '/../services/UserAlertService.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: ../public/login.php');
    exit;
}

$userId = (int)$_SESSION['user_id'];
$alertId = (int)($_POST['alert_id'] ?? $_GET['id'] ?? 0);
$action = strtolower(trim((string)($_POST['action'] ?? $_GET['action'] ?? '')));

$returnTo = $_SERVER['HTTP_REFERER'] ?? 'my_alerts.php';

if ($alertId <= 0 || $action === '') {
    header('Location: ' . $returnTo);
    exit;
}

try {
    if ($action === 'pause') {
        db()->prepare("
            UPDATE institutional_alerts
            SET is_active = 0,
                updated_at = NOW()
            WHERE id = ?
              AND user_id = ?
        ")->execute([$alertId, $userId]);

        $_SESSION['alert_action_message'] = 'Alert paused successfully.';
    } elseif ($action === 'resume') {
        db()->prepare("
            UPDATE institutional_alerts
            SET is_active = 1,
                triggered_at = NULL,
                expired_at = NULL,
                expiration_reason = NULL,
                updated_at = NOW()
            WHERE id = ?
              AND user_id = ?
        ")->execute([$alertId, $userId]);

        $_SESSION['alert_action_message'] = 'Alert resumed successfully.';
    } elseif ($action === 'delete') {
        UserAlertService::deleteAlert($alertId, $userId);
        $_SESSION['alert_action_message'] = 'Tracked setup deleted.';
    }
} catch (Throwable $e) {
    $_SESSION['alert_action_error'] = 'Action could not be completed.';
}

header('Location: ' . $returnTo);
exit;
