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

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/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/registration_functions.php';
require_once $base_path_to_learning . 'admin_api/modules/student_admission/upload_admission_certificate_functions.php';
//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_add_alter_student_ledgers_finware.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 . 'user_management/faculty/functions.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/cache_student_academic_function.php';

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

$postdata = $_POST;

$required_fields = [
    'student_id', 'class_id', 'section_id', 'name', 'fathername', 'mothername',
    'father_occupation', 'mother_occupation', 'email', 'mobile',
    'address_line_1', 'city', 'pincode'
];


foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || trim($postdata[$field]) === '') {
        errorreturn("$field is 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;
$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);
}

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']);
$class_id = trim($postdata['class_id']);
$section_id = trim($postdata['section_id']);
$name = ucwords(trim($postdata['name']));
$fathername = ucwords(trim($postdata['fathername']));
$mothername = ucwords(trim($postdata['mothername']));
$father_occupation = trim($postdata['father_occupation']);
$mother_occupation = trim($postdata['mother_occupation']);
$email = trim($postdata['email']);
$mobile = trim($postdata['mobile']);
$address_line_1 = ucwords(trim($postdata['address_line_1']));
$city = ucwords(trim($postdata['city']));
$pincode = trim($postdata['pincode']);
$status = '1';
$student_profile_image = (isset($_FILES['student_profile_image']) and !empty($_FILES['student_profile_image'])) ? (($_FILES['student_profile_image'])) : null;
$remove_profile_image = (isset($postdata['remove_profile_image']) and !empty($postdata['remove_profile_image'])) ? trim($postdata['remove_profile_image']) : 0;
$sibling_bool =  trim($postdata['sibling_bool']);
$sibling = (isset($postdata['sibling']) && is_array($postdata['sibling']) && !empty($postdata['sibling'])) ? $postdata['sibling'] : null;
$gender = trim($postdata['gender']);
$dob = trim($postdata['dob']);
$bus_id =  (isset($postdata['bus_id']) and !empty($postdata['bus_id'])) ? $postdata['bus_id'] : null;
$route_id =  (isset($postdata['route_id']) and !empty($postdata['route_id'])) ? $postdata['route_id'] : null;
$stop_id =  (isset($postdata['stop_id']) and !empty($postdata['stop_id'])) ? $postdata['stop_id'] : null; 
if ($sibling_bool == 1) {
    if (!is_array($sibling) || empty($sibling)) {
        errorreturn("Select at least one sibling.");
    }
        $imploded_siblings = "('" . implode("','", $sibling) . "')";
        $count_siblings = count($sibling);
    
        $sql_student = $conn_rjllearning_specific->prepare("SELECT COUNT(*) as total FROM students WHERE admission_number IN $imploded_siblings AND institution_id = ? AND branch_id = ?");
        $sql_student->execute([$institution_id, $branch_id]);
        $result_student = $sql_student->fetchAll()[0]['total'];
        if ($result_student != $count_siblings) {
            $sibling_bool = 0;
            $sibling = null;
        } else {
            $sibling = "'" . implode("','", $sibling) . "'";
        }
}

{
    $sql = $conn_rjllearning_specific->prepare("SELECT branch_code FROM  branch WHERE id = ? AND institution_id = ?");
    $sql->execute(array($branch_id, $institution_id));
    $result = $sql->fetchAll();
    if (count($result) >= 1) {
        $branch_code = $result[0]['branch_code'];
    } else {
        errorreturn("Branch  not exists.");
    }

    if (!checkOnlyCharacters($name)) { // 6 digit only
        //eg House Name, Street Name
        errorreturn('Name must only contain letters!"');
    }

    if (!CheckEMailIsValidOrNot($email)) {
        errorreturn('Enter valid Email Id');
    }

    if (strlen($mobile) != 13 or $mobile <= 0) {
        errorreturn('Enter valid 12 digit mobile number ' . $mobile);
    }

    if ($gender != 'M' && $gender != 'F') {
        errorreturn('Invalid gender details');
    }

    $date_now = date("Y-m-d");
    if (!CheckDob($dob) or $dob >= $date_now) {
        errorreturn('Invalid DOB formats');
    }
    //student address
    if (!CheckAddressValidation($address_line_1)) {
        //eg House Name, Street Name
        errorreturn('Invalid Address');
    }

    //Branch Pin Code Validation 
    if (!PinCodeValidation($pincode)) { // 6 digit only
        //eg House Name, Street Name
        errorreturn('Invalid Pin Code');
    }
}


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

