<?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/AlertService.php';

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

$userId = (int)$_SESSION['user_id'];
$returnTo = trim((string)($_POST['return_to'] ?? 'dashboard.php'));

try {
    $payload = $_POST;

    $payload['auto_expire_enabled'] = !empty($_POST['auto_expire_enabled']) ? 1 : 0;
    $payload['expiration_option'] = trim((string)($_POST['expiration_option'] ?? 'never'));

    $result = AlertService::saveTrackedSetup($userId, $payload);

    if (!empty($result['ok'])) {
        $_SESSION['setup_alert_state'] = 'success';
        $_SESSION['setup_alert_message'] = $result['message'] ?? 'Alert tracking activated.';
    } else {
        $_SESSION['setup_alert_state'] = 'error';
        $_SESSION['setup_alert_message'] = $result['message'] ?? 'Alert tracking could not be activated.';
    }
} catch (Throwable $e) {
    error_log('[save_alert] ' . $e->getMessage());

    $_SESSION['setup_alert_state'] = 'error';
    $_SESSION['setup_alert_message'] = 'Alert tracking could not be activated. Please check your alert settings.';
}

if ($returnTo === '' || str_starts_with($returnTo, 'http://') || str_starts_with($returnTo, 'https://')) {
    $returnTo = 'dashboard.php';
}

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