<?php
require_once '../config/config.php';
require_once '../includes/user_auth.php';

if (!$auth->isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$db = Database::getInstance()->connect();
$user_id = $auth->getCurrentUserId();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Mark notifications as read
    $action = $_POST['action'] ?? '';
    if ($action === 'mark_read') {
        $stmt = $db->prepare("UPDATE notifications SET is_read = 1 WHERE user_id = ? AND is_read = 0");
        $stmt->execute([$user_id]);
        echo json_encode(['success' => true]);
        exit();
    }
} else {
    // Fetch unread notifications
    $count_stmt = $db->prepare("SELECT COUNT(*) as unread_count FROM notifications WHERE user_id = ? AND is_read = 0");
    $count_stmt->execute([$user_id]);
    $unread_count = $count_stmt->fetchColumn();

    $list_stmt = $db->prepare("SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 5");
    $list_stmt->execute([$user_id]);
    $notifications = $list_stmt->fetchAll();

    $html = '';
    if (empty($notifications)) {
        $html = '<p class="text-center text-gray-500 text-sm p-4">No notifications yet.</p>';
    } else {
        foreach ($notifications as $notification) {
            $icon = 'fa-info-circle';
            $color = 'blue';
            switch ($notification['type']) {
                case 'success': case 'profit': case 'deposit_approved':
                    $icon = 'fa-check-circle'; $color = 'green'; break;
                case 'error':
                    $icon = 'fa-exclamation-circle'; $color = 'red'; break;
                case 'warning':
                    $icon = 'fa-exclamation-triangle'; $color = 'yellow'; break;
            }
            $read_class = $notification['is_read'] ? 'opacity-60' : 'bg-'.$color.'-50';
            $html .= '<div class="p-3 rounded-lg hover:bg-gray-100 ' . $read_class . '"><div class="flex items-start space-x-3">';
            $html .= '<i class="fas ' . $icon . ' text-'.$color.'-500 mt-1"></i>';
            $html .= '<div><p class="text-sm font-semibold">' . htmlspecialchars($notification['title']) . '</p>';
            $html .= '<p class="text-sm text-gray-600">' . htmlspecialchars($notification['message']) . '</p>';
            $html .= '<p class="text-xs text-gray-400 mt-1">' . date('M d, Y H:i', strtotime($notification['created_at'])) . '</p></div></div></div>';
        }
        $html .= '<div class="mt-3 pt-3 border-t text-center"><a href="'.SITE_URL.'/user/notifications.php" class="text-sm text-purple-600 hover:text-purple-800">View All Notifications</a></div>';
    }

    echo json_encode([
        'success' => true,
        'unread_count' => $unread_count,
        'html' => $html
    ]);
}
?>