<?php
// Enable strict error reporting for development
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session for user authentication
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Database Credentials
define('DB_HOST', 'localhost');
define('DB_USER', 'lifelead_admin');
define('DB_PASS', 'WW9UNbfb3MWmZ8t'); // !!! IMPORTANT: CHANGE THIS IN PRODUCTION !!!
define('DB_NAME', 'lifelead_cs');

// Application Constants
define('APP_NAME', 'ClassKey Online Education');
define('BASE_URL', '/'); // Adjust if not running from web root

// Global variable for PDO connection
global $pdo;

// Establish Database Connection (PDO)
try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // In a real application, you would log this and show a generic error page
    die("Database Connection Error: " . $e->getMessage());
}


// --- Mock Session Data & Utility Functions (Adjusted for DB usage) ---

// Define the application name if not defined (used in layouts.php)
if (!defined('APP_NAME')) {
    define('APP_NAME', 'Class Key App');
}

// Mock Session Data for Demonstration (User/Auth should be handled elsewhere)
if (!isset($_SESSION['user_role'])) {
    $_SESSION['user_name'] = 'Dr. Admin';
    $_SESSION['profile_image_url'] = 'https://placehold.co/40x40/9333ea/ffffff?text=AD';
    $_SESSION['user_role'] = 'admin'; // Change this to 'student' to test student view
    $_SESSION['user_id'] = 'demo_admin_id';
}

/**
 * Gets the current user role from the session.
 * @return string 'admin' or 'student'
 */
function get_user_role() {
    return $_SESSION['user_role'] ?? 'student';
}

/**
 * Checks if the current user has the 'admin' role.
 * @return bool
 */
function is_admin() {
    return get_user_role() === 'admin';
}

/**
 * Gets the current user's ID.
 * @return string
 */
function get_current_user_id() {
    return $_SESSION['user_id'] ?? 'anonymous';
}

/**
 * Ensures the user is logged in and optionally has a specific role.
 * If checks fail, the user is redirected to the index/login page.
 * @param string|null $requiredRole The role required ('admin' or 'student'). Null if only login is required.
 */
function require_login($requiredRole = null) {
    // Check if user is logged in (using 'user_id' as proxy)
    if (get_current_user_id() === 'anonymous') {
        // Not logged in: redirect to BASE_URL (or login page)
        header('Location: ' . BASE_URL);
        exit();
    }

    // Check for required role
    if ($requiredRole !== null) {
        $userRole = get_user_role();
        if ($userRole !== $requiredRole) {
            // Logged in but wrong role: redirect to unauthorized page or dashboard
            // For simplicity, redirecting to the base URL
            header('Location: ' . BASE_URL . '?error=unauthorized');
            exit();
        }
    }
}

/**
 * Helper function to ensure the current user is an admin.
 * Stops execution and shows an error if not an admin.
 * This is useful for pages like dashboard.php and addquiz.php.
 */
function require_admin() {
    if (!is_admin()) {
        die("Access Denied: You must be an administrator to view this page.");
    }
}


// --- Database Interaction Functions (Based on quiz_system.sql) ---

/**
 * Retrieves all available quizzes with question counts.
 * @return array
 */
function get_all_quizzes() {
    global $pdo;
    try {
        // CORRECTION: Removed the original query with the SQL syntax error (PHP comment line)
        // This query is now robust and should execute correctly.
        $sql = "
            SELECT
                q.quiz_id AS id,
                q.title,
                q.topic,
                q.time_limit_seconds,
                COUNT(t.question_id) AS question_count
            FROM
                quizzes q
            LEFT JOIN
                questions t ON q.quiz_id = t.quiz_id
            GROUP BY
                q.quiz_id,
                q.title,
                q.topic,
                q.time_limit_seconds
            ORDER BY q.created_at DESC
        ";

        // Execute the corrected query
        $stmt = $pdo->query($sql);
        
        // Remap for compatibility with existing PHP code expecting 'id' key
        $quizzes = [];
        while ($row = $stmt->fetch()) {
            // Mock question array for count() compatibility in the presentation layer
            $row['questions'] = array_fill(0, $row['question_count'], 1); 
            unset($row['question_count']);
            $quizzes[$row['id']] = $row;
        }
        return $quizzes;

    } catch (PDOException $e) {
        // Log or handle the error gracefully
        error_log("Database error in get_all_quizzes: " . $e->getMessage());
        return [];
    }
}

/**
 * Retrieves a single quiz by ID, including its questions and options.
 * @param int $quizId
 * @return array|null
 */
