<?php
// Guard and session
define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/Database.php';
require_once __DIR__ . '/Notification.php';
require_once __DIR__ . '/middleware/SecurityMiddleware.php';

// Set headers
header('Content-Type: application/json');
// Dynamic origin for credentials
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) {
    header('Access-Control-Allow-Origin: ' . $origin);
} else {
    $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if (!empty($host)) {
        header('Access-Control-Allow-Origin: ' . $scheme . '://' . $host);
    }
}
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-Requested-With, X-API-KEY');
header('Access-Control-Allow-Credentials: true');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Initialize database connection
try {
    $pdo = Database::getInstance()->getConnection();
    $notification = new Notification($pdo);
    
    // Check if request method is POST
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Method not allowed', 405);
    }
    
    // Require authentication
    requireLogin(true);
    
    // Get request data
    $data = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    $requiredFields = ['user_id', 'notification_id'];
    foreach ($requiredFields as $field) {
        if (!isset($data[$field])) {
            throw new Exception("Missing required field: $field", 400);
        }
    }
    
    // Use session user_id unless admin specifies a user_id for impersonation
    $sessionUserId = $_SESSION['user_id'] ?? null;
    if (!$sessionUserId) {
        throw new Exception('User session required', 401);
    }
    $targetUserId = $sessionUserId;
    if (isset($data['user_id']) && isUserAdmin()) {
        $targetUserId = (int)$data['user_id'];
    }
    
    // Mark notification as read
    $success = $notification->markAsRead((int)$data['notification_id'], (int)$targetUserId);
    
    if (!$success) {
        throw new Exception('Failed to mark notification as read', 500);
    }
    
    // Get updated unread count
    $unreadCount = $notification->getUnreadCount((int)$targetUserId);
    
    // Return success response
    echo json_encode([
        'success' => true,
        'message' => 'Notification marked as read',
        'unread_count' => $unreadCount
    ]);
    
} catch (Exception $e) {
    http_response_code($e->getCode() ?: 500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'code' => $e->getCode()
    ]);
}
