<?php



//real one(pending)

function getPendingTests($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $class_id, $section_id, $subject_id, $userid) {
    // Initialize the array to return
    $array_return = [];

    // Fetch the total count of tests where the current date and time is between publish_date/publish_time and last_date/last_submission_time
    $sql_count = "
        SELECT COUNT(*) as total_rows
        FROM test t
        LEFT JOIN test_attempt sta 
        ON t.id = sta.test_id 
        AND sta.student_id = ? 
        AND sta.status != 2  -- Exclude completed tests (status = 2)
        WHERE t.institution_id = ?
        AND CONCAT(t.publish_date, ' ', t.publish_time) <= NOW()
        AND CONCAT(t.last_date, ' ', t.last_submission_time) >= NOW()
    ";

    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute([$userid, $institution_id]);
    $result_total = $stmt->fetch(PDO::FETCH_ASSOC);
    $totalrows = $result_total['total_rows'];

    // Fetch the tests where the current date and time is between publish_date/publish_time and last_date/last_submission_time, with filtering and pagination
    $sql = "
        SELECT t.*
        FROM test t
        LEFT JOIN test_attempt sta 
        ON t.id = sta.test_id 
        AND sta.student_id = ? 
        AND sta.status != 2  -- Exclude completed tests (status = 2)
        WHERE t.institution_id = ?
        AND CONCAT(t.publish_date, ' ', t.publish_time) <= NOW()
        AND CONCAT(t.last_date, ' ', t.last_submission_time) >= NOW()
    ";

    // Apply filters
    $array_params = [$userid, $institution_id]; // Include student_id at the beginning

    if (!empty($search_string)) {
        $sql .= " AND (t.name LIKE ? OR t.description LIKE ?)";
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
    }

    if ($branch_id !== null && $branch_id !== 'all') {
        $sql .= " AND t.branch_id = ?";
        $array_params[] = $branch_id;
    }

    if ($class_id !== null && $class_id !== 'all') {
        $sql .= " AND t.class_id = ?";
        $array_params[] = $class_id;
    }

    if ($section_id !== null && $section_id !== 'all') {
        $sql .= " AND t.section_id = ?";
        $array_params[] = $section_id;
    }

    if ($subject_id !== null && $subject_id !== 'all') {
        $sql .= " AND t.subject_id = ?";
        $array_params[] = $subject_id;
    }

    // Order by and pagination
    $sql .= " ORDER BY t.date_created ASC, t.time_created ASC";

    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($result as $rows) {
        $total_duration_seconds = parseTimer($rows['timer']);
        $test_id = $rows['id'];

        // Determine if the test has been attempted
        $attemptQuery = "SELECT * FROM test_attempt WHERE institution_id = ? AND test_id = ? AND student_id = ?";
        $status_stmt = $conn_rjllearning_specific->prepare($attemptQuery);
        $status_stmt->execute([$institution_id, $test_id, $userid]);

        $status_result = $status_stmt->fetch(PDO::FETCH_ASSOC);

        if ($status_result) {
            if ($status_result['status'] == 2) {
                // Skip completed tests
                continue;
            }

            $remaining_time = calculateRemainingTime($status_result['exam_start_time'], $total_duration_seconds, $status_result['exit_time']);

            if ($remaining_time <= 0) {
                $remaining_time = 0; // Set remaining time to 0 if auto-submitted
            }

            // Ensure tests with ongoing timers are included
            if ($remaining_time > 0 || $status_result['exit_time'] === null) {
                $array_return[] = formatTestInfo($rows, $total_duration_seconds, $remaining_time, 1, $conn_rjllearning_specific, $institution_id, $userid);
            }
        } else {
            // Test not yet attempted
            $array_return[] = formatTestInfo($rows, $total_duration_seconds, $total_duration_seconds, 0, $conn_rjllearning_specific, $institution_id, $userid);
        }
    }

    return array(
        'total_rows' => $totalrows,
        'test_info' => $array_return,
    );
}