if (!isset($postdata['student_id']) or !checkIfIssetAndNotEmpty($postdata['student_id'])) {
    errorreturn('Error in updating the student.');
} else {
    $student_id = $postdata['student_id'];
}

$current_time = date('Y-m-d H:i:s');

 $conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
    $conn_rjllearning_specific->beginTransaction();
    try {
       
        $res = $conn_rjllearning_specific->prepare("SELECT id,admission_number,institution_id,birth_certificate,nationality_proof,student_profile_image,user_id FROM  students WHERE id = ? and institution_id=? and branch_id =?  ");
        $res->execute(array($student_id, $institution_id, $branch_id));
        $result1 = $res->fetchAll();
        if (count($result1) == 1) {
            $existing_birth_certificate = $result1[0]['birth_certificate'];
            if ($existing_birth_certificate !=  null) {
                $birth_certificate_data = json_decode($existing_birth_certificate, true);
                $birth_certificate_path = $birth_certificate_data['filepath'];
            }
            $existing_nationality_proof = $result1[0]['nationality_proof'];
            if ($existing_nationality_proof !=  null) {
                $data_attachment_proof = json_decode($existing_nationality_proof, true);
                $nationality_file_path = $data_attachment_proof['filepath'];
            }
            $existing_student_profile_image = $result1[0]['student_profile_image'];
            if ($existing_student_profile_image !=  null) {
                $data_attachment = json_decode($existing_student_profile_image, true);
                $profile_image_path = $data_attachment['filepath'];
            }
            $admission_number = $result1[0]['admission_number'];
            $user_id = $result1[0]['user_id'];
        }

        


        if ($student_profile_image != null) {
            if ($existing_student_profile_image == null) {
                $currentYear = date('Y');
                $currentMonth = date('m');
                $currentDay =  date('d');
                //$directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/admission_documents/" . "/student_uploads/" . $currentYear . "/" . $currentMonth . "/";
                $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/" . $branch_id .  "/students/" . $admission_number .  "/" . $currentYear . "/" . $currentMonth . "/";
            } else {
                $directoryPathMain = substr($profile_image_path, 0, strrpos($profile_image_path, '/') + 1);
            }

            $file_name = $_FILES['student_profile_image']['name'];
            $fileTmpName = $_FILES['student_profile_image']["tmp_name"];
            $fileSize = $_FILES['student_profile_image']["size"];
            $fileType = $_FILES['student_profile_image']["type"];
            $fileError = $_FILES['student_profile_image']["error"];
            $student_file_extension = strtolower(pathinfo($_FILES['student_profile_image']['name'], PATHINFO_EXTENSION));
            $size = filesize($fileTmpName);
            // Check if it's a valid image
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/heic']; // Allowed image types
            $allowed_extensions = ['jpg', 'png', 'heic', 'jpeg', 'pdf'];
            $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)

            checkFileValidation($fileSize, $fileType, $student_file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
        }
        
       
        
        //get student_admission
        $sql_student_admission = $conn_rjllearning_specific->prepare("
        SELECT last_tc FROM student_admission 
        WHERE admission_number = ? AND institution_id = ?");
        $sql_student_admission->execute([$admission_number, $institution_id]);
        $result_student_admission = $sql_student_admission->fetchAll();
        
        $existing_last_tc = null;
        $last_tc_path = null;
        
        if (!empty($result_student_admission[0]['last_tc'])) {
        $existing_last_tc = $result_student_admission[0]['last_tc'];
        $last_tc_data = json_decode($existing_last_tc, true);
        $last_tc_path = $last_tc_data['filepath'] ?? null;
        }


       

        updateUsers($conn_rjllearning, $workspace_id, $institution_id, $name, $dob, $gender, $email, $mobile, $user_id);
        $sql = "UPDATE students 
        SET class_id = ?, section_id = ?, name = ?, fathername = ?, mothername = ?, 
            father_occupation = ?, mother_occupation = ?, email = ?, mobile = ?, 
            address_line_1 = ?, city = ?, pincode = ?, status = ?, sibling = ?, sibling_bool = ?
        WHERE id = ? AND institution_id = ?";

        $params = [
            $class_id, $section_id, $name, $fathername, $mothername,
            $father_occupation, $mother_occupation, $email, $mobile,
            $address_line_1, $city, $pincode, $status, $sibling,$sibling_bool,
            $student_id, $institution_id
        ];
   
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $result = $stmt->execute($params);
        
        $check_query = "SELECT * FROM student_stops WHERE student_id = ? AND institution_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($check_query);
        $stmt->execute([$student_id, $institution_id]);
        $result = $stmt->fetch();

        if (is_null($bus_id)) {
            if ($result) {
                // If bus_id is null and the row exists, delete the row
                $delete_query = "DELETE FROM student_stops WHERE student_id = ? AND institution_id = ?";
                $stmt = $conn_rjllearning_specific->prepare($delete_query);
                $stmt->execute([$student_id, $institution_id]);
            }
        } else {
            if ($result) {
                // Row exists, perform update
                $stop_id_to_update = is_null($route_id) ? null : $stop_id;
                $update_query = "UPDATE student_stops SET bus_id = ?, route_id = ?, stop_id = ?, last_modified_by = ?, last_modified_at = ? WHERE institution_id = ? AND branch_id = ? AND student_id = ?";
                $stmt = $conn_rjllearning_specific->prepare($update_query);
                $stmt->execute([$bus_id, $route_id, $stop_id, $username, $current_time, $institution_id, $branch_id, $student_id]);
            } else {
                // No row exists, perform insert
                $stop_id_to_insert = is_null($route_id) ? null : $stop_id;
                $insert_query = "INSERT INTO student_stops (institution_id, branch_id, student_id, bus_id, route_id, stop_id, created_by, created_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                $stmt_insert = $conn_rjllearning_specific->prepare($insert_query);
                $stmt_insert->execute([$institution_id, $branch_id, $student_id, $bus_id, $route_id, $stop_id, $username, $current_time]);
            }
        }

        if ($remove_profile_image == 1 and $existing_student_profile_image != null) {
            $sql_image = $conn_rjllearning_specific->prepare("SELECT student_profile_image FROM  students  where id = ? and institution_id = ? ");
            $sql_image->execute(array($student_id, $institution_id));
            $result_image = $sql_image->fetchAll();
            if (count($result_image) == 1) {
                $profileimage = $result_image[0]['student_profile_image'];
                if ($profileimage !=  null) {
                    $data_attachment = json_decode($profileimage, true);
                    $filePath = $data_attachment['filepath'];
                }
                awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $filePath, null, null);
                $sql = "UPDATE students SET student_profile_image = ? WHERE  id = ? and institution_id = ? ";
                $conn_rjllearning_specific->prepare($sql)->execute(array(null, $student_id, $institution_id));
            }
        }

        if ($remove_profile_image == 1 and $student_profile_image !=  null) {
            $image_name = "student_profile_image_" . $student_id . "." . $student_file_extension; // Define the image name dynamically
            $profile_image_aws = $directoryPathMain . $image_name; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $student_profile_image, $profile_image_aws, $multiple_files_bool = false, $multiple_file_index = 0);
            $attachment_image = json_encode(array("filepath" => $profile_image_aws, "original_name" => $_FILES['student_profile_image']['name']));
            $sql_logo = "UPDATE students SET student_profile_image = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image, $student_id));
        }




        $branch = getBranchDetails($conn_rjllearning_specific, $branch_id, $institution_id);
        if (!empty($branch)) {
            if (!empty($fathername)) {
                // Use father's name if it's not null
                $ledger_name = "$name S/o $fathername - $admission_number";
            } elseif (!empty($mothername)) {
                // Use mother's name if father's name is null
                $ledger_name = "$name D/o $mothername - $admission_number";
            } else {
                // If both father's and mother's names are null, handle as needed (e.g., just the name and admission number)
                $ledger_name = "$name - $admission_number";
            }

            $ledger_address = sanitizeInput($address_line_1);
            $ledger_name = sanitizeInput($ledger_name);
            $class_info = getClass($conn_rjllearning_specific, $institution_id, $class_id);
            // print_r($class_info);die();
            $section_data = getSection($conn_rjllearning_specific, $institution_id, $section_id);
            // Create array with student and branch details for formattedData
            $formattedData[] = array(
                'product_connection_id' => $student_id,
                'ledger_address' => $ledger_address,
                'ledger_name' => $ledger_name,
                'ledger_main_ledgerhead' => 'Sundry Debtors',
                'mobile' => $mobile,
                'email' => $email,
                'class' => $class_info['class_name'],
                'section' => $section_data['section_name'],
                "function_type" => "alter"
            );
            $students_data  = array("workspace_id" => $workspace_id, "branch" => $branch, "student_learning" => $formattedData, "created_by" => $username);
            curlAddAlterStudentLedgersFinware($students_data);
        }
        cacheAcademicStudentData($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $student_id, $date_now);
        $conn_rjllearning_specific->commit();
        
        successreturn("Updated student Successfully");
    } catch (Exception $e) {
        $conn_rjllearning_specific->rollBack();
        errorreturn("Error : " . $e->getMessage());
    }
}
