<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: 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'); // Must match lesson_service.dart
define('ALLOWED_USER_AGENTS', [
    'Dart/', // Flutter/Dart HTTP client
    'ensi-flutter-app', // Custom user agent for your app
]);

// Helper: Validate API access
function validateApiAccess() {
    // Check API Key
    $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;
    }
    
    // Check User Agent
    $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;
    }
}

// Validate API access before processing any requests
validateApiAccess();

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Only POST requests are allowed');
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$token = $input['token'] ?? '';
$lessonId = $input['lesson_id'] ?? 0;
$action = $input['action'] ?? '';

if (empty($token) || !$lessonId || empty($action)) {
    sendResponse(false, 'Token, lesson_id, and action are required');
}

try {
    $conn = getDBConnection();
    
    // 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'];
    
    // Get or create progress record
    $stmt = $conn->prepare("
        INSERT INTO lesson_progress (user_id, lesson_id) 
        VALUES (?, ?)
        ON DUPLICATE KEY UPDATE last_accessed = CURRENT_TIMESTAMP
    ");
    $stmt->execute([$userId, $lessonId]);
    
    // Update specific progress
    $validActions = [
        'complete_video' => 'completed_video',
        'complete_audio' => 'completed_audio',
        'complete_reading' => 'completed_reading',
        'complete_pronunciation' => 'completed_pronunciation',
        'complete_listen_write' => 'completed_listen_write'
    ];
    
    if (!isset($validActions[$action])) {
        sendResponse(false, 'Invalid action');
    }
    
    $column = $validActions[$action];
    
    $stmt = $conn->prepare("
        UPDATE lesson_progress 
        SET $column = 1 
        WHERE user_id = ? AND lesson_id = ?
    ");
    $stmt->execute([$userId, $lessonId]);
    
    // Check if all required parts are completed
    $stmt = $conn->prepare("
        SELECT l.*, p.* 
        FROM lessons l
        LEFT JOIN lesson_progress p ON l.id = p.lesson_id AND p.user_id = ?
        WHERE l.id = ?
    ");
    $stmt->execute([$userId, $lessonId]);
    $data = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $allCompleted = true;
    if ($data['has_video'] && !$data['completed_video']) $allCompleted = false;
    if ($data['has_audio'] && !$data['completed_audio']) $allCompleted = false;
    if ($data['has_reading'] && !$data['completed_reading']) $allCompleted = false;
    if ($data['has_pronunciation'] && !$data['completed_pronunciation']) $allCompleted = false;
    if ($data['has_listen_write'] && !$data['completed_listen_write']) $allCompleted = false;
    
    if ($allCompleted) {
        $stmt = $conn->prepare("
            UPDATE lesson_progress 
            SET overall_completed = 1 
            WHERE user_id = ? AND lesson_id = ?
        ");
        $stmt->execute([$userId, $lessonId]);
    }
    
    sendResponse(true, 'Progress updated successfully', [
        'action' => $action,
        'overall_completed' => $allCompleted
    ]);
    
} catch (PDOException $e) {
    error_log("Progress API error: " . $e->getMessage());
    sendResponse(false, 'An error occurred');
}
