<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

require_once __DIR__ . '/../../database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    // في نظام حقيقي، نأخذ user_id من الجلسة
    $user_id = $_GET['user_id'] ?? 1;
    
    $query = "SELECT 
                id,
                type,
                title,
                message,
                data,
                is_read,
                created_at
              FROM notifications
              WHERE user_id = :user_id
              ORDER BY created_at DESC
              LIMIT 20";
    
    $stmt = $db->prepare($query);
    $stmt->execute(['user_id' => $user_id]);
    
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // حساب عدد غير المقروءة
    $unreadQuery = "SELECT COUNT(*) as unread_count FROM notifications WHERE user_id = :user_id AND is_read = 0";
    $unreadStmt = $db->prepare($unreadQuery);
    $unreadStmt->execute(['user_id' => $user_id]);
    $unread = $unreadStmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $notifications,
        'unread_count' => $unread['unread_count'] ?? 0
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>