<?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';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.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,["teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
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_type = trim($postdata['function_type']);

$Faculty_Codes = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$Faculty_Codes->execute(array($userid, $institution_id, $branch_id));

// Fetch a single row instead of all
$result_faculty = $Faculty_Codes->fetch(PDO::FETCH_ASSOC);

// Check if the faculty exists
if ($result_faculty === false) {
    errorreturn("Faculty Not Found.");
}

// Retrieve the faculty_id from the result
$faculty_id = $result_faculty['id'];

function getAllStudents($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $assignment_id, $assignment_date, $assignment_academic_id, $check_academic_confirmation_id, $limit, $offset)
{
    // Initialize variables to store the total number of students and attempted students
    $total_students = 0;
    $total_attempted_Students = 0;
    $array_return = [];

    // If the academic session is active (matching the academic_id with check_academic_confirmation_id)
    $fetched_academic_session = compareDatesAcademicSession($conn_rjllearning_specific, $institution_id, $assignment_date, null);
        // Fetch all students for the active academic session
       if ($assignment_date == date("Y-m-d")) {
            // Fetch total students for the current academic session
            $sql = "SELECT COUNT(id) AS total_rows 
                    FROM students 
                    WHERE institution_id = ? 
                      AND branch_id = ? 
                      AND class_id = ? 
                      AND section_id = ? 
                      AND date_admission <= ? 
                      AND (date_left > ? OR date_left IS NULL)";
            $array_params = [$institution_id, $branch_id, $class_id, $section_id, $assignment_date, $assignment_date];
            $validate_student = $conn_rjllearning_specific->prepare($sql);
            $validate_student->execute($array_params);
            $result_total = $validate_student->fetch(PDO::FETCH_ASSOC);
            $total_students = $result_total['total_rows'];
        
            // Fetch students who have submitted assignments for the current academic session
            $sql = "SELECT COUNT(DISTINCT a.student_id) AS total_rows 
                    FROM students AS s 
                    JOIN assignment_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.academic_id = ? 
                      AND s.status = ?";
            $array_params = [$institution_id, $branch_id, $class_id, $section_id, $fetched_academic_session['academic_session_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 students for the current academic session
            $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 AS s 
                    WHERE s.institution_id = ? 
                      AND s.branch_id = ? 
                      AND s.class_id = ? 
                      AND s.section_id = ? 
                      AND s.date_admission <= ? 
                      AND (s.date_left > ? OR s.date_left IS NULL)";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute([$institution_id, $branch_id, $class_id, $section_id, $assignment_date, $assignment_date]);
            $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } else {
            // Fetch total students for older academic sessions
            $sql = "SELECT COUNT(*) AS total_students 
                    FROM students 
                    WHERE institution_id = ? 
                      AND branch_id = ? 
                      AND date_admission <= ? 
                      AND (date_left > ? OR date_left IS NULL) 
                      AND id IN (
                          SELECT student_id 
                          FROM cache_academic_students_data 
                          WHERE class_id = ? 
                            AND section_id = ? 
                            AND (date, student_id) IN (
                                SELECT MAX(date), student_id 
                                FROM cache_academic_students_data 
                                WHERE institution_id = ? 
                                  AND branch_id = ? 
                                  AND date <= ? 
                                GROUP BY student_id
                            )
                      )";
            $array_params = [$institution_id, $branch_id, $assignment_date, $assignment_date, $class_id, $section_id, $institution_id, $branch_id, $assignment_date];
            $validate_student = $conn_rjllearning_specific->prepare($sql);
            $validate_student->execute($array_params);
            $result_total = $validate_student->fetch(PDO::FETCH_ASSOC);
            $total_students = $result_total['total_students'];
        
            // Fetch students who have submitted assignments for older sessions
            $sql = "SELECT COUNT(DISTINCT a.student_id) AS total_rows 
                    FROM students AS s 
                    JOIN assignment_submission AS a 
                      ON s.user_id = a.student_id 
                    JOIN cache_academic_students_data AS c 
                      ON s.user_id = c.student_id 
                    WHERE s.institution_id = ? 
                      AND s.branch_id = ? 
                      AND (s.date_left IS NULL OR s.date_left > ?)";
            $array_params = [$institution_id, $branch_id, $assignment_date];
            $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 students for older academic sessions
            $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 AS s 
                    WHERE s.institution_id = ? 
                      AND s.branch_id = ? 
                      AND s.date_admission <= ? 
                      AND (s.date_left > ? OR s.date_left IS NULL) 
                      AND s.id IN (
                          SELECT student_id 
                          FROM cache_academic_students_data 
                          WHERE class_id = ? 
                            AND section_id = ? 
                            AND (date, student_id) IN (
                                SELECT MAX(date), student_id 
                                FROM cache_academic_students_data 
                                WHERE institution_id = ? 
                                  AND branch_id = ? 
                                  AND date <= ? 
                                GROUP BY student_id
                            )
                      )";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $array_params = [$institution_id, $branch_id, $assignment_date, $assignment_date, $class_id, $section_id, $institution_id, $branch_id, $assignment_date];
            $stmt->execute($array_params);
            $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        // Process the students and their assignment data
        foreach ($students as $student) {
            // Fetch assignments for the student in the active academic session
            $sqlAssignments = "SELECT student_id, SUM(marks_obtained) AS total_marks_obtained, points, 
                              GROUP_CONCAT(DISTINCT id ORDER BY id ASC) AS assignment_ids, 
                              GROUP_CONCAT(DISTINCT status ORDER BY id ASC) AS statuses 
                              FROM assignment_submission 
                              WHERE student_id = ? AND institution_id = ? AND branch_id = ? AND class_id = ? AND section_id = ? AND assignment_id = ?  
                              GROUP BY student_id ORDER BY id ASC";
            $stmtAssignments = $conn_rjllearning_specific->prepare($sqlAssignments);
            $stmtAssignments->execute([$student['user_id'], $institution_id, $branch_id, $class_id, $section_id, $assignment_id]);
            $assignments = $stmtAssignments->fetchAll(PDO::FETCH_ASSOC);

            // Check if the student has assignments
            if (count($assignments) > 0) {
                $assignment_ids = explode(',', $assignments[0]['assignment_ids']);
                $statuses = explode(',', $assignments[0]['statuses']);
                $total_marks_obtained = $assignments[0]['total_marks_obtained'];
                $points = $assignments[0]['points'];

                // Calculate total points obtained
                $total_points_obtained = $total_marks_obtained + $points;

                // Determine assignment status based on the first status in the array
                $status = "Not Submitted"; // Default status
                if (isset($statuses[0])) {
                    if ($statuses[0] == 1) {
                        $status = "Submitted";
                    } else if ($statuses[0] == 2) {
                        $status = "Checked";
                    }
                }

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

    // Check assignment 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'] == "assignment_submission_students") {
   
    $class_id = trim($postdata['class_id']);
    $section_id = trim($postdata['section_id']);
    // errorreturn($section_id);
    $assignment_id = trim($postdata['assignment_id']);
    
    $teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    $class_section_subjects  = $teacher_data['class_section_subjects'];
    // errorreturn($class_section_subjects);
    $class_incharge_roles = $teacher_data['class_incharge_roles'];
    $staff_access_modules = $teacher_data['staff_access_modules'];
    
    $sql = "SELECT subject_id FROM assignments WHERE institution_id = ? AND id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$institution_id, $assignment_id]);
    $assignment_subject = $stmt->fetchColumn();
    
    $check_faculty_status = checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, $assignment_subject, $conn_rjllearning);
    if($check_faculty_status == false){
        errorreturn("Access denied: You do not have the required permissions.");
    }
    
    
    $sql = "SELECT last_date FROM assignments WHERE institution_id = ? AND id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);  // Prepare the SQL statement
    $stmt->execute([$institution_id, $assignment_id]);  // Execute the statement with parameters
    // Fetch the result
    $assignment_date = $stmt->fetchAll()[0]['last_date'];

    $assignment_academic_id = findAcademicSession($conn_rjllearning_specific, 'assignments', $assignment_id, $institution_id);

    $check_academic_confirmation_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation_id != 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, $assignment_id, $assignment_date, $assignment_academic_id, $check_academic_confirmation_id, $limit, $offset);
    successreturn($success);
}