<?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';

// 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 . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.php";
require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_function_branch_students.php';
require_once $base_path_to_learning_resources .  'external_requests/finware_curl/student/curl_left_student_finware.php';

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

$required_fields = [
    'api_signature',
    'function_type',
    'jwt_token',
    'student_id'
];

foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || empty($postdata[$field])) {
        errorreturn("All * fields are required.");
    }
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

if (!$jwt_validate) {
    errorreturn('Invalid 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;

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

$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);

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

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

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

// verifying student
$verify_query = "SELECT id, admission_id, admission_number, nationality, caste, date_admission, dob , class_id , section_id FROM students WHERE institution_id = ? AND branch_id = ? AND  id = ?";
$verify_stmt = $conn_rjllearning_specific->prepare($verify_query);
$verify_stmt->execute([$institution_id, $branch_id, $student_id]);
$student_exists = $verify_stmt->fetchAll();

if (count($student_exists) != 1) {
    errorreturn("Student record not found.");
}
$date_admission = $student_exists[0]['date_admission'];
$dob = $student_exists[0]['dob'];
$class_id = $student_exists[0]['class_id'];
$section_id = $student_exists[0]['section_id'];

// Proceed with alumni creation or update
$class_in_words = isset($postdata['class_in_words']) ? $postdata['class_in_words'] : null;
$school_last_examination = trim($postdata['school_last_examination']);
$failed_same_class = trim($postdata['failed_same_class']);
$subject_studied = isset($postdata['subject_studied']) ? $postdata['subject_studied'] : null;

if ($subject_studied !== null) {
    // Iterate over the array of objects and access each item
    foreach ($subject_studied as $item) {
        // Access each property of the object
        $value = $item['value'];
        // Process $value as needed
    }
}
// $last_class = trim($postdata['last_class']);
$last_class = isset($postdata['last_class']) ? trim($postdata['last_class']) : null;

$promotion_higher_class = isset($postdata['promotion_higher_class']) ? trim($postdata['promotion_higher_class']) : null;
$paid = isset($postdata['paid']) ? trim($postdata['paid']) : null;
$fee_concession = isset($postdata['fee_concession']) ? trim($postdata['fee_concession']) : null;
$working_days = trim($postdata['working_days']);

$present_days = isset($postdata['present_days']) ? trim($postdata['present_days']) : null;
$board = isset($postdata['board']) ? trim($postdata['board']) : null;
$ncc = isset($postdata['ncc']) ? trim($postdata['ncc']) : null;
$nationality=trim($postdata['nationality']);
$caste=trim($postdata['caste']);
$conduct = isset($postdata['conduct']) ? trim($postdata['conduct']) : null;
$class_in_figure = isset($postdata['class_in_figure']) ? trim($postdata['class_in_figure']) : null;
// $extra_curricular_activities = isset($_FILES['extra_curricular_activities']) ? $_FILES['extra_curricular_activities'] : null;
$extra_curricular_activities = trim($postdata['extra_curricular_activities']);
$date_application_certificate = $postdata['date_application_certificate'];
$date_issue_certificate = $postdata['date_issue_certificate'];
// $date_application_certificate = isset($postdata['date_application_certificate']) ? $postdata['date_application_certificate'] : null;
// $date_issue_certificate = isset($postdata['date_issue_certificate']) ? $postdata['date_issue_certificate'] : null;
$reasons_leaving_school = trim($postdata['reasons_leaving_school']);
$remarks = trim($postdata['remarks']);

// function processFileUpload($file, $workspace_id, $institution_id, $directoryPathMain) {
//     $currentYear = date('Y');
//     $currentMonth = date('n');
//     $directoryPathMain = "user_uploads/{$workspace_id}/{$institution_id}/attachment/{$currentYear}/{$currentMonth}/";

//     if (!file_exists($GLOBALS['base_path_to_learning'] . $directoryPathMain)) {
//         mkdir($GLOBALS['base_path_to_learning'] . $directoryPathMain, 0777, true);
//     }
//     $file_name = $file['name'];
//     $fileTmpName = $file["tmp_name"];
//     $fileSize = $file["size"];
//     $fileType = $file["type"];
//     $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
//     $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)

//     $allowedTypes = [
//         'image/jpeg', 'image/png', 'image/gif', 'image/heic', 'application/pdf', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel',
//         'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
//     ];
//     $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];

//     checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
//     $image_name = date('d-m-Y') . "." . $file_extension;
//     $attachment_path = $directoryPathMain . $image_name;

//     try {
//         $s3_learning_bucket->putObject([
//             'Bucket' => $learning_bucketName,
//             'Key' => $attachment_path,
//             'SourceFile' => $fileTmpName,
//         ]);
//     } catch (Exception $e) {
//         errorreturn($e->getMessage());
//     }

//     return $attachment_path;
// }

// if ($date_application_certificate != null) {
//     $date_application_certificate = processFileUpload($date_application_certificate, $workspace_id, $institution_id, "date_application_certificate");
// }

// if ($date_issue_certificate != null) {
//     $date_issue_certificate = processFileUpload($date_issue_certificate, $workspace_id, $institution_id, "date_issue_certificate");
// }

$conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
$conn_rjllearning_specific->beginTransaction();
if ($postdata['function_type'] == "create_manage_alumni") {
    $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($postdata['function_type'], $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, null, $conn_rjllearning);
    if ($check_faculty_status == false) {
        errorreturn("Access denied: You do not have the required permissions.");
    }
    $res = $conn_rjllearning_specific->prepare("SELECT id FROM left_students WHERE institution_id = ? AND branch_id=? AND class_id = ? AND section_id = ? AND student_id  = ?");
    $res->execute([$institution_id, $branch_id, $class_id, $section_id, $student_id ]);
    $result1 = $res->fetchAll();

    if (count($result1) >= 1) {
        errorreturn("Alumni already exists.");
    } else {

        $sql = "SELECT user_id, admission_number from students where institution_id = ? and id = ?";
        $fetch = $conn_rjllearning_specific->prepare($sql);
        $fetch->execute(array($institution_id, $student_id));
        $result = $fetch->fetchAll();
        if (count($result) != 1) {
            $conn_rjllearning_specific->rollBack();
        } else {
            $student_userid = $result[0]['user_id'];
            $admission_number = $result[0]['admission_number'];
        }

        $insert_query = "INSERT INTO left_students (
            institution_id, branch_id, class_id, class_in_words, section_id, student_id, nationality, caste, date_admission, dob, school_last_examination, 
            failed_same_class, subject_studied,last_class, promotion_higher_class, paid, fee_concession, 
            working_days,board,ncc,conduct,present_days,class_in_figure,extra_curricular_activities, date_application_certificate, 
            date_issue_certificate, reasons_leaving_school, remarks,added_by, admission_number
        ) VALUES (
            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?
        )";

        $stmt = $conn_rjllearning_specific->prepare($insert_query);
        $subject_studied_json = json_encode($subject_studied);
        $stmt->execute([
            $institution_id,
            $branch_id,
            $class_id,
            $class_in_words,
            $section_id,
            $student_id,
            $nationality,
            $caste,
            $date_admission,
            $dob,
            $school_last_examination,
            $failed_same_class,
            $subject_studied_json,
            $last_class,
            $promotion_higher_class,
            $paid,
            $fee_concession,
            $working_days,
            $board,
            $ncc,
            $conduct,
            $present_days,
            $class_in_figure,
            $extra_curricular_activities,
            $date_application_certificate,
            $date_issue_certificate,
            $reasons_leaving_school,
            $remarks,
            $username,
            $admission_number
        ]);

        $id = $conn_rjllearning_specific->lastInsertId();

        $sql = "UPDATE students SET can_activate = ?, status = ?, date_left = ? WHERE institution_id = ? AND id = ?";
        $conn_rjllearning_specific->prepare($sql)->execute([0, 0, $date_issue_certificate, $institution_id, $student_id]);
        
        $branch = getBranchDetails($conn_rjllearning_specific, $branch_id, $institution_id);
        
        $ledger_message = '';
        if (!empty($branch)) {
            $student_data = [
                "workspace_id" => $workspace_id,
                "branch" => $branch,
                "student" => $student_id
            ];
            
            // Call and capture any message
            $ledger_result = curlLeftStudentFinware($student_data);
            if ($ledger_result !== true) {
                $ledger_message = $ledger_result; // e.g., "Student ledger not found. Please create it manually in Finware."
            }
        }
        
        $conn_rjllearning_specific->commit();
        
        $sql = "UPDATE users SET can_activate = ?, status = ? WHERE workspace_id = ? AND institution_id = ? AND id = ?";
        $conn_rjllearning->prepare($sql)->execute([0, 0, $workspace_id, $institution_id, $student_userid]);
        
        // Final message
        $success_msg = "Successfully alumni added.";
        if (!empty($ledger_message)) {
            $success_msg .= " Note: " . $ledger_message;
        }
        
        // Return success response
        successreturn(['id' => $id, 'successmsg' => $success_msg]);

    }
}
?>
