<?php
require "../config/database.php";
require "../includes/auth.php";
require "../includes/csrf.php";

error_reporting(0);

header("Content-Type: application/json; charset=utf-8");
requireApiAuth();

$userId = (int)$_SESSION["user"]["id"];
$method = $_SERVER["REQUEST_METHOD"] ?? "GET";

if ($method === "POST") {
    $data = json_decode(file_get_contents("php://input"), true);
    if (!is_array($data)) {
        http_response_code(400);
        echo json_encode(["success" => false, "error" => "invalid_payload"]);
        exit;
    }

    if (!requireCsrfFromPayload($data, "csrf")) {
        http_response_code(403);
        echo json_encode(["success" => false, "error" => "invalid_csrf"]);
        exit;
    }

    $notificationId = (int)($data["notification_id"] ?? 0);
    if ($notificationId <= 0) {
        http_response_code(422);
        echo json_encode(["success" => false, "error" => "notification_id_required"]);
        exit;
    }

    $stmt = $pdo->prepare("UPDATE notifications SET is_read = 1, read_at = NOW() WHERE id = ? AND receiver_id = ?");
    $stmt->execute([$notificationId, $userId]);

    echo json_encode(["success" => true]);
    exit;
}

$unreadMessagesStmt = $pdo->prepare("SELECT COUNT(*) FROM messages WHERE receiver_id = ? AND status = 'unread'");
$unreadMessagesStmt->execute([$userId]);
$unreadMessages = (int)$unreadMessagesStmt->fetchColumn();

$listStmt = $pdo->prepare("
    SELECT n.id, n.type, n.message, n.is_read, n.created_at, u.email AS sender_email
    FROM notifications n
    LEFT JOIN users u ON u.id = n.sender_id
    WHERE n.receiver_id = ?
    ORDER BY n.id DESC
    LIMIT 50
");
$listStmt->execute([$userId]);
$notifications = $listStmt->fetchAll(PDO::FETCH_ASSOC);

$unreadNotificationsStmt = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE receiver_id = ? AND is_read = 0");
$unreadNotificationsStmt->execute([$userId]);
$unreadNotifications = (int)$unreadNotificationsStmt->fetchColumn();

echo json_encode([
    "success" => true,
    "data" => [
        "unread_messages" => $unreadMessages,
        "unread_notifications" => $unreadNotifications,
        "notifications" => $notifications
    ]
]);