function getPreviousTests($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $class_id, $section_id, $subject_id, $userid) {
    // Initialize the array to return
    $array_return = [];

    // Fetch the total count of tests where both last_date and last_submission_time have ended or tests that have been completed
    $sql_count = "
        SELECT COUNT(DISTINCT t.id) as total_rows
        FROM test t
        LEFT JOIN test_attempt ta
        ON t.id = ta.test_id AND ta.student_id = ? AND ta.status = 2
        WHERE t.institution_id = ?
        AND (
            (t.last_date < NOW() AND t.last_submission_time < NOW())
            OR ta.test_id IS NOT NULL
        )
    ";

    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute([$userid, $institution_id]);
    $result_total = $stmt->fetch(PDO::FETCH_ASSOC);
    $totalrows = $result_total['total_rows'];

 // Base SQL query
$sql = "
    SELECT * 
    FROM (
        (
            SELECT t.*
            FROM test t
            WHERE t.institution_id = ?
            AND t.last_date < NOW()
            AND t.last_submission_time < NOW()
        )
        UNION
        (
            SELECT t.*
            FROM test t
            JOIN test_attempt ta
            ON t.id = ta.test_id
            WHERE ta.student_id = ?
            AND ta.status = 2
            AND t.institution_id = ?
        )
    ) AS combined_tests
";

// Add search string filter if present
if (!empty($search_string)) {
    $sql .= " AND (name LIKE ? OR description LIKE ?)";
    $array_params[] = '%' . $search_string . '%';
    $array_params[] = '%' . $search_string . '%';
}

// Add order by clause
$sql .= " ORDER BY date_created ASC, time_created ASC";

// Prepare and execute the statement
$params = [$institution_id, $userid, $institution_id];
$stmt = $conn_rjllearning_specific->prepare($sql);
$stmt->execute($params);
$result = $stmt->fetchAll();




    // Process each test
    foreach ($result as $rows) {
        $total_duration_seconds = parseTimer($rows['timer']);
        $test_id = $rows['id'];

        // Determine if the test has been attempted
        $attemptQuery = "SELECT * FROM test_attempt WHERE institution_id = ? AND test_id = ? AND student_id = ?";
        $status_stmt = $conn_rjllearning_specific->prepare($attemptQuery);
        $status_stmt->execute([$institution_id, $test_id, $userid]);

        $status_result = $status_stmt->fetch(PDO::FETCH_ASSOC);


        if ($status_result) {
            $has_attempted =$status_result['status'];
            $remaining_time = calculateRemainingTime($status_result['exam_start_time'], $total_duration_seconds, $status_result['exit_time']);

            if ($remaining_time <= 0) {

                $remaining_time = 0; // Set remaining time to 0 if auto-submitted
            }

            // Include the test in the result regardless of timer, since it's a previous test
            $array_return[] = formatTestInfo($rows, $total_duration_seconds, $remaining_time, $has_attempted, $conn_rjllearning_specific, $institution_id, $userid);
        } else {
            // Test not attempted
            $array_return[] = formatTestInfo($rows, $total_duration_seconds, 0, 0, $conn_rjllearning_specific, $institution_id, $userid);
        }
    }

    return array(
        'total_rows' => $totalrows,
        'test_info' => $array_return,
    );
}




function formatTestInfo($rows, $total_duration_seconds, $remaining_time, $has_attempted, $conn_rjllearning_specific, $institution_id, $userid) {
    // Fetch additional info
    $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);
    $class_info = getClass($conn_rjllearning_specific, $institution_id, $rows['class_id']);
    $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $rows['subject_id']);
    $section_id = $rows['section_id'];
    $section_info = [];

    if ($section_id == 'all') {
        $section_info[] = array('section_id' => $section_id, 'section_name' => ucwords($section_id));
    } else {
        $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($section_id)";
        $array_params = [$institution_id]; // Add institution_id to parameters
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute($array_params);
        $section_rows = $stmt->fetchAll();

        foreach ($section_rows as $section_data) {
            $section_info[] = array('section_id' => $section_data['id'], 'section_name' => $section_data['section_name']);
        }
    }

    return array(
        "test_id" => $rows['id'],
        'branch_id' => $branch,
        'class_info' => $class_info,
        'section_id' => $section_info,
        'subject_info' => $subject_info,
        "name" => $rows['name'],
        "description" => $rows['description'],
        "max_points" => $rows['max_points'],
        "publish_date" => $rows['publish_date'],
        "last_date" => $rows['last_date'],
        "publish_time" => $rows['publish_time'],
        "last_submission_time" => $rows['last_submission_time'],
        "timer" => $remaining_time,
        "display_question_by" => $rows['display_question_by'],
        "status" => $has_attempted 
    );
}


// function getPreviousTests($conn_rjllearning_specific, $institution_id, $student_id) {
//     $sql = "
//         SELECT 
//             t.id AS test_id, t.name, t.description, t.max_points, t.publish_date, 
//             t.last_date, t.publish_time, t.last_submission_time, t.timer, t.display_question_by,
//             ta.id AS test_attempt_id, ta.start_time, ta.end_time, ta.status AS attempt_status
//         FROM 
//             test t
//         LEFT JOIN 
//             test_attempt ta 
//         ON 
//             t.id = ta.test_id AND ta.student_id = ?
//         WHERE 
//             t.institution_id = ? AND ta.status IN ('completed', 'cannot_complete')
//     ";

//     $stmt = $conn_rjllearning_specific->prepare($sql);
//     $stmt->execute([$student_id, $institution_id]);
//     $previous_tests = $stmt->fetchAll();

//     return $previous_tests;
// }




