<?php
ini_set('display_errors', 1);

require_once '../../../../resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

// Validation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
// DB access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
//aws image store
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";

require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = json_decode(file_get_contents("php://input"), true);
// print_r($postdata);die();
checkIfNoPhpContentsReceive();

if (
    // !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or
    !isset($postdata['jwt_token']) or  !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}
validateApiSignature($postdata['api_signature']);
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning, $conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

function getAllStudents($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $test_id, $limit, $offset)
{

    $sql = "SELECT COUNT(id) AS total_rows FROM students WHERE  institution_id = ? AND branch_id = ? AND class_id = ? AND section_id = ? AND status = ? ";
    $array_params = [$institution_id, $branch_id, $class_id, $section_id, 1];
    $validate_student = $conn_rjllearning_specific->prepare($sql);
    $validate_student->execute($array_params);
    $result_total = $validate_student->fetchAll();
    $total_students = $result_total[0]['total_rows'];

    $sql = "
    SELECT COUNT(DISTINCT user_id) AS total_rows
    FROM students  AS s
    JOIN test_submission  AS a ON s.user_id = a.student_id 
    WHERE s.institution_id = ? 
      AND s.branch_id = ? 
      AND s.class_id = ? 
      AND s.section_id = ? 
      AND s.status = ?";
    $array_params = [$institution_id, $branch_id, $class_id, $section_id, 1];
    $validate_student = $conn_rjllearning_specific->prepare($sql);
    $validate_student->execute($array_params);
    $result_total = $validate_student->fetch(PDO::FETCH_ASSOC);
    $total_attempted_Students = $result_total['total_rows'];


    // Fetch the students
    $sql = "
    SELECT DISTINCT s.user_id, s.id, s.name, s.fathername, s.class_id, s.section_id, s.institution_id, s.branch_id, s.status 
    FROM students s
    WHERE s.institution_id = ? 
      AND s.branch_id = ? 
      AND s.class_id = ? 
      AND s.section_id = ? 
      AND s.status = ? 
    ORDER BY s.id ASC 
    ";
    $sql .= "LIMIT " . $offset . " ," . $limit;
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$institution_id, $branch_id, $class_id, $section_id, 1]);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    // print_r($students);die();
    $array_return = [];
    $sqlquizs = "SELECT student_id, 
                              SUM(marks_obtained) as total_marks_obtained,
                              GROUP_CONCAT(DISTINCT id ORDER BY id ASC) as quiz_ids,
                              GROUP_CONCAT(DISTINCT status ORDER BY id ASC) as statuses 
                       FROM test_submission 
                       WHERE student_id = ? AND institution_id = ? AND branch_id = ? AND class_id = ? AND section_id = ? AND test_id = ?
                       GROUP BY student_id";
    $sqlquizs .= " ORDER BY id ASC ";
    foreach ($students as $student) {
       // echo $student['user_id'], $institution_id, $branch_id, $class_id, $section_id, $test_id;
        // Fetch distinct quizs for each student
        $stmtquizs = $conn_rjllearning_specific->prepare($sqlquizs);
        $stmtquizs->execute([$student['user_id'], $institution_id, $branch_id, $class_id, $section_id, $test_id]);
        $quizs = $stmtquizs->fetchAll();
        
        if (count($quizs) >= 1) {
           // echo 'here';
            
            //foreach ($quizs as $quiz) {
            $quiz_ids = explode(',', $quizs[0]['quiz_ids']);
            $statuses = explode(',', $quizs[0]['statuses']);


            // Ensure the status index exists
            //$status = isset($statuses[0]) && $statuses[0] == 1 ? "Submitted" : "Not Submitted" ;
            if (isset($statuses[0]) && $statuses[0] == 1) {
                $status = "Submitted";
            } else if (isset($statuses[0]) && $statuses[0] == 2) {
                $status = "Checked";
            }

            $array_return[] = array(
                "student_id" => $student['user_id'],
                //"quiz_ids" => $quiz_ids,
                "name" => $student['name'],
                "fathername" => $student['fathername'],
                "quiz_status" => $status,
                "marks_obtained" => $quizs[0]['total_marks_obtained']
            );

            //}
        } else {
            // No quizs found for this student
            $array_return[] = array(
                "student_id" => $student['user_id'],
                "name" => $student['name'],
                "fathername" => $student['fathername'],
                //"quiz_id" => null,
                "quiz_status" => "Not Submitted",
                "marks_obtained" => null
            );
        }
    }

    // Check quiz count and return the response
    if (count($array_return) < 50) {
        return array(
            'total_student' => $total_students,
            'total_attempted_students' => $total_attempted_Students,
            'students_info' => $array_return,
            'maxreach' => 1
        );
    } else {
        return array(
            'total_student' => $total_students,
            'total_attempted_students' => $total_attempted_Students,
            'students_info' => $array_return,
            'maxreach' => 0
        );
    }
}


if ($postdata['function_type'] == "test_submission_students") {
    
    $class_id = trim($postdata['class_id']);
    $section_id = trim($postdata['section_id']);
    $test_id = trim($postdata['test_id']);

    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;
    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
    } else {
        $offset =  null;
    }
    $success['data'] = getAllStudents($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $test_id, $limit, $offset);
    successreturn($success);
}
