<?php
/**
 * Simple API endpoint to get notification count for navbar badge
 * Usage: GET api/get_notification_count.php?event_id=123&user_id=456
 */

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

// Basic database connection
$config_paths = [
    '../includes/config.php',
    '../includes/db.php',
    '../../includes/config.php',
    '../../includes/db.php'
];

$pdo = null;
foreach ($config_paths as $config_path) {
    if (file_exists($config_path)) {
        try {
            require_once $config_path;
            if (isset($pdo) && $pdo instanceof PDO) {
                break;
            }
        } catch (Exception $e) {
            continue;
        }
    }
}

// Fallback database connection
if (!$pdo) {
    $host = 'localhost';
    $dbname = 'pzls_livescore_398dsk';
    $username = 'root';
    $password = '';
    
    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        echo json_encode(['error' => 'Database connection failed', 'count' => 0]);
        exit;
    }
}

// Get parameters
$event_id = $_GET['event_id'] ?? null;
$user_id = $_GET['user_id'] ?? 'anonymous';
$since = $_GET['since'] ?? 0; // Only count notifications after this ID

try {
    if (!$event_id) {
        echo json_encode(['error' => 'Event ID required', 'count' => 0]);
        exit;
    }
    
    // Create tables if they don't exist
    createNotificationsTable($pdo);
    createNotificationReadsTable($pdo);
    
    // Count unread notifications for this user and event
    $sql = "
        SELECT COUNT(*) as unread_count
        FROM event_notifications n
        LEFT JOIN notification_reads nr ON n.id = nr.notification_id AND nr.user_id = ?
        WHERE n.event_id = ? 
        AND n.id > ?
        AND nr.id IS NULL
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$user_id, $event_id, $since]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $count = (int)($result['unread_count'] ?? 0);
    
    // Get latest notification ID for next poll
    $latest_stmt = $pdo->prepare("SELECT MAX(id) as latest_id FROM event_notifications WHERE event_id = ?");
    $latest_stmt->execute([$event_id]);
    $latest_result = $latest_stmt->fetch(PDO::FETCH_ASSOC);
    $latest_id = (int)($latest_result['latest_id'] ?? 0);
    
    echo json_encode([
        'success' => true,
        'count' => $count,
        'latest_id' => $latest_id,
        'event_id' => $event_id,
        'user_id' => $user_id
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'error' => 'Query failed: ' . $e->getMessage(),
        'count' => 0
    ]);
}

function createNotificationsTable($pdo) {
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS event_notifications (
                id INT AUTO_INCREMENT PRIMARY KEY,
                event_id INT NOT NULL,
                type ENUM('success', 'danger', 'warning', 'info') DEFAULT 'info',
                category ENUM('general', 'competition', 'participant', 'judge', 'system', 'heat', 'scoring', 'technical') DEFAULT 'general',
                title VARCHAR(255) NOT NULL,
                message TEXT,
                user_id VARCHAR(100) DEFAULT 'system',
                data JSON,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_event_created (event_id, created_at),
                INDEX idx_event_id (event_id),
                INDEX idx_category (category)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    } catch (PDOException $e) {
        // Ignore table creation errors
    }
}

function createNotificationReadsTable($pdo) {
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS notification_reads (
                id INT AUTO_INCREMENT PRIMARY KEY,
                notification_id INT NOT NULL,
                user_id VARCHAR(100) NOT NULL,
                read_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                UNIQUE KEY unique_read (notification_id, user_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    } catch (PDOException $e) {
        // Ignore table creation errors
    }
}
?>
