<?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";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

// Validation files
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/check_username_availability.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/validate_faculty.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . 'lib/task_schedule/task_scheduler_functions.php';
// Dynamic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

// Decode JSON post data
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

// Check if required fields are present
if (
    !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    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;

// Validate user access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

// Extract and validate input data
$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$status = trim($postdata['status']);

// Validate status value
if ($status !== null && !in_array($status, [-1, 0, 1])) {
    errorreturn('Invalid status value.');
}

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

// Validate branch
if ($branch_id != "all") {
    $sql_branch = $conn_rjllearning_specific->prepare("SELECT id, name FROM branch WHERE id = ? AND institution_id = ?");
    $sql_branch->execute([$branch_id, $institution_id]);
    $branch = $sql_branch->fetch(PDO::FETCH_ASSOC);
    if (!$branch) {
        errorreturn("Branch does not exist in the specified institution.");
    }
}

// Proceed if function type is for updating leave status
$function_type = $postdata['function_type'];
if ($function_type === "create_status_updates") {
    $date_now = date('Y-m-d');  
    compareDatesAcademicSession($conn_rjllearning_specific, $institution_id, $date_now, null, true);
    
    $leave_id = (array)$postdata['leave_id'];
    if (empty($leave_id)) {
        erroreturn("Error: No leave IDs provided!");
    }

    $placeholders = implode(',', array_fill(0, count($leave_id), '?'));
    $sql = "UPDATE apply_leaves SET status = ? WHERE institution_id = ? AND id IN ($placeholders)";
    $array_params = array_merge([$status, $institution_id], $leave_id);
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    
     foreach ($leave_id as $leave) {
        manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'apply_leaves', $leave, $date_now, (time() + 120), 1, 'create');
    }


    if (count($leave_id) > 0) {
        $sql_leaves = $conn_rjllearning_specific->prepare("
            SELECT id, student_id, class_id, section_id, subject_id, start_date, end_date, status 
            FROM apply_leaves 
            WHERE id IN ($placeholders) AND institution_id = ?"); 
        $array_params = array_merge($leave_id, [$institution_id]);
        $sql_leaves->execute($array_params);
      
        $leaves = $sql_leaves->fetchAll(PDO::FETCH_ASSOC);
      
        foreach ($leaves as $leave) {
            $user_id = $leave['student_id'];
            $start_date = $leave['start_date'];
            $end_date = $leave['end_date'];
            $class_id = $leave['class_id'];
            $section_id = $leave['section_id'];
            $subject_id = $leave['subject_id'];
            $status = $leave['status'];

            $sql_student = $conn_rjllearning_specific->prepare("SELECT id FROM students WHERE user_id = ?");
            $sql_student->execute([$user_id]);
            $student_id = $sql_student->fetchColumn();
            if (!$student_id) continue;

            $sql_global = $conn_rjllearning_specific->prepare("SELECT attendance_system FROM institution_global_settings WHERE institution_id = ? AND branch_id = ?");
            $sql_global->execute([$institution_id, $branch_id]);
            $attendance_type = $sql_global->fetchColumn();
            
            for ($date = strtotime($start_date); $date <= strtotime($end_date); $date += 86400) {
                $current_date = date('Y-m-d', $date);
            
                if ($status == 1) { // **Approval Case**
                    if ($attendance_type == 'subject_wise') {
                        // **Update 'A' to 'L' only if not already 'L'**
                        $stmt = $conn_rjllearning_specific->prepare("
                            UPDATE student_attendance_subjectwise 
                            SET value = 'L', last_updated_by = ?, last_updated_time = ? 
                            WHERE student_id = ? AND class_id = ? AND section_id = ? AND subject_id = ? 
                            AND date = ? AND value = 'A'
                        ");
                        $stmt->execute([$username, time(), $student_id, $class_id, $section_id, $subject_id, $current_date]);

                        // **Check if already stored as 'L'**
                        $stmt_check = $conn_rjllearning_specific->prepare("
                            SELECT COUNT(*) FROM student_attendance_subjectwise 
                            WHERE student_id = ? AND class_id = ? AND section_id = ? AND subject_id = ? 
                            AND date = ? AND value = 'L'
                        ");
                        $stmt_check->execute([$student_id, $class_id, $section_id, $subject_id, $current_date]);
                        $already_marked = $stmt_check->fetchColumn();

                        // **Insert only if not already stored**
                        if ($stmt->rowCount() == 0 && $already_marked == 0) {
                            $stmt = $conn_rjllearning_specific->prepare("
                                INSERT INTO student_attendance_subjectwise 
                                (institution_id, branch_id, academic_id, student_id, class_id, section_id, subject_id, date, value, added_by, last_updated_by, time_created, last_updated_time) 
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'L', ?, ?, ?, ?)
                            ");
                            $stmt->execute([$institution_id, $branch_id, $academic_id, $student_id, $class_id, $section_id, $subject_id, $current_date, $username, $username, time(), time()]);
                        }
                    } else {
                        // **Update 'A' to 'L' only if not already 'L'**
                        $stmt = $conn_rjllearning_specific->prepare("
                            UPDATE student_attendance_daywise 
                            SET value = 'L', last_updated_by = ?, last_updated_time = ? 
                            WHERE student_id = ? AND class_id = ? AND section_id = ? 
                            AND date = ? AND value = 'A'
                        ");
                        $stmt->execute([$username, time(), $student_id, $class_id, $section_id, $current_date]);

                        // **Check if already stored as 'L'**
                        $stmt_check = $conn_rjllearning_specific->prepare("
                            SELECT COUNT(*) FROM student_attendance_daywise 
                            WHERE student_id = ? AND class_id = ? AND section_id = ? 
                            AND date = ? AND value = 'L'
                        ");
                        $stmt_check->execute([$student_id, $class_id, $section_id, $current_date]);
                        $already_marked = $stmt_check->fetchColumn();

                        // **Insert only if not already stored**
                        if ($stmt->rowCount() == 0 && $already_marked == 0) {
                            $stmt = $conn_rjllearning_specific->prepare("
                                INSERT INTO student_attendance_daywise 
                                (institution_id, branch_id, academic_id, student_id, class_id, section_id, date, value, added_by, last_updated_by, time_created, last_updated_time) 
                                VALUES (?, ?, ?, ?, ?, ?, ?, 'L', ?, ?, ?, ?)
                            ");
                            $stmt->execute([$institution_id, $branch_id, $academic_id, $student_id, $class_id, $section_id, $current_date, $username, $username, time(), time()]);
                        }
                    }
                } else { // **Disapproval Case (Status = 0)**
                    if ($attendance_type == 'subject_wise') {
                        $stmt = $conn_rjllearning_specific->prepare("
                            DELETE FROM student_attendance_subjectwise 
                            WHERE student_id = ? AND class_id = ? AND section_id = ? AND subject_id = ? AND date = ? AND value = 'L'
                        ");
                        $stmt->execute([$student_id, $class_id, $section_id, $subject_id, $current_date]);
                    } else {
                        $stmt = $conn_rjllearning_specific->prepare("
                            DELETE FROM student_attendance_daywise 
                            WHERE student_id = ? AND class_id = ? AND section_id = ? AND date = ? AND value = 'L'
                        ");
                        $stmt->execute([$student_id, $class_id, $section_id, $current_date]);
                    }
                }
            }
        }
    }
    successreturn("Successfully updated leave status and attendance.");
}



?>
