<?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";
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);

checkIfNoPhpContentsReceive();

if (
    // !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    // !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or
    !isset($postdata['class_id']) or !checkIfIssetAndNotEmpty($postdata['class_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 . '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);

$class_id = trim($postdata['class_id']);


$function_type = trim($postdata['function_type']);


function fetch_students_details($institution_id, $branch_id, $class_id,$marksheet_id, $conn_rjllearning_specific,$userid,$conn_rjllearning, $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'];
    $teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    $class_section_subjects  = $teacher_data['class_section_subjects'];
    $class_incharge_roles = $teacher_data['class_incharge_roles'];
    $staff_access_modules = $teacher_data['staff_access_modules'];
 
    $check_faculty_status=checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, null, null, $conn_rjllearning);
    if($check_faculty_status == false){
        errorreturn("Access denied: You do not have the required permissions.");
    }
    
    // $static_path = 'https://rejoicebilldesk.in/rjllearning_development/admin_api/modules/marksheet_template/';
    //   $date == date("Y-m-d");
    // $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)";
    //     $fetch_students = $conn_rjllearning_specific->prepare($sql);
    //     $fetch_students->execute(array($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))";
    //     $fetch_students = $conn_rjllearning_specific->prepare($sql);
    //     $fetch_students->execute(array($institution_id, $branch_id, $date, $date, $class_id, $institution_id, $branch_id, $date));
    //     $students = $fetch_students->fetchAll(PDO::FETCH_ASSOC);
    // }
    
    $sql = "SELECT id as student_id, name, fathername, section_id, status 
            FROM students 
            WHERE institution_id = ? AND branch_id = ? AND class_id = ? AND can_activate = 1 AND status = 1";
            
    $array_params = array($institution_id,$branch_id,$class_id);    
    
    
    $sql_append_data = facultyFilterQueryAppend($sql, $array_params, $function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules,$class_id, null, null,$conn_rjllearning, 1, 1, 1, 1);

    $sql = $sql_append_data['sql'];  // Get the modified SQL query
    $array_params = $sql_append_data['array_params'];
    // print_r($sql);

    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $students = $stmt->fetchAll();
    // print_r($students);

    if (empty($students)) {
        errorreturn("No students found for the given criteria.");
    }

    $student_details = [];


    foreach ($students as $student) {
        // $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $branch_id);
        $section = getSection($conn_rjllearning_specific, $institution_id, $student['section_id']);

        // $marksheet_sql = "SELECT COUNT(*) as marks_count 
        //                   FROM student_marksheet_data 
        //                   WHERE student_id = ? AND institution_id = ? AND branch_id = ? AND class_id = ?";

        // $marksheet_stmt = $conn_rjllearning_specific->prepare($marksheet_sql);
        // $marksheet_stmt->execute([$student['student_id'], $institution_id, $branch_id, $class_id]);
        // $marksheet_data = $marksheet_stmt->fetch();

        $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'], $class_id, $student['section_id'],$marksheet_id]);

        $marksheet_data = $marksheet_stmt->fetch();


        // Determine the marks upload status
        $marks_upload_status = ($marksheet_data['marks_count'] > 0) ? 'Complete' : 'Incomplete';

        $student_status = ($student['status'] == 0) ? 'not-active' : 'active';

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

    return $student_details;
}



// function fetch_students_details($institution_id, $branch_id, $class_id,$marksheet_id, $conn_rjllearning_specific)
// {
//     // $static_path = 'https://rejoicebilldesk.in/rjllearning_development/admin_api/modules/marksheet_template/';

// //   $params = [$institution_id]; // Initialize the parameters array with institution_id and marksheet_id

// //     $sql = "SELECT id as student_id, name, fathername, section_id, status ,class_id,branch_id
// //             FROM students 
// //             WHERE institution_id = ? ";
    
// //     // Add branch_id condition
// //     if ($branch_id !== 'all') {
// //         $sql .= " AND branch_id = ? ";
// //         $params[] = $branch_id; // Append branch_id to parameters
// //     }
    
// //     // Add class_id condition
// //     if ($class_id !== 'all') {
// //         $sql .= " AND class_id = ? ";
// //         $params[] = $class_id; // Append class_id to parameters
// //     }
    
// //     // // Add section_id condition
// //     // if ($section_id !== 'all') {
// //     //     $sql .= " AND section_id = ? ";
// //     //     $params[] = $section_id; // Append section_id to parameters
// //     // }
// //     $sql .= "order by section_id asc";
// //     $stmt = $conn_rjllearning_specific->prepare($sql);
// //     $stmt->execute($params); // Use the constructed $params array
// //     $students = $stmt->fetchAll();
  
// //     if (empty($students)) {
// //         errorreturn("No students found for the given criteria.");
// //     }

// //   // Process the $students array as needed


// //     $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 institution_id = ? AND branch_id = ? AND class_id = ?";

// //         // $marksheet_stmt = $conn_rjllearning_specific->prepare($marksheet_sql);
// //         // $marksheet_stmt->execute([$student['student_id'], $institution_id, $branch_id, $class_id]);
// //         // $marksheet_data = $marksheet_stmt->fetch();

// //         $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();


// //         // Determine the marks upload status
// //         $marks_upload_status = ($marksheet_data['marks_count'] > 0) ? 'Complete' : 'Incomplete';

// //         $student_status = ($student['status'] == 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
// //         ];
// //     }
//   $date == date("Y-m-d");
//  $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)";
//         $fetch_students = $conn_rjllearning_specific->prepare($sql);
//         $fetch_students->execute(array($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))";
//         $fetch_students = $conn_rjllearning_specific->prepare($sql);
//         $fetch_students->execute(array($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;
// }
if ($postdata['function_type'] == "fetch_students_details") {
    
    $teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    $class_section_subjects  = $teacher_data['class_section_subjects'];
    $class_incharge_roles = $teacher_data['class_incharge_roles'];
    $staff_access_modules = $teacher_data['staff_access_modules'];

    $check_faculty_status = checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, null, null, null, $conn_rjllearning);
    if ($check_faculty_status == false) {
        errorreturn("Access denied: You do not have the required permissions.");
    }
    
    $marksheet_id = trim($postdata['marksheet_id']);
    // $institution_id = trim($postdata['institution_id']);
    // $branch_id = trim($postdata['branch_id']);
    // $class_id = trim($postdata['class_id']);
    // $section_id = trim($postdata['section_id']);
    $students_details = fetch_students_details($institution_id, $branch_id, $class_id,$marksheet_id, $conn_rjllearning_specific,$userid,$conn_rjllearning, $function_type);
    successreturn($students_details);
}
