<?php
session_start();

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

require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

$customerId = (int)$_SESSION['customer_id'];
$notificationId = (int)($_GET['id'] ?? 0);

if ($notificationId <= 0) {
    header('Location: notifications.php');
    exit;
}

$stmt = $db->prepare("
    SELECT *
    FROM notifications
    WHERE id = :id
      AND customer_id = :customer_id
    LIMIT 1
");
$stmt->execute([
    ':id' => $notificationId,
    ':customer_id' => $customerId
]);

$notification = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$notification) {
    header('Location: notifications.php');
    exit;
}

// Mark as read
$update = $db->prepare("
    UPDATE notifications
    SET is_read = 1,
        read_at = COALESCE(read_at, NOW())
    WHERE id = :id
      AND customer_id = :customer_id
");
$update->execute([
    ':id' => $notificationId,
    ':customer_id' => $customerId
]);

$link = trim((string)($notification['link'] ?? ''));

if ($link === '' || $link === '#') {
    header('Location: notifications.php');
    exit;
}

// Normalize old links
$link = str_replace('/customer/', '', $link);

// Allow only safe customer portal pages
$allowedPages = [
    'dashboard.php',
    'request.php',
    'my_requests.php',
    'messages.php',
    'profile.php',
    'notifications.php',
    'request_details.php'
];

$parsed = parse_url($link);
$path = basename($parsed['path'] ?? '');
$query = isset($parsed['query']) ? ('?' . $parsed['query']) : '';

if (!in_array($path, $allowedPages, true)) {
    header('Location: notifications.php');
    exit;
}

// Convert request_details.php?id=123 to my_requests.php?request_id=123
if ($path === 'request_details.php') {
    parse_str($parsed['query'] ?? '', $queryParams);
    $requestId = (int)($queryParams['id'] ?? 0);

    if ($requestId > 0) {
        header('Location: my_requests.php?request_id=' . $requestId);
        exit;
    }

    header('Location: my_requests.php');
    exit;
}

header('Location: ' . $path . $query);
exit;