function checkTestTimeValidity($conn_rjllearning_specific, $test_id, $institution_id, $branch_id) {
    $testQuery = "
        SELECT 
            publish_date, 
            last_date, 
            publish_time, 
            last_submission_time, 
            timer, 
            NOW() AS current_datetime 
        FROM 
            test 
        WHERE 
            id = ? 
            AND institution_id = ? 
            AND branch_id = ?
    ";
    
    $testStmt = $conn_rjllearning_specific->prepare($testQuery);
    $testStmt->execute([$test_id, $institution_id, $branch_id]);
    $testDetails = $testStmt->fetch(PDO::FETCH_ASSOC);

    if (!$testDetails) {
        errorreturn("Test details not found.");
    }
    
    //  $exitTimeQuery = "
    //     SELECT 
    //         exit_time 
    //     FROM 
    //         test_attempt 
    //     WHERE 
    //         test_id = ? 
    //         AND student_id = ? 
    //         AND institution_id = ? 
    //         AND branch_id = ?
    //     LIMIT 1
    // ";

    // $exitTimeStmt = $conn_rjllearning_specific->prepare($exitTimeQuery);
    // $exitTimeStmt->execute([$test_id, $student_id, $institution_id, $branch_id]);
    // $exitTimeResult = $exitTimeStmt->fetch(PDO::FETCH_ASSOC);

    // if ($exitTimeResult && $exitTimeResult['exit_time'] !== null) {
    //     errorreturn("Test has already been completed and cannot be started again.");
    // }

    $current_datetime = $testDetails['current_datetime'];
    
    $publish_datetime = $testDetails['publish_date'] . ' ' . $testDetails['publish_time'];
    $last_submission_datetime = $testDetails['last_submission_time'] ;
   
    $last_date_datetime = $testDetails['last_date']; // Assuming end of day if `last_date` is a date only

    // Check if test is published
    if ($current_datetime < $publish_datetime) {
        errorreturn("Test is not yet published.");
    }
// var_dump($current_datetime);
// die();

    // Check if test has ended
    if ($current_datetime > $last_date_datetime) {
        errorreturn("Test submission period has ended.");
    }

    // // Check if test can still be submitted based on time
    // if ($current_datetime > $last_submission_datetime) {
    //     errorreturn("Test submission time has ended.");
    // }

    // If all checks pass, return test details
    return $testDetails;
}



function insertTestAttempt($conn_rjllearning_specific, $institution_id, $branch_id, $test_id, $exam_start_time, $exit_time, $student_id, $status) 
{
    try {
        // Check if a record with the same details already exists
        $checkQuery = "SELECT COUNT(*) FROM test_attempt 
                       WHERE institution_id = ? AND branch_id = ? AND test_id = ? AND student_id = ?";
        
        // Prepare the statement
        $checkStmt = $conn_rjllearning_specific->prepare($checkQuery);

        // Execute the statement with provided values
        $checkStmt->execute([$institution_id, $branch_id, $test_id, $student_id]);

        // Fetch the count
        $count = $checkStmt->fetchColumn();

        if ($count > 0) {
            return false; // Record already exists
        }

        // Prepare the SQL query
        $insertQuery = "INSERT INTO test_attempt 
                        (institution_id, branch_id, test_id, exam_start_time, exit_time, student_id, date_created, time_created, status) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        // Prepare the statement
        $stmt = $conn_rjllearning_specific->prepare($insertQuery);

        // Execute the statement with provided values
        $stmt->execute([$institution_id, $branch_id, $test_id, $exam_start_time, $exit_time, $student_id, date('Y-m-d'), date('H:i:s'), $status]);

        // Optionally return the last inserted ID if needed
        return $conn_rjllearning_specific->lastInsertId();
    } catch (PDOException $e) {
        // Handle database errors
        errorReturn("Error: " . $e->getMessage());
        return false; // or throw an exception based on your error handling strategy
    }
}



function getSpecificTest($conn_rjllearning_specific, $test_id, $institution_id, $display_question_by)
{
    $sql = "SELECT * FROM test WHERE id = ? AND institution_id = ? ORDER BY date_created ASC, time_created ASC";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$test_id, $institution_id]);
    $result = $stmt->fetchAll();

    if (count($result) == 1) {
        $test_questions = [];

        $sql = "
            SELECT 
                tq.*, 
                qbi.*, 
                t.*
            FROM 
                test_questions tq
            JOIN 
                question_bank_info qbi 
                ON tq.question_bank_id = qbi.id
            JOIN 
                test t
                ON tq.test_id = t.id
            WHERE 
                tq.test_id = ? 
                AND tq.institution_id = ?
                AND t.display_question_by = ?
            GROUP BY 
                tq.id, 
                qbi.id
        ";

        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([$test_id, $institution_id, $display_question_by]);
        $result_question = $stmt->fetchAll();

        if (count($result_question) >= 1) {
            foreach ($result_question as $temp) {
                $final_array_attachment = null;

                if (isset($temp['question_attachment']) && $temp['question_attachment'] !== null && !is_array($temp['question_attachment'])) {
                    $data_attachment = json_decode($temp['question_attachment'], true);
                    $filePath = $data_attachment['filepath'];
                    $originalName = $data_attachment['original_name'];
                    $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                    $final_array_attachment = array("filepath" => $aws_attachment, "original_name" => $originalName);
                }

                $options = json_decode($temp['options'], true);
                $formatted_options = [];

                if (!is_null($options) && is_array($options)) {
                    foreach ($options as $option) {
                        $formatted_options[] = ['value' => $option];
                    }
                }

                $test_questions[] = array(
                    "test_questions_id" => $temp['id'],
                    "institution_id" => $temp['institution_id'],
                    "branch_id" => $temp['branch_id'],
                    "question_no" => $temp['question_no'],
                    "question_type" => $temp['question_type'],
                    'question_description' => $temp['question_description'],
                    "options" => $formatted_options,
                    "question_attachment" => $final_array_attachment,
                    "question_marks" => $temp['question_marks']
                );
            }

            $section_id = $result[0]['section_id'];
            $section_info = [];
            if ($section_id == 'all') {
                $section_info = array('section_id' => $section_id, 'section_name' => ucwords($section_id));
            } else {
                $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($section_id)";
                $stmt = $conn_rjllearning_specific->prepare($sql);
                $stmt->execute([$institution_id]);
                $section_rows = $stmt->fetchAll();

                foreach ($section_rows as $section_data) {
                    $section_info = array('section_id' => $section_data['id'], 'section_name' => $section_data['section_name']);
                }
            }

            $class_info = getClass($conn_rjllearning_specific, $institution_id, $result[0]['class_id']);
            $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $result[0]['subject_id']);
            $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $result[0]['branch_id']);

            $array_return = array(
                "test_id" => $result[0]['id'],
                'branch_id' => $branch,
                'class_info' => $class_info,
                'section_id' => $section_info,
                'subject_info' => $subject_info,
                "name" => $result[0]['name'],
                "description" => $result[0]['description'],
                "max_points" => $result[0]['max_points'],
                "publish_date" => $result[0]['publish_date'],
                "last_date" => $result[0]['last_date'],
                "publish_time" => $result[0]['publish_time'],
                "last_submission_time" => $result[0]['last_submission_time'],
                "test_questions" => $test_questions
            );

            return $array_return;
        }
    }

    return null;
}


