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

//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'faculty_api/modules/student_registration/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";
require_once $base_path_to_learning . 'functions/common_functions.php';

$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();
if (
    !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  !isset($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);

if ($postdata['function_type'] == "create_registration") {
    if (
        !isset($postdata['name']) or !checkIfIssetAndNotEmpty($postdata['name']) or
        !isset($postdata['email']) or !checkIfIssetAndNotEmpty($postdata['email']) or
        !isset($postdata['mobile']) or !checkIfIssetAndNotEmpty($postdata['mobile']) or
        !isset($postdata['city']) or !checkIfIssetAndNotEmpty($postdata['city'] or
        !isset($postdata['dob']) or !checkIfIssetAndNotEmpty($postdata['dob']) or
        !isset($postdata['gender']) or !checkIfIssetAndNotEmpty($postdata['gender']) or
        !isset($postdata['for_class']) or !checkIfIssetAndNotEmpty($postdata['for_class']) or
        !isset($postdata['last_school']) or !checkIfIssetAndNotEmpty($postdata['last_school']) or
        !isset($postdata['current_class']) or !checkIfIssetAndNotEmpty($postdata['current_class'])
            // !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']
        )
    ) {
        errorreturn("All * fields are required.");
    }
    // $institution_id = trim($postdata['institution_id']);
    // $branch_id = trim($postdata['branch_id']);
    $reg_no = trim($postdata['reg_no']);
    $name = ucwords(trim($postdata['name']));
    $fathername = ucwords(trim($postdata['fathername']));
    $mothername = ucwords(trim($postdata['mothername']));
    $mobile = trim($postdata['mobile']);
    $email = trim($postdata['email']);
    $address_line_1 = ucwords(trim($postdata['address_line_1']));
    $city = ucwords(trim($postdata['city']));
    $pincode = trim($postdata['pincode']);
    $dob = trim($postdata['dob']);
    $gender = trim($postdata['gender']);
    $for_class = trim($postdata['for_class']);
    $last_school = trim($postdata['last_school']);
    $current_class = trim($postdata['current_class']);
    $reg_fees = trim($postdata['reg_fees']);
    $paid_through = trim($postdata['paid_through']);
    // $refrence_number = trim($postdata['refrence_number']);
    $refrence_number = (isset($postdata['refrence_number']) and !empty($postdata['refrence_number'])) ? trim($postdata['refrence_number']) : null;
    $sibling_bool = trim($postdata['sibling_bool']);
    // $sibling = (isset($postdata['sibling']) and !empty($postdata['sibling'])) ? ($postdata['sibling']) : null;

    $sibling = (isset($postdata['sibling']) && is_array($postdata['sibling']) && !empty($postdata['sibling']))
        ? $postdata['sibling']
        : null;

    //only allow alphabets
    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 (!is_numeric($reg_fees)) {
        // Handle error - reg_fees is not a valid numeric value
        errorreturn('Registration fees is not a valid numeric value');
    }
    $bank_array = ['bank', 'cash', 'net_banking', 'cheque', 'credit_card', 'UPI'];
    if (!in_array($paid_through, $bank_array)) {
        errorreturn('Invalid Payment mode');
    }

    if ($sibling_bool == 1 && is_array($sibling)) {
        if (!is_array($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) {
            // If student count does not match, reset sibling details
            $sibling_bool = 0;
            $sibling = null;
        } else {
            $sibling = "'" . implode("','", $sibling) . "'";
        }
    }
    if($refrence_number !=  null){
    if (!preg_match('/^\d{6,10}$/', $refrence_number)) {
        // Handle error - reference_number does not match the expected format (6 to 10 digits in this example)
        errorreturn('Reference number is not valid.');
    }
    }
    $sql_table = $conn_rjllearning_specific->prepare("SELECT * FROM student_registration WHERE institution_id = ? and branch_id = ? and reg_no = ? ");
    $sql_table->execute(array($institution_id, $branch_id, $reg_no));
    $result1 = $sql_table->fetchAll();

    if (count($result1) >= 1) {
        errorreturn("Student already exists: registration number  $reg_no ");
    }

    $success = insertStudentRegistration($conn_rjllearning_specific, $institution_id, $branch_id, $reg_no, $name, $fathername, $mothername, $mobile, $email, $address_line_1, $city, $pincode, $dob, $gender, $reg_fees, $paid_through, $refrence_number, $for_class, $last_school, $current_class, $username,$sibling_bool,$sibling);
     if($reg_fees !=null ){
     registerStudent($conn_rjllearning_specific,$institution_id,$branch_id,$name,'Student_Registration',$reg_fees,$date_now,'receipt',1,$paid_through,$username,$refrence_number);
     }
    
    if ($success != false) {
        $reg_id = $success;
        successreturn(array('id' => $reg_id, 'successmsg' => "Successfully student registration completed."));
    } else {
        // errorreturn
        errorreturn("Invalid studnet registration.");
    }
} else if ($postdata['function_type'] == "alter_registration") {
    if (
        !isset($postdata['name']) or !checkIfIssetAndNotEmpty($postdata['name']) or !isset($postdata['email']) or !checkIfIssetAndNotEmpty($postdata['email']) or !isset($postdata['mobile']) or !checkIfIssetAndNotEmpty($postdata['mobile']) or
        !isset($postdata['city']) or !checkIfIssetAndNotEmpty($postdata['city'] or !isset($postdata['dob']) or !checkIfIssetAndNotEmpty($postdata['dob']) or !isset($postdata['gender']) or !checkIfIssetAndNotEmpty($postdata['gender']) or !isset($postdata['for_class']) or !checkIfIssetAndNotEmpty($postdata['for_class']) or !isset($postdata['last_school']) or !checkIfIssetAndNotEmpty($postdata['last_school']) or
            !isset($postdata['current_class']) or !checkIfIssetAndNotEmpty($postdata['current_class']) or !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']))
    ) {
        errorreturn("All * fields are required.");
    }
    if (!isset($postdata['reg_id']) or !checkIfIssetAndNotEmpty($postdata['reg_id'])) {
        errorreturn('Error in updating the student registration.');
    } else {
        $reg_id = $postdata['reg_id'];
    }
    // $institution_id = trim($postdata['institution_id']);
    $reg_no = trim($postdata['reg_no']);
    // $branch_id = trim($postdata['branch_id']);
    $name = ucwords(trim($postdata['name']));
    $fathername = ucwords(trim($postdata['fathername']));
    $mothername = ucwords(trim($postdata['mothername']));
    $mobile = trim($postdata['mobile']);
    $email = trim($postdata['email']);
    $address_line_1 = ucwords(trim($postdata['address_line_1']));
    $city = ucwords(trim($postdata['city']));
    $pincode = trim($postdata['pincode']);
    $dob = trim($postdata['dob']);
    $gender = trim($postdata['gender']);
    $for_class = trim($postdata['for_class']);
    $last_school = trim($postdata['last_school']);
    $current_class = trim($postdata['current_class']);
    $reg_fees = trim($postdata['reg_fees']);
    $paid_through = trim($postdata['paid_through']);
    $refrence_number = trim($postdata['refrence_number']);
    $sibling_bool = trim($postdata['sibling_bool']);
    // $sibling = (isset($postdata['sibling']) and !empty($postdata['sibling'])) ? ($postdata['sibling']) : null;

    $sibling = (isset($postdata['sibling']) && is_array($postdata['sibling']) && !empty($postdata['sibling']))
        ? $postdata['sibling']
        : null;

    // $confirmed_role_user = validatePrimaryAccess($conn_rjllearning_specific, $institution_id, null, $role, $userid);
    // if ($confirmed_role_user != "superadmin" && $confirmed_role_user != "admin") {
    //     errorreturn("Access denied.");
    // }

    //only allow alphabets
    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 10 digit mobile number');
    }

    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 (!is_numeric($reg_fees)) {
        // Handle error - reg_fees is not a valid numeric value
        errorreturn('Registration fees is not a valid numeric value');
    }

    // Validate $paid_through as either "bank" or "cash"
    if ($paid_through !== "bank" && $paid_through !== "cash" && $paid_through !== "cheque" && $paid_through !== "net_banking" && $paid_through !== "credit_card" && $paid_through !== "UPI") {
        // Handle error - paid_through is not "bank" or "cash"
        errorreturn('Invalid registration fees is paid through');
    }

    if (!empty($reference_number)) {
    if (!preg_match('/^\d{6,12}$/', $reference_number)) {
        if (preg_match('/^\d{12,}$/', $reference_number)) {
            errorreturn('Reference number cannot be more than 10 digits.');
        } else {
            errorreturn('Reference number is not valid.');
        }
    }
  }



    if ($sibling_bool == 1 && is_array($sibling)) {
        if (!is_array($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) {
            // If student count does not match, reset sibling details
            $sibling_bool = 0;
            $sibling = null;
        } else {
            $sibling = "'" . implode("','", $sibling) . "'";
        }
    }
    //  $res = $conn_rjllearning_specific->prepare("SELECT id,institution_id FROM student_registration WHERE id != ? and institution_id=? and (name = ? or fathername = ? or mothername  = ? or mobile= ? or email= ?)");
    //  $res->execute(array($id,$institution_id,$name, $fathername, $mothername, $mobile, $email));
    //  $result1 = $res->fetchAll();
    //  if (count($result1) >= 1) {
    //      errorreturn("The student already exists");
    //  }
    $success = updateStudentRegistration($conn_rjllearning_specific, $reg_id, $institution_id, $branch_id, $reg_no, $name, $fathername, $mothername, $mobile, $email, $address_line_1, $city, $pincode, $dob, $gender, $reg_fees, $paid_through, $refrence_number, $for_class, $last_school, $current_class, $username,$sibling_bool,$sibling);
    if ($success == true) {
        successreturn("Updated student details Successfully");
    } else {
        // errorreturn
        errorreturn("Invalid studnet registration.");
    }
} else if ($postdata['function_type'] == "cancel_registration") {

    $id = $postdata['registration_id'];
    $res = $conn_rjllearning_specific->prepare("SELECT id,status FROM student_registration WHERE id = ? and institution_id =? ");
    $res->execute(array($id, $institution_id));
    $result1 = $res->fetchAll();
    $lockstatus = $result1[0]['status'];


    if ($lockstatus == '1') {
        //0 is for inactive registration
        $lock_status = '0';
        $sql = "UPDATE student_registration SET status=?  WHERE id=?  and institution_id= ?";
        $conn_rjllearning_specific->prepare($sql)->execute(array($lock_status, $id, $institution_id));
    } else if ($lockstatus == '0') {
        //1 is for active registration
        $lock_status = '1';
        $sql = "UPDATE student_registration SET status=?  WHERE id = ?  and institution_id =?";
        $conn_rjllearning_specific->prepare($sql)->execute(array($lock_status, $id, $institution_id));
    }
    successreturn("Student Registration updated Successfully");
}
