<?php
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, Authorization, X-API-Key, User-Agent');

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

require_once 'config.php';

// API Security Configuration
define('API_KEY', 'ensi_app_2025_secure_key_v1');
define('ALLOWED_USER_AGENTS', [
    'Dart/',
    'ensi-flutter-app',
]);

// Helper: Validate API access
function validateApiAccess() {
    $apiKey = $_SERVER['HTTP_X_API_KEY'] ?? $_GET['api_key'] ?? '';
    if ($apiKey !== API_KEY) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid API key.',
            'status_code' => 403
        ]);
        exit;
    }
    
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $isValidUserAgent = false;
    
    foreach (ALLOWED_USER_AGENTS as $allowedAgent) {
        if (strpos($userAgent, $allowedAgent) !== false) {
            $isValidUserAgent = true;
            break;
        }
    }
    
    if (!$isValidUserAgent) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid client.',
            'status_code' => 403
        ]);
        exit;
    }
    
    error_log("User Progress API Access: " . $userAgent . " from " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
}

validateApiAccess();

try {
    $conn = getDBConnection();
    
    if (!$conn) {
        sendResponse(false, 'Database connection failed');
    }
    
    $action = $_GET['action'] ?? 'get_progress';
    $token = $_GET['token'] ?? '';
    
    if (empty($token)) {
        sendResponse(false, 'Token is required');
    }
    
    // Validate session
    $stmt = $conn->prepare("
        SELECT user_id FROM user_sessions 
        WHERE token = ? AND expires_at > NOW()
    ");
    $stmt->execute([$token]);
    $session = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$session) {
        sendResponse(false, 'Invalid or expired session');
    }
    
    $userId = $session['user_id'];
    
    switch ($action) {
        case 'get_progress':
            // Get user's highest completed level
            $stmt = $conn->prepare("
                SELECT MAX(l.level) as last_completed_level
                FROM lessons l
                INNER JOIN lesson_progress p ON l.id = p.lesson_id
                WHERE p.user_id = ? AND p.overall_completed = 1
            ");
            $stmt->execute([$userId]);
            $progress = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $lastCompletedLevel = $progress['last_completed_level'] ?? 0;
            
            // Get total levels available
            $stmt = $conn->prepare("SELECT MAX(level) as max_level FROM lessons WHERE is_active = 1");
            $stmt->execute();
            $maxLevelData = $stmt->fetch(PDO::FETCH_ASSOC);
            $maxLevel = $maxLevelData['max_level'] ?? 1;
            
            // Get current level user is working on (next incomplete level)
            $stmt = $conn->prepare("
                SELECT MIN(l.level) as current_level
                FROM lessons l
                LEFT JOIN lesson_progress p ON l.id = p.lesson_id AND p.user_id = ?
                WHERE l.is_active = 1 AND (p.overall_completed IS NULL OR p.overall_completed = 0)
            ");
            $stmt->execute([$userId]);
            $currentProgress = $stmt->fetch(PDO::FETCH_ASSOC);
            $currentLevel = $currentProgress['current_level'] ?? 1;
            
            sendResponse(true, 'Progress retrieved successfully', [
                'last_completed_level' => $lastCompletedLevel,
                'current_level' => $currentLevel,
                'max_level' => $maxLevel,
                'suggested_start_level' => max(1, $currentLevel - 3),
                'suggested_end_level' => min($maxLevel, $currentLevel + 3)
            ]);
            break;
            
        case 'get_level_completion':
            // Get completion status for specific levels
            $levels = $_GET['levels'] ?? '';
            if (empty($levels)) {
                sendResponse(false, 'Levels parameter is required');
            }
            
            $levelArray = explode(',', $levels);
            $placeholders = str_repeat('?,', count($levelArray) - 1) . '?';
            
            $stmt = $conn->prepare("
                SELECT 
                    l.level,
                    COUNT(l.id) as total_lessons,
                    COUNT(CASE WHEN p.overall_completed = 1 THEN 1 END) as completed_lessons,
                    CASE 
                        WHEN COUNT(l.id) = COUNT(CASE WHEN p.overall_completed = 1 THEN 1 END) 
                        THEN 1 ELSE 0 
                    END as level_completed
                FROM lessons l
                LEFT JOIN lesson_progress p ON l.id = p.lesson_id AND p.user_id = ?
                WHERE l.level IN ($placeholders) AND l.is_active = 1
                GROUP BY l.level
                ORDER BY l.level
            ");
            
            $params = array_merge([$userId], $levelArray);
            $stmt->execute($params);
            $levelCompletions = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            sendResponse(true, 'Level completion status retrieved', [
                'level_completions' => $levelCompletions
            ]);
            break;
            
        default:
            sendResponse(false, 'Invalid action');
    }
    
} catch (PDOException $e) {
    error_log("User Progress API error: " . $e->getMessage());
    sendResponse(false, 'An error occurred while fetching progress');
}
?>