<?php
// filepath: c:\stylescore2025\htdocs\v2\api\notification_api.php
// Real-time notification system for competition events

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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// Try to include config, but provide fallback if it doesn't exist
$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; // Successfully got PDO connection
            }
        } catch (Exception $e) {
            // Continue to next path or fallback
            continue;
        }
    }
}

// If no config worked, try fallback database connection
if (!$pdo) {
    $host = 'localhost';
    $dbname = 'pzls_livescore_398dsk'; // Updated to match your actual database name
    $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) {
        // If database connection fails, return simple success responses
        $pdo = null;
    }
}

// Try to include auth session and get actual user ID
$session_user_id = null;
$actual_user_id = null;
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
$session_user_id = $_SESSION['user_id'] ?? $_SESSION['id'] ?? null;

// Get the actual numeric user ID from session
if ($session_user_id) {
    $actual_user_id = $session_user_id;
} else {
    // Try to get from different session variables that might contain the user ID
    $actual_user_id = $_SESSION['judge_id'] ?? $_SESSION['participant_id'] ?? $_SESSION['admin_id'] ?? null;
    
    // Remove any role prefix if it exists (e.g., "judge_1" -> "1")
    if ($actual_user_id && is_string($actual_user_id) && strpos($actual_user_id, '_') !== false) {
        $parts = explode('_', $actual_user_id);
        $actual_user_id = end($parts); // Get the last part (the number)
    }
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$event_id = $_GET['event_id'] ?? $_POST['event_id'] ?? null;

// Actions that don't require event_id
$no_event_id_required = ['mark_read', 'get_user_notifications', 'dismiss_notification', 'delete_notification'];

if (!$event_id && !in_array($action, $no_event_id_required)) {
    http_response_code(400);
    echo json_encode(['error' => 'Event ID is required for this action']);
    exit;
}

try {
    switch ($action) {
        case 'send_notification':
            sendNotification();
            break;
        case 'get_notifications':
            getNotifications();
            break;
        case 'mark_read':
            markNotificationRead();
            break;
        case 'dismiss_notification':
            dismissNotification();
            break;
        case 'delete_notification':
            deleteNotification();
            break;
        case 'cleanup_user_ids':
            cleanupUserIds();
            break;
        case 'clear_all':
            clearAllNotifications();
            break;
        default:
            http_response_code(400);
            echo json_encode(['error' => 'Invalid action']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}

function sendNotification() {
    global $pdo, $event_id;
    
    $type = $_POST['type'] ?? 'info';
    $title = $_POST['title'] ?? '';
    $message = $_POST['message'] ?? '';
    $user_id = $_POST['user_id'] ?? 'system';
    $data = $_POST['data'] ?? '{}';
    $category = $_POST['category'] ?? 'general';
    
    if (empty($title)) {
        throw new Exception('Title is required');
    }
    
    // If no database connection, return success without storing
    if (!$pdo) {
        echo json_encode([
            'success' => true,
            'notification' => [
                'id' => time(),
                'event_id' => $event_id,
                'type' => $type,
                'title' => $title,
                'message' => $message,
                'user_id' => $user_id,
                'data' => $data,
                'category' => $category,
                'created_at' => date('Y-m-d H:i:s')
            ],
            'message' => 'Notification sent successfully (no database storage)'
        ]);
        return;
    }
    
    // Create notifications table if it doesn't exist
    createNotificationsTable();
    
    $stmt = $pdo->prepare("
        INSERT INTO event_notifications 
        (event_id, type, title, message, user_id, data, category, created_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    
    $stmt->execute([$event_id, $type, $title, $message, $user_id, $data, $category]);
    
    $notification_id = $pdo->lastInsertId();
    
    // Get the created notification
    $stmt = $pdo->prepare("
        SELECT * FROM event_notifications 
        WHERE id = ?
    ");
    $stmt->execute([$notification_id]);
    $notification = $stmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'notification' => $notification,
        'message' => 'Notification sent successfully'
    ]);
}

function getNotifications() {
    global $pdo, $event_id;
    
    $since = $_GET['since'] ?? 0;
    $limit = $_GET['limit'] ?? 50;
    $category = $_GET['category'] ?? null; // Filter by category
    $user_id = $_GET['user_id'] ?? $_POST['user_id'] ?? $actual_user_id ?? 'anonymous';
    
    // Clean up user_id - remove role prefixes if present
    if ($user_id && is_string($user_id) && strpos($user_id, '_') !== false) {
        $parts = explode('_', $user_id);
        if (is_numeric(end($parts))) {
            $user_id = end($parts); // Extract just the numeric ID
        }
    }
    
    // If no database connection, return empty notifications
    if (!$pdo) {
        echo json_encode([
            'success' => true,
            'notifications' => [],
            'latest_id' => 0,
            'count' => 0,
            'message' => 'No database connection - notifications not persisted'
        ]);
        return;
    }
    
    try {
        createNotificationsTable();
        createNotificationReadsTable();
        
        // Debug: Check if we have dismissed notifications for this user
        $debug_stmt = $pdo->prepare("SELECT COUNT(*) as dismissed_count FROM notification_reads WHERE user_id = ?");
        $debug_stmt->execute([$user_id]);
        $dismissed_info = $debug_stmt->fetch(PDO::FETCH_ASSOC);
        
        // Query to get notifications excluding dismissed ones
        $sql = "
            SELECT n.*, 
                   CASE WHEN nr.id IS NOT NULL THEN 1 ELSE 0 END as is_dismissed
            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 > ?
        ";
        $params = [$user_id, $event_id, $since];
        
        // Add category filter if specified
        if ($category) {
            $sql .= " AND n.category = ?";
            $params[] = $category;
        }
        
        // Only show non-dismissed notifications
        $sql .= " AND nr.id IS NULL";
        $sql .= " ORDER BY n.created_at DESC LIMIT " . (int)$limit;
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get the latest ID for next polling
        $latest_id = 0;
        if (!empty($notifications)) {
            $latest_id = max(array_column($notifications, 'id'));
        }
        
        echo json_encode([
            'success' => true,
            'notifications' => array_reverse($notifications), // Show oldest first
            'latest_id' => $latest_id,
            'count' => count($notifications),
            'debug_info' => [
                'user_id' => $user_id,
                'event_id' => $event_id,
                'dismissed_count' => $dismissed_info['dismissed_count'],
                'since' => $since
            ]
        ]);
    } catch (Exception $e) {
        throw new Exception("Database error in getNotifications: " . $e->getMessage());
    }
}

function markNotificationRead() {
    global $pdo;
    
    $notification_id = $_POST['notification_id'] ?? $_GET['notification_id'] ?? null;
    $user_id = $_POST['user_id'] ?? $_GET['user_id'] ?? 'anonymous';
    
    if (!$notification_id) {
        throw new Exception('Notification ID is required');
    }
    
    // If no database connection, just return success
    if (!$pdo) {
        echo json_encode(['success' => true, 'message' => 'Notification marked as read (no database storage)']);
        return;
    }
    
    // Create read tracking table if needed
    createNotificationReadsTable();
    
    $stmt = $pdo->prepare("
        INSERT IGNORE INTO notification_reads 
        (notification_id, user_id, read_at) 
        VALUES (?, ?, NOW())
    ");
    $stmt->execute([$notification_id, $user_id]);
    
    echo json_encode(['success' => true, 'message' => 'Notification marked as read']);
}

function dismissNotification() {
    global $pdo, $actual_user_id;
    
    $notification_id = $_POST['notification_id'] ?? $_GET['notification_id'] ?? null;
    $user_id = $_POST['user_id'] ?? $_GET['user_id'] ?? $actual_user_id ?? 'anonymous';
    
    // Clean up user_id - remove role prefixes if present
    if ($user_id && is_string($user_id) && strpos($user_id, '_') !== false) {
        $parts = explode('_', $user_id);
        if (is_numeric(end($parts))) {
            $user_id = end($parts); // Extract just the numeric ID
        }
    }
    
    if (!$notification_id) {
        throw new Exception('Notification ID is required');
    }
    
    // If no database connection, just return success
    if (!$pdo) {
        echo json_encode(['success' => true, 'message' => 'Notification dismissed (no database storage)']);
        return;
    }
    
    // Mark as dismissed
    createNotificationReadsTable();
    
    // Check if already dismissed
    $check_stmt = $pdo->prepare("SELECT id FROM notification_reads WHERE notification_id = ? AND user_id = ?");
    $check_stmt->execute([$notification_id, $user_id]);
    $existing = $check_stmt->fetch();
    
    if ($existing) {
        echo json_encode(['success' => true, 'message' => 'Notification already dismissed']);
        return;
    }
    
    // Insert dismiss record
    $stmt = $pdo->prepare("
        INSERT INTO notification_reads 
        (notification_id, user_id, read_at) 
        VALUES (?, ?, NOW())
    ");
    $result = $stmt->execute([$notification_id, $user_id]);
    
    if ($result) {
        echo json_encode([
            'success' => true, 
            'message' => 'Notification dismissed successfully',
            'debug_info' => [
                'notification_id' => $notification_id,
                'user_id' => $user_id,
                'dismissed_at' => date('Y-m-d H:i:s')
            ]
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to dismiss notification']);
    }
}

function deleteNotification() {
    global $pdo;
    
    $notification_id = $_POST['notification_id'] ?? $_GET['notification_id'] ?? null;
    
    if (!$notification_id) {
        throw new Exception('Notification ID is required');
    }
    
    // If no database connection, just return success
    if (!$pdo) {
        echo json_encode(['success' => true, 'message' => 'Notification deleted (no database storage)']);
        return;
    }
    
    // Delete the notification permanently
    $stmt = $pdo->prepare("DELETE FROM event_notifications WHERE id = ?");
    $stmt->execute([$notification_id]);
    
    // Also delete any read records for this notification
    $stmt = $pdo->prepare("DELETE FROM notification_reads WHERE notification_id = ?");
    $stmt->execute([$notification_id]);
    
    echo json_encode(['success' => true, 'message' => 'Notification deleted permanently']);
}

function cleanupUserIds() {
    global $pdo;
    
    if (!$pdo) {
        echo json_encode(['success' => false, 'message' => 'No database connection']);
        return;
    }
    
    try {
        // Update notification_reads table to use numeric user IDs
        $stmt = $pdo->prepare("
            UPDATE notification_reads 
            SET user_id = SUBSTRING_INDEX(user_id, '_', -1)
            WHERE user_id LIKE '%_%' AND SUBSTRING_INDEX(user_id, '_', -1) REGEXP '^[0-9]+$'
        ");
        $result = $stmt->execute();
        $affected = $stmt->rowCount();
        
        echo json_encode([
            'success' => true, 
            'message' => "Cleaned up {$affected} user ID records",
            'affected_rows' => $affected
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Cleanup failed: ' . $e->getMessage()]);
    }
}

function clearAllNotifications() {
    global $pdo, $event_id;
    
    $stmt = $pdo->prepare("DELETE FROM event_notifications WHERE event_id = ?");
    $stmt->execute([$event_id]);
    
    echo json_encode(['success' => true, 'message' => 'All notifications cleared']);
}

function createNotificationsTable() {
    global $pdo;
    
    // Skip if no database connection
    if (!$pdo) {
        return;
    }
    
    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),
                INDEX idx_event_category (event_id, category)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    } catch (PDOException $e) {
        // Ignore table creation errors
    }
}

function createNotificationReadsTable() {
    global $pdo;
    
    // Skip if no database connection
    if (!$pdo) {
        return;
    }
    
    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
    }
}
?>
