<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, 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 Lesson Actions API Access: " . $userAgent . " from " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
}

validateApiAccess();

// Simple token validation function
function validateTokenAndGetUserId($token) {
    global $conn;
    
    if (empty($token)) {
        return false;
    }
    
    try {
        // Check if token exists and is still valid in user_sessions table
        $stmt = $conn->prepare("
            SELECT us.user_id 
            FROM user_sessions us 
            JOIN users u ON us.user_id = u.id 
            WHERE us.token = ? 
            AND us.expires_at > NOW() 
            AND u.is_deleted = 0 
            AND u.is_verified = 1
        ");
        $stmt->execute([$token]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($result) {
            return (int)$result['user_id'];
        }
    } catch (Exception $e) {
        error_log("Token validation error: " . $e->getMessage());
    }
    
    return false;
}

try {
    $conn = getDBConnection();
    
    if (!$conn) {
        sendResponse(false, 'Database connection failed');
    }

    $method = $_SERVER['REQUEST_METHOD'];
    $action = $_GET['action'] ?? '';

    switch ($method) {
        case 'POST':
            if ($action === 'create_table') {
                createTable($conn);
            } else {
                handlePost($conn, $action);
            }
            break;
        case 'GET':
            if ($action === 'create_table') {
                createTable($conn);
            } else {
                handleGet($conn, $action);
            }
            break;
        case 'DELETE':
            handleDelete($conn, $action);
            break;
        default:
            sendResponse(false, 'Method not allowed');
    }

} catch (Exception $e) {
    error_log("User Lesson Actions API error: " . $e->getMessage());
    sendResponse(false, 'Error: ' . $e->getMessage());
}

function handlePost($conn, $action) {
    $data = json_decode(file_get_contents('php://input'), true);
    $action = $data['action'] ?? $action; // Use action from JSON data if available
    $token = $data['token'] ?? '';
    $lessonId = (int)($data['lesson_id'] ?? 0);
    $actionType = $data['action_type'] ?? '';

    if (empty($token) || $lessonId <= 0 || !in_array($actionType, ['bookmark', 'save', 'favorite'])) {
        sendResponse(false, 'Invalid parameters');
    }

    $userId = validateTokenAndGetUserId($token);
    if (!$userId) {
        sendResponse(false, 'Invalid token');
    }

    switch ($action) {
        case 'add':
            addAction($conn, $userId, $lessonId, $actionType);
            break;
        default:
            sendResponse(false, 'Invalid action');
    }
}

function handleGet($conn, $action) {
    if ($action === 'create_table') {
        createTable($conn);
        return;
    }
    
    $token = $_GET['token'] ?? '';
    $actionType = $_GET['action_type'] ?? '';

    if (empty($token)) {
        sendResponse(false, 'Token required');
    }

    $userId = validateTokenAndGetUserId($token);
    if (!$userId) {
        sendResponse(false, 'Invalid token');
    }

    switch ($action) {
        case 'list':
            listActions($conn, $userId, $actionType);
            break;
        case 'check':
            checkAction($conn, $userId, $_GET['lesson_id'] ?? 0, $actionType);
            break;
        default:
            sendResponse(false, 'Invalid action');
    }
}

function handleDelete($conn, $action) {
    $data = json_decode(file_get_contents('php://input'), true);
    $token = $data['token'] ?? '';
    $lessonId = (int)($data['lesson_id'] ?? 0);
    $actionType = $data['action_type'] ?? '';

    if (empty($token) || $lessonId <= 0 || !in_array($actionType, ['bookmark', 'save', 'favorite'])) {
        sendResponse(false, 'Invalid parameters');
    }

    $userId = validateTokenAndGetUserId($token);
    if (!$userId) {
        sendResponse(false, 'Invalid token');
    }

    switch ($action) {
        case 'remove':
            removeAction($conn, $userId, $lessonId, $actionType);
            break;
        default:
            sendResponse(false, 'Invalid action');
    }
}

function addAction($conn, $userId, $lessonId, $actionType) {
    try {
        $conn->beginTransaction();

        // Special handling for bookmarks - only one bookmark per user
        if ($actionType === 'bookmark') {
            // Remove any existing bookmarks for this user
            $stmt = $conn->prepare("DELETE FROM user_lesson_actions WHERE user_id = ? AND action_type = 'bookmark'");
            $stmt->execute([$userId]);
        }

        // Check if lesson exists
        $stmt = $conn->prepare("SELECT id FROM lessons WHERE id = ? AND is_active = 1");
        $stmt->execute([$lessonId]);
        if (!$stmt->fetch()) {
            $conn->rollBack();
            sendResponse(false, 'Lesson not found');
        }

        // Add the new action (or update if exists for save/favorite)
        $stmt = $conn->prepare("
            INSERT INTO user_lesson_actions (user_id, lesson_id, action_type) 
            VALUES (?, ?, ?) 
            ON DUPLICATE KEY UPDATE updated_at = CURRENT_TIMESTAMP
        ");
        $stmt->execute([$userId, $lessonId, $actionType]);

        $conn->commit();

        $actionLabel = ucfirst($actionType);
        if ($actionType === 'bookmark') {
            sendResponse(true, "Lesson bookmarked successfully", ['replaced_previous' => true]);
        } else {
            sendResponse(true, "$actionLabel added successfully");
        }

    } catch (Exception $e) {
        $conn->rollBack();
        throw $e;
    }
}

function removeAction($conn, $userId, $lessonId, $actionType) {
    $stmt = $conn->prepare("
        DELETE FROM user_lesson_actions 
        WHERE user_id = ? AND lesson_id = ? AND action_type = ?
    ");
    $stmt->execute([$userId, $lessonId, $actionType]);

    if ($stmt->rowCount() > 0) {
        $actionLabel = ucfirst($actionType);
        sendResponse(true, "$actionLabel removed successfully");
    } else {
        sendResponse(false, 'Action not found');
    }
}

function listActions($conn, $userId, $actionType = '') {
    $sql = "
        SELECT ula.*, l.title, l.description, l.level, l.order_index,
               l.has_video, l.has_audio, l.has_reading, l.has_pronunciation, l.has_listen_write
        FROM user_lesson_actions ula
        JOIN lessons l ON ula.lesson_id = l.id
        WHERE ula.user_id = ? AND l.is_active = 1
    ";
    
    $params = [$userId];
    
    if (!empty($actionType) && in_array($actionType, ['bookmark', 'save', 'favorite'])) {
        $sql .= " AND ula.action_type = ?";
        $params[] = $actionType;
    }
    
    $sql .= " ORDER BY ula.action_type, l.level ASC, l.order_index ASC";
    
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);
    $actions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Group by action type
    $grouped = [];
    foreach ($actions as $action) {
        $type = $action['action_type'];
        if (!isset($grouped[$type])) {
            $grouped[$type] = [];
        }

        // Format lesson data
        $lesson = [
            'id' => (int)$action['lesson_id'],
            'title' => $action['title'],
            'description' => $action['description'],
            'level' => (int)$action['level'],
            'order_index' => (int)$action['order_index'],
            'has_video' => (bool)$action['has_video'],
            'has_audio' => (bool)$action['has_audio'],
            'has_reading' => (bool)$action['has_reading'],
            'has_pronunciation' => (bool)$action['has_pronunciation'],
            'has_listen_write' => (bool)$action['has_listen_write'],
            'added_at' => $action['created_at']
        ];

        $grouped[$type][] = $lesson;
    }

    sendResponse(true, 'Actions retrieved successfully', [
        'actions' => $grouped,
        'counts' => [
            'bookmark' => count($grouped['bookmark'] ?? []),
            'save' => count($grouped['save'] ?? []),
            'favorite' => count($grouped['favorite'] ?? [])
        ]
    ]);
}

function checkAction($conn, $userId, $lessonId, $actionType) {
    if ($lessonId <= 0 || !in_array($actionType, ['bookmark', 'save', 'favorite'])) {
        sendResponse(false, 'Invalid parameters');
    }

    $stmt = $conn->prepare("
        SELECT id FROM user_lesson_actions 
        WHERE user_id = ? AND lesson_id = ? AND action_type = ?
    ");
    $stmt->execute([$userId, $lessonId, $actionType]);
    $exists = $stmt->fetch() !== false;

    sendResponse(true, 'Check completed', [
        'exists' => $exists,
        'lesson_id' => $lessonId,
        'action_type' => $actionType
    ]);
}

function createTable($conn) {
    try {
        $sql = "
        CREATE TABLE IF NOT EXISTS `user_lesson_actions` (
          `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
          `user_id` INT(11) UNSIGNED NOT NULL,
          `lesson_id` INT(11) UNSIGNED NOT NULL,
          `action_type` ENUM('bookmark', 'save', 'favorite') NOT NULL COMMENT 'Type of action: bookmark (1 per user), save for later, or favorite',
          `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          
          PRIMARY KEY (`id`),
          UNIQUE KEY `unique_user_lesson_action` (`user_id`, `lesson_id`, `action_type`),
          KEY `idx_user_id` (`user_id`),
          KEY `idx_lesson_id` (`lesson_id`),
          KEY `idx_action_type` (`action_type`),
          KEY `idx_user_action` (`user_id`, `action_type`),
          FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE,
          FOREIGN KEY (`lesson_id`) REFERENCES `lessons`(`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ";
        
        $conn->exec($sql);
        
        // Create indexes
        $indexSql = "CREATE INDEX IF NOT EXISTS `idx_user_lesson_actions_compound` ON `user_lesson_actions` (`user_id`, `action_type`, `created_at`)";
        $conn->exec($indexSql);
        
        sendResponse(true, 'Table created successfully');
    } catch (Exception $e) {
        sendResponse(false, 'Failed to create table: ' . $e->getMessage());
    }
}
?>