function fetchTestdetails($conn_rjllearning_specific, $test_id, $institution_id, $branch_id) {
    $sql = "SELECT * FROM test WHERE id = ? AND institution_id = ? AND branch_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$test_id, $institution_id, $branch_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($result) {
        return $result; // Ensure 'display_question_by' is included in the result
    } else {
        return false;
    }
}


function checkTestValidity($conn_rjllearning_specific, $test_id, $institution_id, $branch_id) {
    $joinQuery = "
        SELECT 
            t.id AS test_id, 
            t.max_points,
            t.display_question_by,
            q.id AS test_question_id,
            q.question_bank_id,
            qb.question_type,
            qb.question_description,
            qb.answer,
            qb.options,
            qb.question_marks 
        FROM 
            test AS t 
        JOIN 
            test_questions AS q 
            ON t.id = q.test_id 
        JOIN 
            question_bank_info AS qb 
            ON q.question_bank_id = qb.id 
        WHERE 
            t.id = ?  
            AND t.institution_id = ? 
            AND t.branch_id = ?
    ";
    $joinStmt = $conn_rjllearning_specific->prepare($joinQuery);
    $joinStmt->execute([$test_id, $institution_id, $branch_id]);
    $result = $joinStmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$result) {
        errorreturn("Test question or test does not exist.");
    }
    return $result;
   
    
}











function checkExistingTestAttempt($conn_rjllearning_specific, $institution_id, $branch_id, $test_id, $user_id) {
    $query = "
        SELECT id 
        FROM test_attempt 
        WHERE institution_id = ? 
        AND branch_id = ? 
        AND test_id = ? 
        AND student_id = ? 
        AND status = ?
    ";
    $stmt = $conn_rjllearning_specific->prepare($query);
    $stmt->execute([$institution_id, $branch_id, $test_id, $user_id, 1]); // Adjust status as needed
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $result ? $result['id'] : false;
}

function handleTestSubmission($conn_rjllearning_specific, $insertValues) {
    if (!empty($insertValues)) {
        $inserttestQuery = "INSERT INTO test_submission(institution_id, branch_id, class_id, section_id, test_id, test_questions_id, question_attachment, question_text_answer, student_id, student_test_attempt_id, remarks, marks_obtained, points, added_by, time_created, date_created, last_modified_by, status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $inserttestStmt = $conn_rjllearning_specific->prepare($inserttestQuery);

        foreach ($insertValues as $insertData) {
            $inserttestStmt->execute($insertData);
        }

        $test_submission_id = $conn_rjllearning_specific->lastInsertId();
        successreturn(['id' => $test_submission_id, 'successmsg' => "Successfully added test submissions."]);
    } else {
        errorreturn("No valid answer format found.");
    }
}















//step 4
function fetchTestQuestions($conn_rjllearning_specific, $test_id, $institution_id) {
    // Query to fetch test questions along with related question bank info
    $sql = "SELECT 
                tq.id,
                tq.test_id,
                tq.institution_id,
                tq.branch_id,
                tq.question_bank_id,
                qbi.class_id,
                qbi.section_id,
                qbi.subject_id,
                qbi.question_no,
                qbi.question_type,
                qbi.level,
                qbi.question_marks,
                qbi.topic_name,
                qbi.author,
                qbi.question_description,
                qbi.options,
                qbi.answer,
                qbi.question_attachment,
                qbi.status
            FROM 
                test_questions tq
            JOIN 
                question_bank_info qbi
            ON 
                tq.question_bank_id = qbi.id
            WHERE 
                tq.test_id = ? AND tq.institution_id = ?";

    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$test_id, $institution_id]);
    $result_question = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $test_questions = [];
    if (count($result_question) >= 1) {
        foreach ($result_question as $temp) {

            $final_array_attachment = null;

            if (!empty($temp['question_attachment']) && $temp['question_attachment'] !== null && !is_array($temp['question_attachment'])) {
                $data_attachment = json_decode($temp['question_attachment'], true);
                
                if ($data_attachment) {
                    $filePath = $data_attachment['filepath'];
                    $originalName = $data_attachment['original_name'];
                    $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                    $final_array_attachment = array("filepath" => $aws_attachment, "original_name" => $originalName);
                }
            }

            $options = !empty($temp['options']) ? json_decode($temp['options'], true) : [];
            $formatted_options = [];

            if (is_array($options)) {
                foreach ($options as $option) {
                    $formatted_options[] = ['value' => $option];
                }
            }

            $test_questions[] = array(
                "test_questions_id" => $temp['id'],
                "institution_id" => $temp['institution_id'],
                "branch_id" => $temp['branch_id'],
                "question_no" => $temp['question_no'],
                "question_type" => $temp['question_type'],
                'question_description' => $temp['question_description'],
                "options" => $formatted_options,
                "question_attachment" => $final_array_attachment,
                "question_marks" => $temp['question_marks']
            );
        }
    }

    return $test_questions;
}



