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

// Include required files
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';

//valdation 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_resources .'lib/common_modules/attendance/function.php';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";


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

// Check if required fields are present
$required_fields = ['student_id','api_signature', 'function_type', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.");
    }
}

// Validate API signature
validateApiSignature($postdata['api_signature']);

// Authenticate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

// Extract data from JWT token
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

// Validate user access
$specific_db_name = validateStudentAcess($conn_rjllearning, $role, $workspace_id, ["teacher"], null, null, $userid);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

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

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

$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.");
}

if ($postdata['function_type'] == "fetch_specific_student_attendance") {  

    $faculty_id = $result_faculty['id'];
    $faculty_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    
    $class_section_subjects  = $faculty_data['class_section_subjects'];
    $class_incharge_roles = $faculty_data['class_incharge_roles'];
    $staff_access_modules = $faculty_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.");
    }
    
    // Check academic session status
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    // Set optional parameters
    // $class_id = isset($postdata['class_id']) && !empty($postdata['class_id']) ? trim($postdata['class_id']) : 'all';
    // $section_id = isset($postdata['section_id']) && !empty($postdata['section_id']) ? trim($postdata['section_id']) : 'all';
    $subject_id = isset($postdata['subject_id']) && !empty($postdata['subject_id']) ? trim($postdata['subject_id']) : 'all';
    $search_string = isset($postdata['search_string']) && !empty($postdata['search_string']) ? trim($postdata['search_string']) : null;
    
    $from_date = isset($postdata['from_date']) && !empty($postdata['from_date']) ? trim($postdata['from_date']) : null;
    $to_date = isset($postdata['to_date']) && !empty($postdata['to_date']) ? trim($postdata['to_date']) : null;

    if (!empty($from_date) && !empty($to_date) && ($from_date > $to_date)) {
        errorreturn('Invalid Date format');
    }

    $students_id = trim($postdata['student_id']);

    // Fetch student ID from database
    $sql_total_attendance_record = "SELECT user_id FROM students WHERE institution_id = ? AND id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql_total_attendance_record);
    $stmt->execute([$institution_id, $students_id]);
    $total_attendance_record_result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$total_attendance_record_result) {
        errorreturn("Student not found.");
    }

    $student_id = $total_attendance_record_result['user_id'];

    // Fetch attendance
    $success = checkAttendanceSystemAndFetchAttendance(
        $conn_rjllearning_specific,
        $institution_id,
        $check_academic_confirmation,
        $students_id,
        $branch_id,
        // $class_id,
        // $section_id,
        $subject_id,
        $from_date,
        $to_date,
        $search_string
    );
    
    successreturn($success);
}

?>
