<?php

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../core/api.php';
global $pdo;

include_once 'db/adn-class-config.php';
include_once 'db/adn-quiz-config.php';


if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
$current_user_id = (int)$_SESSION['user_id'];


function get_user_progress($pdo, $user_id) {
    global $adn_classes;
    
    $progress = [
        'class_status' => [],
        'quiz_attempts' => []
    ];
    
    for ($i = 1; $i <= TOTAL_ADN_CLASSES; $i++) {
        $progress['class_status'][$i] = 'locked';
        $progress['quiz_attempts'][$i] = 0; 
    }
    
    $stmt = $pdo->prepare("SELECT class_id, status, last_attempt FROM adn_user_progress WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $db_progress = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $has_progress = false;
    foreach ($db_progress as $row) {
        $has_progress = true;
        $class_id = (int)$row['class_id'];
        
        if ($class_id > 0 && $class_id <= TOTAL_ADN_CLASSES) {
            $progress['class_status'][$class_id] = $row['status'];
            
            if ($row['last_attempt']) {
                $last_attempt_time = strtotime($row['last_attempt']);
                $retry_time = $last_attempt_time + (24 * 3600); 
                
                if (time() < $retry_time) {
                    $progress['quiz_attempts'][$class_id] = $retry_time; 
                }
            }
        }
    }

    if (!$has_progress) {
        $progress['class_status'][1] = 'unlocked';
        try {
            $stmt_insert = $pdo->prepare("
                INSERT INTO adn_user_progress (user_id, class_id, status) 
                VALUES (?, 1, 'unlocked')
                ON DUPLICATE KEY UPDATE status = 'unlocked'
            ");
            $stmt_insert->execute([$user_id]);
        } catch (PDOException $e) {
            error_log("Error al insertar progreso inicial para user_id: $user_id. " . $e->getMessage());
        }
    }
    
    return $progress;
}

function get_selected_questions($pdo, $class_id, $limit) {
    global $adn_quiz_questions;
    
    if (!isset($adn_quiz_questions[$class_id]) || empty($adn_quiz_questions[$class_id])) {
        return [];
    }
    
    $questions_for_class = $adn_quiz_questions[$class_id];
    
    shuffle($questions_for_class);
    
    return array_slice($questions_for_class, 0, $limit);
}


function can_attempt_quiz($class_number) {
    global $adn_progress; 
    return ($adn_progress['quiz_attempts'][$class_number] == 0);
}

function set_quiz_retry_lock($pdo, $user_id, $class_number) {
    global $adn_progress;
    $retry_timestamp = time() + (24 * 3600); 
    
    try {
        $stmt = $pdo->prepare("
            UPDATE adn_user_progress 
            SET last_attempt = NOW() 
            WHERE user_id = ? AND class_id = ?
        ");
        $stmt->execute([$user_id, $class_number]);
        $adn_progress['quiz_attempts'][$class_number] = $retry_timestamp;
        
    } catch (PDOException $e) {
        error_log("Error al establecer el bloqueo de quiz para user_id $user_id, class_id $class_number: " . $e->getMessage());
    }
}


$adn_progress = get_user_progress($pdo, $current_user_id);
?>