//step 2

function handleNewAttempt($conn_rjllearning_specific, $institution_id, $branch_id, $test_id, $student_id, $exam_start_time, $exit_time) {
    // Insert a new test attempt
    $insertQuery = "INSERT INTO test_attempt (institution_id, branch_id, test_id, exam_start_time,question_counter, exit_time, student_id, date_created, time_created, status) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
    $stmt = $conn_rjllearning_specific->prepare($insertQuery);
    $stmt->execute([$institution_id, $branch_id, $test_id, $exam_start_time,'0', null, $student_id, date('Y-m-d'), date('H:i:s'), '1']);

    return $conn_rjllearning_specific->lastInsertId();
}






//step 5 (all)
// function startOrContinueTest($conn_rjllearning_specific, $institution_id, $branch_id, $test_id, $class_id, $section_id, $student_id, $display_question_by) {
//     // Fetch test questions
//     $test_questions = fetchTestQuestions($conn_rjllearning_specific, $test_id, $institution_id);
    
// //   var_dump($test_id);
// //   die();

//     // Check if the student has already attempted the test
//     $attemptQuery = "SELECT * FROM test_attempt WHERE institution_id=? AND test_id = ? AND student_id = ?";
//     $attemptStmt = $conn_rjllearning_specific->prepare($attemptQuery);
//     $attemptStmt->execute([$institution_id,$test_id, $student_id]);

//     $attempt = $attemptStmt->fetch(PDO::FETCH_ASSOC);
    
    

//     if ($attempt) {
//         if ($attempt['status'] == 'Pending') {
//             // Continue the test
//             if ($display_question_by == 0) {
//                 // Display all questions at once
//                 successreturn (['questions' => $test_questions]);
//             } else {
//                 // Display one question at a time
//                                 $question_counter = $attempt['question_counter'] ?? 0;
                
//                 // Ensure the counter is within the range of available questions
//                 if ($question_counter >= count($test_questions)) {
//                     errorreturn('No more questions available.');
//                 }
                
//                 // Fetch the current question based on the counter
//                 $current_question = $test_questions[$question_counter];
                
//                 successreturn(['question' => $current_question, 'question_counter' => $question_counter]);
//  // Adjust as per your logic for one-by-one question display
//             }
//         } 
//         else {
//             // Test already completed
//             errorreturn ('Test already completed');
//         }
//     } else {
//         // New attempt
//         $exam_start_time = date('Y-m-d H:i:s');
//         $exit_time = date('Y-m-d H:i:s');
//         $attempt_id = handleNewAttempt($conn_rjllearning_specific, $institution_id, $branch_id, $test_id, $student_id, $exam_start_time, $exit_time);
        
      
        
//         if ($display_question_by == 0) {
//             // Display all questions at once
//             successreturn (['attempt_id' => $attempt_id, 'questions' => $test_questions]);
//         } else {
//             // Display one question at a time
//             successreturn (['attempt_id' => $attempt_id, 'questions' => [$test_questions[0]]]); // Adjust as per your logic for one-by-one question display
//         }
//     }
// }
function parseTimer($timer) {
    $total_seconds = 0;

    // Match hours and minutes using regular expression
    if (preg_match('/(\d+)\s*h/', $timer, $matches)) {
        $total_seconds += $matches[1] * 3600; // Convert hours to seconds
    }

    if (preg_match('/(\d+)\s*m/', $timer, $matches)) {
        $total_seconds += $matches[1] * 60; // Convert minutes to seconds
    }

    return $total_seconds;
}


function calculateRemainingTime($start_time, $total_duration_seconds, $exit_time = null) {
    $current_time = time();
    $start_timestamp = strtotime($start_time);

    if ($exit_time) {
        $exit_timestamp = strtotime($exit_time);
        $elapsed_time = $exit_timestamp - $start_timestamp;
    } else {
        $elapsed_time = $current_time - $start_timestamp;
    }

    return $total_duration_seconds - $elapsed_time;
}





