<?php
/**
 * Mark Notification as Read API
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

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

if (session_status() === PHP_SESSION_NONE) session_start();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonError('Method not allowed', 405);
}

if (!isset($_SESSION['user_id'])) {
    jsonError('Not authenticated', 401);
}

$userId = $_SESSION['user_id'];
$data = json_decode(file_get_contents('php://input'), true);

$notificationId = $data['notification_id'] ?? null;
$markAll = $data['mark_all'] ?? false;

try {
    if ($markAll) {
        dbQuery(
            "UPDATE push_notifications SET is_read = 1 WHERE user_id = ? AND is_read = 0",
            [$userId]
        );
        jsonSuccess('All notifications marked as read');
    } elseif ($notificationId) {
        dbQuery(
            "UPDATE push_notifications SET is_read = 1 WHERE id = ? AND user_id = ?",
            [$notificationId, $userId]
        );
        jsonSuccess('Notification marked as read');
    } else {
        jsonError('Notification ID or mark_all flag required');
    }

} catch (Exception $e) {
    error_log("Mark Read Error: " . $e->getMessage());
    jsonError('Failed to mark notification');
}
