<?php
require_once __DIR__ . '/utils/response.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/controllers/AuthController.php';
require_once __DIR__ . '/controllers/NotificationController.php';

// Mock AuthController::authenticateRequest to return user 19 (test6)
class MockAuthController {
    public static function authenticateRequest() {
        return ['id' => 19, 'email' => 't6@gmail.com'];
    }
}

// Override the real AuthController used in NotificationController if possible
// Since we can't easily override static classes in PHP without extensions, 
// I will temporarily modify NotificationController to use a passed ID or just manually run the logic here.

$userId = 19;
$db = getDb();

$page  = 1;
$limit = 20;
$offset = 0;

// Fetch notifications with read status
$stmt = $db->prepare(
    "SELECT 
        un.id as user_notif_id,
        un.notification_id,
        COALESCE(n.title, un.title, 'Notification') as title,
        COALESCE(n.message, un.message) as message,
        COALESCE(n.created_at, un.created_at) as created_at,
        un.is_read,
        un.read_at
     FROM user_notifications un
     LEFT JOIN notifications n ON n.id = un.notification_id
     WHERE un.user_id = ?
     ORDER BY created_at DESC
     LIMIT ? OFFSET ?"
);
$stmt->bind_param("iii", $userId, $limit, $offset);
$stmt->execute();
$result = $stmt->get_result();

$notifications = [];
while ($row = $result->fetch_assoc()) {
    $row['is_read'] = (bool)$row['is_read'];
    $row['id'] = $row['notification_id'] ?? $row['user_notif_id'];
    $notifications[] = $row;
}
$stmt->close();

header('Content-Type: application/json');
echo json_encode([
    'status' => 'success',
    'data' => [
        'notifications' => $notifications,
        'total' => count($notifications)
    ]
], JSON_PRETTY_PRINT);
?>
