<?php
// Define guard and include 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 to support 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: GET, 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 GET
    if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
        throw new Exception('Method not allowed', 405);
    }
    
    // Require authentication
    requireLogin(true);
    
    // Determine user ID: default to session user; admin may impersonate via ?user_id=
    $userId = $_SESSION['user_id'] ?? null;
    if (isset($_GET['user_id']) && isUserAdmin()) {
        $userId = (int)$_GET['user_id'];
    }
    if (!$userId) {
        throw new Exception('User ID not found in session', 401);
    }
    
    // Get pagination parameters
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $offset = ($page - 1) * $limit;
    
    // Get notifications
    $notifications = $notification->getByUserId($userId, $limit, $offset);
    $unreadCount = $notification->getUnreadCount($userId);
    
    // Return success response
    echo json_encode([
        'success' => true,
        'data' => [
            'notifications' => $notifications,
            'unread_count' => $unreadCount,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => count($notifications)
            ]
        ]
    ]);
    
} catch (Exception $e) {
    http_response_code($e->getCode() ?: 500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'code' => $e->getCode()
    ]);
}