function startOrContinueTest($conn_rjllearning_specific, $institution_id, $branch_id, $test_id, $class_id, $section_id, $student_id, $display_question_by) {
    // Fetch test questions

    $test_questions = fetchTestQuestions($conn_rjllearning_specific, $test_id, $institution_id);

    // Check if the student has already attempted the test
    $attemptQuery = "SELECT * FROM test_attempt WHERE institution_id=? AND test_id = ? AND student_id = ?";
    $attemptStmt = $conn_rjllearning_specific->prepare($attemptQuery);
    $attemptStmt->execute([$institution_id, $test_id, $student_id]);

    $attempt = $attemptStmt->fetch(PDO::FETCH_ASSOC);
    
                 $questionCountQuery = "
        SELECT COUNT(*) AS total_questions 
        FROM test_questions 
        WHERE test_id = ? AND institution_id = ? 
    ";
    $questionCountStmt = $conn_rjllearning_specific->prepare($questionCountQuery);
    $questionCountStmt->execute([$test_id, $institution_id]);
    $questionCountResult = $questionCountStmt->fetch(PDO::FETCH_ASSOC);
    
    $total_questions = $questionCountResult['total_questions'];

    if ($attempt) {
        // If test has been attempted but bypass "already completed" check for testing
        if ($attempt['status'] == 'Pending') {
            if ($display_question_by == 0) {
                // Display all questions at once
                successreturn(['questions' => $test_questions,"total_questions" => $total_questions,]);
            } else {
                // Display one question at a time
                $question_counter = $attempt['question_counter'] ?? 0;
                
                // Ensure the counter is within the range of available questions
                if ($question_counter >= count($test_questions)) {
                    errorreturn('No more questions available.');
                }
                
                // Fetch the current question based on the counter
                $current_question = $test_questions[$question_counter];
                
                successreturn(['question' => $current_question,"total_questions" => $total_questions, 'question_counter' => $question_counter]);
            }
        } else {
            // Temporarily bypass "Test already completed" message
            if ($display_question_by == 0) {
                // Display all questions at once
                successreturn(['questions' => $test_questions,"total_questions" => $total_questions,]);
            } else {
                // Display one question at a time
                $question_counter = $attempt['question_counter'] ?? 0;

                // Ensure the counter is within the range of available questions
                if ($question_counter >= count($test_questions)) {
                    errorreturn('No more questions available.');
                }

                // Fetch the current question based on the counter
                $current_question = $test_questions[$question_counter];
                
                successreturn(['question' => $current_question,"total_questions" => $total_questions, 'question_counter' => $question_counter]);
            }
        }
    } else {
        // New attempt
        $exam_start_time = date('Y-m-d H:i:s');
        $exit_time = date('Y-m-d H:i:s');
        $attempt_id = handleNewAttempt($conn_rjllearning_specific, $institution_id, $branch_id, $test_id, $student_id, $exam_start_time, $exit_time);

        if ($display_question_by == 0) {
            // Display all questions at once
            successreturn(['attempt_id' => $attempt_id, 'questions' => $test_questions]);
        } else {
            // Display one question at a time
            successreturn(['attempt_id' => $attempt_id, 'question' => $test_questions[0], 'question_counter' => 0]);
        }
    }
}


// function startOrContinueTest($conn_rjllearning_specific, $institution_id, $branch_id, $test_id, $class_id, $section_id, $student_id, $display_question_by) {
//     // Fetch test timer from the test table
//     $testQuery = "SELECT timer FROM test WHERE institution_id = ? AND id = ?";
//     $testStmt = $conn_rjllearning_specific->prepare($testQuery);
//     $testStmt->execute([$institution_id, $test_id]);
//     $testDetails = $testStmt->fetch(PDO::FETCH_ASSOC);
    
//     if (!$testDetails) {
//         errorreturn('Test not found.');
//     }
    
//     $total_duration_seconds = parseTimer($testDetails['timer']); // Convert timer string to seconds
    

//     $test_questions = fetchTestQuestions($conn_rjllearning_specific, $test_id, $institution_id);

//     // Check if the student has already attempted the test
//     $attemptQuery = "SELECT * FROM test_attempt WHERE institution_id=? AND test_id = ? AND student_id = ?";
//     $attemptStmt = $conn_rjllearning_specific->prepare($attemptQuery);
//     $attemptStmt->execute([$institution_id, $test_id, $student_id]);

//     $attempt = $attemptStmt->fetch(PDO::FETCH_ASSOC);

//     if ($attempt) {
//         // Calculate the remaining time
//         $remaining_time = calculateRemainingTime($attempt['exam_start_time'], $total_duration_seconds, $attempt['exit_time']);
//         // var_dump($remaining_time);
//         // die();
        
//         if ($remaining_time <= 0) {
//             // autoSubmitTest($conn_rjllearning_specific, $attempt['id']);
//             errorreturn('Test time is over, and it has been auto-submitted.');
//         }

//         if ($display_question_by == 0) {
//             successreturn(['questions' => $test_questions, 'remaining_time' => $remaining_time]);
//         } else {
//             $question_counter = $attempt['question_counter'] ?? 0;

//             if ($question_counter >= count($test_questions)) {
//                 errorreturn('No more questions available.');
//             }