function get_quiz_by_id($quizId) {
    global $pdo;
    
    // 1. Get Quiz Header
    $stmt = $pdo->prepare("SELECT quiz_id AS id, title, topic, time_limit_seconds FROM quizzes WHERE quiz_id = ?"); // Added time_limit_seconds
    $stmt->execute([$quizId]);
    $quiz = $stmt->fetch();
    
    if (!$quiz) return null;
    
    $quiz['questions'] = [];

    // 2. Get Questions and Options
    $q_stmt = $pdo->prepare("
        SELECT 
            q.question_id AS id, 
            q.question_text AS question, 
            q.correct_answer AS answer,
            GROUP_CONCAT(o.option_text ORDER BY o.option_id SEPARATOR '||') AS options_list
        FROM questions q
        LEFT JOIN options o ON q.question_id = o.question_id
        WHERE q.quiz_id = ?
        GROUP BY q.question_id
        ORDER BY q.question_id
    ");
    $q_stmt->execute([$quizId]);

    while ($row = $q_stmt->fetch()) {
        $options = explode('||', $row['options_list']);
        
        $quiz['questions'][$row['id']] = [
            'question' => $row['question'],
            'answer' => $row['answer'],
            'options' => $options,
            'type' => 'mcq'
        ];
    }
    
    return $quiz;
}

/**
 * Saves a new quiz.
 * @param string $title
 * @param string $topic
 * @param int $timeLimitSeconds The time limit for the quiz in seconds (0 for no limit).
 * @return int The new quiz ID
 */
function save_quiz($title, $topic, $timeLimitSeconds = 0) {
    global $pdo;
    $stmt = $pdo->prepare("INSERT INTO quizzes (title, topic, time_limit_seconds) VALUES (?, ?, ?)");
    $stmt->execute([$title, $topic, $timeLimitSeconds]);
    return $pdo->lastInsertId();
}

/**
 * Adds a question and its options to a specific quiz.
 * @param int $quizId
 * @param string $question
 * @param array $options
 * @param string $answer
 */
function add_quiz_question($quizId, $question, $options, $answer) {
    global $pdo;
    
    $pdo->beginTransaction();
    try {
        // 1. Insert Question
        $q_stmt = $pdo->prepare("INSERT INTO questions (quiz_id, question_text, correct_answer) VALUES (?, ?, ?)");
        $q_stmt->execute([$quizId, $question, $answer]);
        $questionId = $pdo->lastInsertId();
        
        // 2. Insert Options
        $o_stmt = $pdo->prepare("INSERT INTO options (question_id, option_text) VALUES (?, ?)");
        foreach ($options as $optionText) {
            if (!empty($optionText)) {
                $o_stmt->execute([$questionId, $optionText]);
            }
        }
        
        $pdo->commit();
    } catch (Exception $e) {
        $pdo->rollBack();
        error_log("Failed to add question: " . $e->getMessage());
        throw $e;
    }
}

/**
 * Records a student's quiz attempt result.
 * @param int $quizId
 * @param int $score
 * @param int|null $totalQuestions
 */
function record_quiz_result($quizId, $score, $totalQuestions = 0) {
    global $pdo;
    // Ensure $totalQuestions is treated as an integer, defaulting to 0 if null/not set.
    $totalQuestions = (int)($totalQuestions ?? 0);    
    
    $userId = get_current_user_id();
    
    try {
        $stmt = $pdo->prepare("
            INSERT INTO results (user_id, quiz_id, score, total_questions) 
            VALUES (?, ?, ?, ?)
        ");
        $stmt->execute([$userId, $quizId, $score, $totalQuestions]);
    } catch (PDOException $e) {
        // Check for the specific foreign key constraint violation (SQLSTATE 23000 is generic, but the message helps)
        if ($e->getCode() === '23000' && strpos($e->getMessage(), 'results_ibfk_1') !== false) {
            // Log the error indicating the quiz ID is missing
            error_log("Foreign Key Constraint Violation: Attempted to record result for non-existent quiz ID: {$quizId}. Error: " . $e->getMessage());
            // Optionally, return false or throw a custom exception
            return false;
        }
        // Re-throw if it's a different, unexpected PDO error
        throw $e;
    }
}

/**
 * Gets the student's highest score for a quiz.
 * @param int $quizId
 * @return array|null
 */
function get_student_score($quizId) {
    global $pdo;
    $userId = get_current_user_id();
    $stmt = $pdo->prepare("
        SELECT score, total_questions 
        FROM results 
        WHERE user_id = ? AND quiz_id = ? 
        ORDER BY score DESC, attempt_time DESC 
        LIMIT 1
    ");
    $stmt->execute([$userId, $quizId]);
    return $stmt->fetch(); // Returns array with 'score' and 'total_questions'
}
function getGoogleClient() {
    $client = new Google\Client();
    $client->setClientId(GOOGLE_CLIENT_ID);
    $client->setClientSecret(GOOGLE_CLIENT_SECRET);
    $client->setRedirectUri(GOOGLE_REDIRECT_URI);
    // Request user's email and basic profile information
    $client->addScope('email');
    $client->addScope('profile');
    return $client;
}