<?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;

// Function to extract numeric user ID from various formats
function extractUserId($user_id) {
    if (!$user_id || $user_id === 'anonymous') {
        return 'anonymous';
    }
    
    // If it's already numeric, return as is
    if (is_numeric($user_id)) {
        return $user_id;
    }
    
    // Handle formats like "judge_1", "admin_5", "participant_123"
    if (is_string($user_id) && strpos($user_id, '_') !== false) {
        $parts = explode('_', $user_id);
        $last_part = end($parts);
        if (is_numeric($last_part)) {
            return $last_part;
        }
    }
    
    // Return original if no pattern matches
    return $user_id;
}

// Get the actual numeric user ID from session
if ($session_user_id) {
    $actual_user_id = extractUserId($session_user_id);
} else {
    // Try to get from different session variables that might contain the user ID
    $potential_user_id = $_SESSION['judge_id'] ?? $_SESSION['participant_id'] ?? $_SESSION['admin_id'] ?? null;
    $actual_user_id = extractUserId($potential_user_id);
}

$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', 'cleanup_user_ids'];

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;
        case 'save_settings':
            saveNotificationSettings();
            break;
        case 'get_settings':
            getNotificationSettings();
            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, $actual_user_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 using the extractUserId function
    $user_id = extractUserId($user_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();
        createNotificationSettingsTable();
        
        // 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, $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 using the extractUserId function
    $user_id = extractUserId($user_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 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',
        'debug_info' => [
            'notification_id' => $notification_id,
            'user_id' => $user_id,
            'marked_at' => date('Y-m-d H:i:s')
        ]
    ]);
}

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 using the extractUserId function
    $user_id = extractUserId($user_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 {
        // First, get all records that need fixing
        $find_stmt = $pdo->prepare("
            SELECT id, notification_id, user_id 
            FROM notification_reads 
            WHERE user_id LIKE '%_%' AND SUBSTRING_INDEX(user_id, '_', -1) REGEXP '^[0-9]+$'
        ");
        $find_stmt->execute();
        $records_to_fix = $find_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $fixed_count = 0;
        $duplicate_count = 0;
        
        foreach ($records_to_fix as $record) {
            $old_user_id = $record['user_id'];
            $new_user_id = extractUserId($old_user_id);
            
            if ($old_user_id !== $new_user_id) {
                // Check if a record with the new user_id already exists
                $check_stmt = $pdo->prepare("
                    SELECT id FROM notification_reads 
                    WHERE notification_id = ? AND user_id = ?
                ");
                $check_stmt->execute([$record['notification_id'], $new_user_id]);
                $existing = $check_stmt->fetch();
                
                if ($existing) {
                    // Delete the duplicate with the old user_id format
                    $delete_stmt = $pdo->prepare("DELETE FROM notification_reads WHERE id = ?");
                    $delete_stmt->execute([$record['id']]);
                    $duplicate_count++;
                } else {
                    // Update to the new user_id format
                    $update_stmt = $pdo->prepare("
                        UPDATE notification_reads 
                        SET user_id = ? 
                        WHERE id = ?
                    ");
                    $update_stmt->execute([$new_user_id, $record['id']]);
                    $fixed_count++;
                }
            }
        }
        
        // Show current user_ids for verification
        $check_stmt = $pdo->prepare("
            SELECT DISTINCT user_id, COUNT(*) as count 
            FROM notification_reads 
            GROUP BY user_id 
            ORDER BY user_id
        ");
        $check_stmt->execute();
        $current_user_ids = $check_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true, 
            'message' => "Fixed {$fixed_count} records, removed {$duplicate_count} duplicates",
            'fixed_count' => $fixed_count,
            'duplicate_count' => $duplicate_count,
            'current_user_ids' => $current_user_ids
        ]);
    } 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 saveNotificationSettings() {
    global $pdo, $event_id;
    
    if (!$event_id) {
        throw new Exception('Event ID is required');
    }
    
    if (!$pdo) {
        echo json_encode(['success' => false, 'message' => 'No database connection']);
        return;
    }
    
    // Create settings table if needed
    createNotificationSettingsTable();
    
    // Get settings from POST data
    $poll_interval = intval($_POST['pollInterval'] ?? 3000);
    $max_visible = intval($_POST['maxVisibleNotifications'] ?? 5);
    $notification_duration = intval($_POST['notificationDuration'] ?? 10);
    $sound_enabled = filter_var($_POST['soundEnabled'] ?? true, FILTER_VALIDATE_BOOLEAN);
    $auto_dismiss = filter_var($_POST['autoDismiss'] ?? false, FILTER_VALIDATE_BOOLEAN);
    $show_categories = json_encode($_POST['showCategories'] ?? []);
    
    try {
        // Use INSERT ... ON DUPLICATE KEY UPDATE for upsert behavior
        $stmt = $pdo->prepare("
            INSERT INTO event_notification_settings 
            (event_id, poll_interval, max_visible_notifications, notification_duration, 
             sound_enabled, auto_dismiss, show_categories, updated_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
            ON DUPLICATE KEY UPDATE
            poll_interval = VALUES(poll_interval),
            max_visible_notifications = VALUES(max_visible_notifications),
            notification_duration = VALUES(notification_duration),
            sound_enabled = VALUES(sound_enabled),
            auto_dismiss = VALUES(auto_dismiss),
            show_categories = VALUES(show_categories),
            updated_at = NOW()
        ");
        
        $result = $stmt->execute([
            $event_id, 
            $poll_interval, 
            $max_visible, 
            $notification_duration,
            $sound_enabled,
            $auto_dismiss,
            $show_categories
        ]);
        
        if ($result) {
            echo json_encode([
                'success' => true,
                'message' => 'Notification settings saved successfully',
                'settings' => [
                    'event_id' => $event_id,
                    'pollInterval' => $poll_interval,
                    'maxVisibleNotifications' => $max_visible,
                    'notificationDuration' => $notification_duration,
                    'soundEnabled' => $sound_enabled,
                    'autoDismiss' => $auto_dismiss,
                    'showCategories' => json_decode($show_categories, true)
                ]
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to save settings']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
}

function getNotificationSettings() {
    global $pdo, $event_id;
    
    if (!$event_id) {
        throw new Exception('Event ID is required');
    }
    
    if (!$pdo) {
        // Return default settings if no database connection
        echo json_encode([
            'success' => true,
            'settings' => [
                'pollInterval' => 3000,
                'maxVisibleNotifications' => 5,
                'notificationDuration' => 10,
                'soundEnabled' => true,
                'autoDismiss' => false,
                'showCategories' => []
            ]
        ]);
        return;
    }
    
    // Create settings table if needed
    createNotificationSettingsTable();
    
    try {
        $stmt = $pdo->prepare("
            SELECT poll_interval, max_visible_notifications, notification_duration, 
                   sound_enabled, auto_dismiss, show_categories 
            FROM event_notification_settings 
            WHERE event_id = ?
        ");
        $stmt->execute([$event_id]);
        $settings = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($settings) {
            echo json_encode([
                'success' => true,
                'settings' => [
                    'pollInterval' => intval($settings['poll_interval']),
                    'maxVisibleNotifications' => intval($settings['max_visible_notifications']),
                    'notificationDuration' => intval($settings['notification_duration']),
                    'soundEnabled' => (bool)$settings['sound_enabled'],
                    'autoDismiss' => (bool)$settings['auto_dismiss'],
                    'showCategories' => json_decode($settings['show_categories'], true) ?: []
                ]
            ]);
        } else {
            // Return default settings for new events
            echo json_encode([
                'success' => true,
                'settings' => [
                    'pollInterval' => 3000,
                    'maxVisibleNotifications' => 5,
                    'notificationDuration' => 10,
                    'soundEnabled' => true,
                    'autoDismiss' => false,
                    'showCategories' => []
                ],
                'message' => 'Using default settings for this event'
            ]);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
}

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
    }
}

function createNotificationSettingsTable() {
    global $pdo;
    
    // Skip if no database connection
    if (!$pdo) {
        return;
    }
    
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS event_notification_settings (
                id INT AUTO_INCREMENT PRIMARY KEY,
                event_id INT NOT NULL,
                poll_interval INT DEFAULT 3000,
                max_visible_notifications INT DEFAULT 5,
                notification_duration INT DEFAULT 10,
                sound_enabled BOOLEAN DEFAULT TRUE,
                auto_dismiss BOOLEAN DEFAULT FALSE,
                show_categories JSON DEFAULT '[]',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE KEY unique_event_settings (event_id),
                INDEX idx_event_id (event_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    } catch (PDOException $e) {
        // Ignore table creation errors
    }
}
?>