//             $current_question = $test_questions[$question_counter];
//             successreturn(['question' => $current_question, 'question_counter' => $question_counter, 'remaining_time' => $remaining_time]);
//         }
//     } else {
//         // New attempt
//         $exam_start_time = date('Y-m-d H:i:s');
//         $exit_time = date('Y-m-d H:i:s');
//         $attempt_id = handleNewAttempt($conn_rjllearning_specific, $institution_id, $branch_id, $test_id, $student_id, $exam_start_time, $exit_time);

//         if ($display_question_by == 0) {
//             successreturn(['attempt_id' => $attempt_id, 'questions' => $test_questions, 'remaining_time' => $total_duration_seconds]);
//         } else {
//             successreturn(['attempt_id' => $attempt_id, 'question' => $test_questions[0], 'question_counter' => 0, 'remaining_time' => $total_duration_seconds]);
//         }
//     }
// }


function processTestSubmission($conn_rjllearning_specific,$institution_id,$branch_id,$test_id,$display_question_by,$postdata,$workspace_id,$userid,$class_id,$section_id,$student_test_attempt_id,$remarks,$points,$username,$status) {
    // Fetch test questions
    $testQuery = "
    SELECT 
        qbi.id AS question_bank_id, 
        qbi.question_type, 
        qbi.question_description, 
        qbi.answer, 
        qbi.options,
        tq.test_id
    FROM 
        question_bank_info qbi
    JOIN 
        test_questions tq 
        ON qbi.id = tq.question_bank_id
    WHERE 
        tq.institution_id = ? 
        AND tq.branch_id = ? 
        AND tq.test_id = ?
    ";
    $testStmt = $conn_rjllearning_specific->prepare($testQuery);
    $testStmt->execute([$institution_id, $branch_id, $test_id]);
    $testQuestions = $testStmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$testQuestions) {
        errorreturn("Test questions do not exist.");
    }

    // Initialize variables
    $insertValues = []; // Array to hold multiple insert values

    if (isset($postdata['question_text_answer']) && !empty($postdata['question_text_answer'])) {
        // Check if it's already decoded or still a JSON string
        $question_text_answer = is_array($postdata['question_text_answer']) ? $postdata['question_text_answer'] : json_decode($postdata['question_text_answer'], true);

        if (!is_array($question_text_answer)) {
            errorreturn("Invalid JSON format for 'question_text_answer'.");
        }
        
        foreach ($question_text_answer as  $index => $answer) {
            // $file_key = 'file_' . $answer['test_questions_id'];
          $file_key = 'question_text_answer[' . $index . '][answer_file_attached]';

if (isset($_FILES['question_text_answer']) && isset($_FILES['question_text_answer']['name'][$index]['answer_file_attached'])) {
    // Access the file data
    $question_attachment = [
        'name' => $_FILES['question_text_answer']['name'][$index]['answer_file_attached'],
        'type' => $_FILES['question_text_answer']['type'][$index]['answer_file_attached'],
        'tmp_name' => $_FILES['question_text_answer']['tmp_name'][$index]['answer_file_attached'],
        'error' => $_FILES['question_text_answer']['error'][$index]['answer_file_attached'],
        'size' => $_FILES['question_text_answer']['size'][$index]['answer_file_attached'],
    ];
    
 

                $response[] = [
                    'test_questions_id' => $answer['test_questions_id'],
                    'answer' => $answer['answer'],
                    'file' => $question_attachment,
                ];
            } else {
                $response[] = [
                    'test_questions_id' => $answer['test_questions_id'],
                    'answer' => $answer['answer'],
                    'file' => null,
                ];
            }

            // Print the results for debugging
            
        }

       foreach ($response as $rows) {
           
            $test_questions_id = trim($rows['test_questions_id']);
            $student_selected_answer = trim($rows['answer']);
            //  $question_attachment = isset($rows['file']) ? ($rows['file']) : null;
             
        // $test_questions_id = isset($rows['test_questions_id']) ? trim($rows['test_questions_id']) : null;
        
            // $student_selected_answer = isset($rows['answer']) ? trim($rows['answer']) : null;
            $question_attachment = isset($rows['file']) ? ($rows['file']) : null;

            // Validate if test_questions_id and student_selected_answer are not empty
            if (!$test_questions_id) {
                errorreturn("Invalid format.");
            }

            // Fetch correct answer and marks from database based on test_questions_id
            $sqlAnswers = "
                SELECT 
                    qbi.answer, 
                    qbi.question_type, 
                    qbi.options,
                    tq.question_marks 
                FROM 
                    test_questions tq
                JOIN 
                    question_bank_info qbi 
                ON 
                    tq.question_bank_id = qbi.id 
                WHERE 
                    tq.test_id = ? 
                    AND tq.id = ? 
                    AND tq.institution_id = ? 
                    AND tq.branch_id = ?
            ";
            $stmtAnswers = $conn_rjllearning_specific->prepare($sqlAnswers);
            $stmtAnswers->execute([$test_id, $test_questions_id, $institution_id, $branch_id]);
            $result_answers = $stmtAnswers->fetch(PDO::FETCH_ASSOC);

            if (!$result_answers) {
                errorreturn("Test question with ID $test_questions_id does not exist.");
            }

            // Extract correct answer and marks from result
            $correct_answer = $result_answers['answer'];
            $question_marks = $result_answers['question_marks'];
            $question_type = $result_answers['question_type'];

            // Calculate marks obtained based on student's answer
            $marks_obtained = 0;
            if ($question_type === 'mcq') {
                // Check for MCQ options and correct answer
                $options = json_decode($result_answers['options'], true);
                if (empty($options)) {
                    errorreturn("MCQ question must have options.");
                }

                // Calculate marks for MCQ
                $marks_obtained = ($student_selected_answer == $correct_answer) ? $question_marks : 0;
            }
            if ($question_attachment !== null) {
                // Directory path for storing uploaded files
                $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/question_attachment/" . date('Y') . "/" . date('m') . "/";

                // Single file upload
                $file_name = $question_attachment['name'];
                $fileTmpName = $question_attachment["tmp_name"];
                $fileSize = $question_attachment["size"];
                $fileType = $question_attachment["type"];
                $fileError = $question_attachment["error"];
                $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

                $allowedTypes = [
                    'image/jpeg', 'image/png', 'image/gif', 'image/heic',
                    'application/pdf',
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    'application/vnd.ms-excel',
                    'application/msword',
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                ];
                $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
                $maxFileSize = 25 * 1024 * 1024; // Maximum file size 25 MB

                checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);

                $keyName = $directoryPathMain . $userid . "_" . time() . '.' . $file_extension;
                //$question_attachment_name = time() . "." . $file_extension;

                $question_attachment = json_encode(array("filepath" => $keyName, "original_name" => $file_name));
            } else {
                $question_attachment = null;
            }

           $insertValues[] = [
                $institution_id,             
                $branch_id,
                $class_id,
                $section_id,
                $test_id,
                $test_questions_id,
                $question_attachment,
                $student_selected_answer,
                $marks_obtained,
                $userid,
                $remarks,
                $points,
                $username,
                $student_test_attempt_id,
                time(),
                date('Y-m-d'),
                null,
                $status
            ];
        }
    }

    // Process test submission
  if ($display_question_by == 1) {
        // Update question counter
        $sql = "UPDATE test_attempt SET question_counter = question_counter + 1 WHERE id=? AND test_id = ? AND institution_id = ? AND student_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([$student_test_attempt_id, $test_id, $institution_id, $userid]);

        // Fetch answered questions count
        $sql_count = "SELECT COUNT(*) as answered_questions FROM test_submission WHERE test_id = ? AND institution_id = ? AND student_id = ?";
        $stmt_count = $conn_rjllearning_specific->prepare($sql_count);
        $stmt_count->execute([$test_id, $institution_id, $userid]);
        $result_count = $stmt_count->fetch();

        // Fetch total questions in the test
        $sql_total = "SELECT COUNT(*) as total_questions FROM test_questions WHERE test_id = ? AND institution_id = ?";
        $stmt_total = $conn_rjllearning_specific->prepare($sql_total);
        $stmt_total->execute([$test_id, $institution_id]);
        $result_total = $stmt_total->fetch();

        // Insert the current question's submission
        $insertQuery = "
            INSERT INTO test_submission (
                institution_id, branch_id, class_id, section_id, test_id, test_questions_id, 
                question_attachment, question_text_answer, marks_obtained, student_id, 
                remarks, points, added_by, student_test_attempt_id, time_created, date_created, 
                last_modified_by, status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ";
        $insertStmt = $conn_rjllearning_specific->prepare($insertQuery);
        
        // Execute the insertion for the current question
        foreach ($insertValues as $values) {
            $insertStmt->execute($values);
        }

        // Check if all questions have been answered
        if ($result_count['answered_questions'] + 1 >= $result_total['total_questions']) {
            // Last question answered, return success message for complete test submission
            successreturn(['id' => $student_test_attempt_id, 'successmsg' => "Test submitted successfully."]);
        } else {
            // Not the last question, return success message for question submission
            successreturn(['successmsg' => "Question submitted successfully."]);
        }
    }else {
        
         $sql_total = "SELECT COUNT(*) as total_questions FROM test_questions WHERE test_id = ? AND institution_id = ?";
    $stmt_total = $conn_rjllearning_specific->prepare($sql_total);
    $stmt_total->execute([$test_id, $institution_id]);
    $result_total = $stmt_total->fetch();

    $sql_update_counter = "UPDATE test_attempt SET question_counter = ? WHERE id = ? AND test_id = ? AND institution_id = ? AND student_id = ?";
    $stmt_update_counter = $conn_rjllearning_specific->prepare($sql_update_counter);
    $stmt_update_counter->execute([$result_total['total_questions'], $student_test_attempt_id, $test_id, $institution_id, $userid]);

        // Store all answers at once for all questions display
        $insertQuery = "
            INSERT INTO test_submission (
                institution_id, 
                branch_id, 
                class_id, 
                section_id, 
                test_id, 
                test_questions_id, 
                question_attachment, 
                question_text_answer, 
                marks_obtained, 
                student_id,
                remarks,
                points, 
                added_by,
                student_test_attempt_id, 
                time_created, 
                date_created, 
                last_modified_by, 
                status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ";
        $insertStmt = $conn_rjllearning_specific->prepare($insertQuery);
        foreach ($insertValues as $values) {
            $insertStmt->execute($values);
        }
        
         // Update the question_counter to the total number of questions
  
        return true; // Submission processed for all questions at once
    }
}

