<?php

ini_set('display_errors', 1);

require_once '../../../../resources/base_path_include.php';

require_once $base_path_to_learning_resources . "includes/connect.php";
require_once $base_path_to_learning_resources . "lib/function.php";
require_once $base_path_to_learning_resources . "lib/validate_api_signature.php";
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';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning_resources . "includes/specific_db_config.php";
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 . "user_management/functions/functions.php";

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

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

checkIfNoPhpContentsReceive();

// Define the required fields in an array
$requiredFields = [
    'institution_id',
    'branch_id',
    'class_id',
    'marksheet_id',
    'api_signature',
    'function_type',
    'jwt_token'
];

// Loop through each required field and check if it is set and not empty
foreach ($requiredFields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.$field");
    }
}

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;

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


function fetch_students_details($institution_id, $branch_id, $class_id, $marksheet_id, $date, $active_session, $conn_rjllearning_specific) {

    $fetched_academic_session = compareDatesAcademicSession($conn_rjllearning_specific, $institution_id, $date, null);
    
    if ($date == date("Y-m-d")) {
        $sql = "SELECT id AS student_id, name, fathername, branch_id, class_id, section_id, can_activate 
                FROM students 
                WHERE institution_id = ? 
                AND branch_id = ? 
                AND class_id = ?  
                AND date_admission <= ? 
                AND (date_left > ? OR date_left IS NULL)
                ORDER BY name ASC";  // 🔹 Sort by name
        $fetch_students = $conn_rjllearning_specific->prepare($sql);
        $fetch_students->execute([$institution_id, $branch_id, $class_id, $date, $date]);
        $students = $fetch_students->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $sql = "SELECT id AS student_id, name, fathername, branch_id, class_id, section_id, can_activate 
                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 (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
                    )
                )
                ORDER BY name ASC";  // 🔹 Sort by name
        $fetch_students = $conn_rjllearning_specific->prepare($sql);
        $fetch_students->execute([$institution_id, $branch_id, $date, $date, $class_id, $institution_id, $branch_id, $date]);
        $students = $fetch_students->fetchAll(PDO::FETCH_ASSOC);
    }

    // Process students data
    $student_details = [];
    foreach ($students as $student) {

        $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $student['branch_id']);
        $section = getSection($conn_rjllearning_specific, $institution_id, $student['section_id']);
        $class_info = getClass($conn_rjllearning_specific, $institution_id, $student['class_id']);

        $marksheet_sql = "SELECT COUNT(*) AS marks_count 
                          FROM student_marksheet_data 
                          WHERE student_id = ? AND class_id = ? AND section_id = ? AND marksheet_id = ?";
        $marksheet_stmt = $conn_rjllearning_specific->prepare($marksheet_sql);
        $marksheet_stmt->execute([$student['student_id'], $student['class_id'], $student['section_id'], $marksheet_id]);
        $marksheet_data = $marksheet_stmt->fetch();

        $marks_upload_status = ($marksheet_data['marks_count'] > 0) ? 'Complete' : 'Incomplete';
        $student_status = ($student['can_activate'] == 0) ? '1' : '0';

        $student_details[] = [
            'student_id' => $student['student_id'],
            'student_name' => $student['name'],
            'fathers_name' => $student['fathername'],
            'branch' => $branch,
            'class' => $class_info,
            'section' => $section,
            'student_status' => $student_status,
            'marks_upload_status' => $marks_upload_status,
        ];
    }

    return $student_details;
}

// Main logic
if ($postdata['function_type'] == "fetch_students_details") {
    $institution_id = trim($postdata['institution_id']);
    $marksheet_id = trim($postdata['marksheet_id']);
    $branch_id = isset($postdata['branch_id']) ? trim($postdata['branch_id']) : 'all';
    $class_id = isset($postdata['class_id']) ? trim($postdata['class_id']) : 'all';

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

    $date = date('Y-m-d');
    $fetched_academic_session = compareDatesAcademicSession($conn_rjllearning_specific, $institution_id, $date, null);

    $students_details = fetch_students_details(
        $institution_id, 
        $branch_id, 
        $class_id, 
        $marksheet_id, 
        $date, 
        $fetched_academic_session, 
        $conn_rjllearning_specific
    );

    successreturn($students_details);
}
