<?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/authenticate.php';

require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'admin_api/branch_management/functions/functions.php';


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


if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['branch_code']) or !checkIfIssetAndNotEmpty($postdata['branch_code']) or
    !isset($postdata['name']) or !checkIfIssetAndNotEmpty($postdata['name']) or
    !isset($postdata['city']) or !checkIfIssetAndNotEmpty($postdata['city']) or
    !isset($postdata['pincode']) or !checkIfIssetAndNotEmpty($postdata['pincode']) or
    !isset($postdata['address']) or !checkIfIssetAndNotEmpty($postdata['address']) or
    !isset($postdata['contact_number']) or !checkIfIssetAndNotEmpty($postdata['contact_number']) or
    !isset($postdata['email']) or !checkIfIssetAndNotEmpty($postdata['email']) or
    !isset($postdata['country']) or !checkIfIssetAndNotEmpty($postdata['country']) or
    !isset($postdata['state']) or !checkIfIssetAndNotEmpty($postdata['state']) or
    !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  !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}


validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["superadmin","admin"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
$institution_id = trim($postdata['institution_id']);
$branch_code = strtoupper(trim($postdata['branch_code']));



$name = ucwords(strtolower(trim($postdata['name'])));
$city = ucwords(strtolower(trim($postdata['city'])));
$pincode = trim($postdata['pincode']);
$address = ucwords(strtolower(trim($postdata['address'])));
$contact_number = trim($postdata['contact_number']);
$email = trim($postdata['email']);
$website = trim($postdata['website']);
// $email = (isset($postdata['email']) and !empty($postdata['email'])) ? trim($postdata['email']) : null;
// $website = (isset($postdata['website']) and !empty($postdata['website'])) ? trim($postdata['website']) : null;
$country = (isset($postdata['country']) and !empty($postdata['country'])) ? trim($postdata['country']) : null;
$state = trim($postdata['state']);
$affiliation_code = (isset($postdata['affiliation_code']) and !empty($postdata['affiliation_code'])) ? trim($postdata['affiliation_code']) : null;
$date_added = date('Y-m-d');

$otp_settings_array = [
    'students_password_reset_otp' => 1, // OTP on Mail and SMS
    'faculty_password_reset_otp' => 1,
    'inventory_sale_otp' => 1,// OTP on Mail and SMS
    'gate_pass_otp' => 1                // OTP required for gate pass
];
$otp_setting_json = json_encode($otp_settings_array); // JSON encode the OTP settings

// $homeworkSettingData = json_encode([
//     "homework_setting" => 1,
//     "homework_time" => "17:00 PM"
// ]);

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

//validattion
{
    // validate if company name is available
    if (!checkOnlyCharcterNumericwithSpace($name)) { // for english chars + numbers only
        // valid username, alphanumeric & longer than or equals 5 chars
        errorreturn('Invalid name');
    }

    if (!CheckCode($branch_code)) {
        //eg House Name, Street Name
        errorreturn('Invalid Branch Code');
    }
    
    if (strlen($branch_code) < 4 || strlen($branch_code) > 16) {
        errorreturn('Branch code must be between 4 and 16 characters.');
    }

    if (!CheckAddressValidation($address)) { // for english chars + numbers only
        //eg House Name, Street Name
        errorreturn('Invalid company address');
    }
    //Branch Pin Code Validation 
    if (!PinCodeValidation($pincode)) { // 6 digit only
        //eg House Name, Street Name
        errorreturn('Invalid Pin Code');
    }

    if (!preg_match("/^\+91[0-9]{10,}$/", $contact_number)) {
        errorreturn("Enter a valid mobile number starting with +91 and at least 10 digits. Given: " . $contact_number);
    }


    if (!CheckEMailIsValidOrNot($email)) {
        errorreturn('Enter valid Email Id');
    }
    if ($website != null) {
        if (!checkWebsiteUrl($website)) {
            errorreturn('Invalid Website URL.');
        }
    }
}

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

    $res = $conn_rjllearning_specific->prepare("SELECT institution_id,name,branch_code FROM branch WHERE institution_id = ? AND (branch_code = ? OR name = ?)  ");
    $res->execute(array($institution_id, $branch_code, $name));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("Branch name or code already exists");
    }

    try {
        $sql_branch = "INSERT INTO branch(institution_id,branch_code,name,city,pincode,address,contact_number,email,website,date_added,time_created,added_by,country,state,affiliation_code,status)
                                   VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $stmt_branch =  $conn_rjllearning_specific->prepare($sql_branch);

        $stmt_branch->execute(array($institution_id, $branch_code, $name, $city, $pincode, $address, $contact_number, $email, $website, $date_added, time(), $username, $country,$state,$affiliation_code, '1'));
        $id = $conn_rjllearning_specific->lastInsertId();
        
        //conductor ,driver, incharge store in other_staff_groups
        $staff_roles = ['Conductor', 'Driver', 'Incharge'];
        $sql_other_staff_groups = "INSERT INTO other_staff_groups (institution_id, branch_id, group_name, added_by, time_created, date_created, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt_other_staff_groups = $conn_rjllearning_specific->prepare($sql_other_staff_groups);
        foreach ($staff_roles as $staff_role) {
            $stmt_other_staff_groups->execute([$institution_id, $id, $staff_role, $username, time(), $date_added, 1]);
        }
        
        // Prepare the JSON value for accounting_setting
        $accounting_setting = json_encode([
            'student_ledger_display' => 0,
            'student_receipt_mail_alert' => 0
        ]);
        $send_sms_on_fee_receipt = 0;
        // Prepare the fields for processing student fees and transactions
        $fee_concession_application = 0;
        $faculty_attendance_fields = [
            'self_mark' => 0,   // Changed from [0] to 1
            'methods' => [
                'gps' => 0      // Changed from [0] to 0
            ]
        ];
        
        // Convert to JSON before inserting
        $faculty_attendance_fields_json = json_encode($faculty_attendance_fields);
        $sql_branch_global_settings = "INSERT INTO institution_global_settings (institution_id, branch_id, attendance_system,faculty_attendance_setting, otp_setting, accounting_setting,fee_concession_application,send_sms_on_fee_receipt,status, last_modified_by) 
        VALUES ( ?, ?, ?, ?, ?, ?, ?,?,?,?)";
        $stmt_branch_global_settings = $conn_rjllearning_specific->prepare($sql_branch_global_settings);
        $stmt_branch_global_settings->execute(array($institution_id, $id, 'day_wise',$faculty_attendance_fields_json, $otp_setting_json, $accounting_setting,$fee_concession_application,$send_sms_on_fee_receipt, 1, NULL));


        // Insert into print_settings
        $id_card_template_selected = 1;
        $sql_print_settings = "INSERT INTO print_settings(institution_id,branch_id,primary_color,secondary_color,id_card_template_selected,status,last_modified_by,last_updated_time,last_modified_at)
                               VALUES(?,?,?,?,?,?,?,?,?)";
        $stmt_print_settings = $conn_rjllearning_specific->prepare($sql_print_settings);
        $stmt_print_settings->execute(array($institution_id, $id, '#ddd', '#ddd', $id_card_template_selected, 1, NULL, NULL, NULL));
        
        // $collection_types = ['Monthly', 'Quarterly', 'Half Yearly', 'Yearly'];
        // foreach ($collection_types as $type) {
        //     $sql_fees = "INSERT INTO fees_collection_type (institution_id, branch_id, name) VALUES (?, ?, ?)";
        //     $stmt_fees = $conn_rjllearning_specific->prepare($sql_fees);
        //     $stmt_fees->execute([$institution_id, $id, $type]);
        // }


        // createTransportEntry($conn_rjllearning_specific, $institution_id, $id, $username);

        successreturn(array('branch_id' => $id, 'successmsg' => "Successfully branch added."));
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }
} else if ($postdata['function_type'] == "alter_branch") {

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

    $res = $conn_rjllearning_specific->prepare("SELECT id,institution_id,name FROM branch WHERE id != ? and institution_id =?  and (name=? or branch_code=?) ");
    $res->execute(array($id, $institution_id, $name, $branch_code));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("Branch Name already exists");
    }

    $sql = "UPDATE branch SET branch_code = ?,name=?, city=?,pincode=?,address=?,contact_number=?,email=?,website= ?,country=?,state= ?,affiliation_code = ? where id = ? and institution_id= ?";
    $conn_rjllearning_specific->prepare($sql)->execute(array($branch_code,$name, $city, $pincode, $address, $contact_number, $email, $website, $country,$state,$affiliation_code, $id, $institution_id));
    successreturn("Updated branch Successfully");
}
