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

//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning .  'principal_api/modules/staff/staff_details/staff_functions.php';

$postdata = json_decode(file_get_contents("php://input"), true);
// $postdata = $_POST;
checkIfNoPhpContentsReceive();
// print_r($postdata);die();
if (
    // !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['name']) or !checkIfIssetAndNotEmpty($postdata['name'])  or
    !isset($postdata['email']) or !checkIfIssetAndNotEmpty($postdata['email'])  or
    !isset($postdata['phone']) or !checkIfIssetAndNotEmpty($postdata['phone'])  or
    !isset($postdata['group_id']) or !checkIfIssetAndNotEmpty($postdata['group_id'])  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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
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);

$name = ucwords(strtolower(trim($postdata['name'])));
$email = trim($postdata['email']);
$phone = trim($postdata['phone']);
$address = (isset($postdata['address']) and !empty($postdata['address'])) ? trim($postdata['address']) : null;
$group_id = trim($postdata['group_id']);
$date_of_joining = trim(date('Y-m-d', strtotime($postdata['date_of_joining'])));
$print_bank_details = (isset($postdata['print_bank_details']) and !empty($postdata['print_bank_details'])) ? trim($postdata['print_bank_details']) : null;
$account_name = (isset($postdata['account_name']) and !empty($postdata['account_name'])) ? ucwords(trim($postdata['account_name'])) : null;
$account_holder_name = (isset($postdata['account_holder_name']) and !empty($postdata['account_holder_name'])) ? trim($postdata['account_holder_name']) : null;
$account_no = (isset($postdata['account_no']) and !empty($postdata['account_no'])) ? trim($postdata['account_no']) : null;
$ifsc_code = (isset($postdata['ifsc_code']) and !empty($postdata['ifsc_code'])) ? trim($postdata['ifsc_code']) : null;
$branch_address = (isset($postdata['branch_address']) and !empty($postdata['branch_address'])) ? trim($postdata['branch_address']) : null;
$account_type = (isset($postdata['account_type']) and !empty($postdata['account_type'])) ? trim($postdata['account_type']) : null;
//validation 
if($address != null){
   if (!CheckAddressValidation($address)) {
        //eg House Name, Street Name
        errorreturn('Invalid Address' .$address);
    }
}
if ($email != null) {
    if (!CheckEMailIsValidOrNot($email)) {
        errorreturn('Enter valid Email Id');
    }
}
if (!CheckStartDate($date_of_joining)) {
    //eg House Name, Street Name
    errorreturn('Invalid Date of joining Format');
}
if (strlen($phone) != 13 or $phone <= 0) {
    errorreturn('Enter valid 12 digit mobile number ' . $phone);
}
if ($print_bank_details ==  '1' and $print_bank_details != null) {
    if (empty($account_name) || !preg_match('/^[A-Za-z\s]+$/', $account_name)) {
        errorreturn("Account holder name should only contain letters and spaces.");
    }
    
     if (empty($account_no) ||  isset($account_no) && !preg_match('/^\d{11}$/', $account_no)) {
        errorreturn("Account number should be 11 digits.");
     }

    if (empty($account_no) ||  isset($account_no) && !preg_match('/^\d{11}$/', $account_no)) {
        errorreturn("Account number should be 11 digits.");
    }
    if (empty($ifsc_code) || isset($ifsc_code) && !preg_match('/^[A-Z]{4}0[A-Z0-9]{6}$/', $ifsc_code)) {
        errorreturn("IFSC code format is incorrect.");
    }
    if (empty($account_holder_name) || isset($account_holder_name) && !preg_match('/^[A-Za-z\s]+$/', $account_holder_name)) {
        errorreturn("Account holder name should only contain letters and spaces.");
    }
    if (empty($branch_address) || isset($branch_address) && !preg_match('/^[A-Za-z0-9\s\-.,#\/]+$/', $branch_address)) {
        errorreturn("Branch address contains invalid characters.");
    }
    if (empty($account_type) || isset($account_type) && $account_type !== "savings" && $account_type !== "current") {
        errorreturn("Invalid account type. Allowed types are 'savings' or 'current'.");
    }
}

$sql_staff = "SELECT * FROM staff_groups WHERE id = ? AND institution_id =? AND branch_id = ?";
$stmt_staff = $conn_rjllearning_specific->prepare($sql_staff);
$stmt_staff->execute(array($group_id, $institution_id,$branch_id));
$result_staff = $stmt_staff->fetchAll();
if (count($result_staff) < 1) {
    errorreturn("Staff group not found.");
}

if ($postdata['function_type'] == 'create_staff') {

        $success = createStaff($conn_rjllearning_specific,$institution_id,$branch_id,$name,$email,$phone,$address,$group_id,$date_of_joining,$print_bank_details,$account_holder_name,$account_name,$account_no,$ifsc_code,$branch_address,$account_type,$username);
         if ($success != false) {
             $staff_id = $success;
             successreturn(array('staff_id' => $staff_id, 'successmsg' => "staff detail added successfully."));
        } else {
            errorreturn("Invalid Staff Details.");
        }
       
      
} if (!isset($postdata['staff_id']) or !checkIfIssetAndNotEmpty($postdata['staff_id']) and !checkIfIssetAndNotEmpty($postdata['staff_id']) ) {
            errorreturn('Error in updating the staff id.');
        } else {
            $staff_id = $postdata['staff_id'];
        }

        if ($postdata['function_type'] == 'alter_staff') {

            $sql = "Select name from staff_details where  id != ? AND institution_id = ? AND branch_id = ? AND (name = ? OR email = ? OR phone = ?) ";
            $fetch_staff = $conn_rjllearning_specific->prepare($sql);
            $fetch_staff->execute(array($staff_id,$institution_id,$branch_id,$name,$email,$phone));
            $result_staff = $fetch_staff->fetchAll();
            if (count($result_staff) > 0) {
                errorreturn('Staff already exists.');
            }

            $sql = "Update  staff_details set name = ?,email  = ?,phone = ?,address = ?,group_id =?,date_of_joining = ?,print_bank_details = ?,account_holder_name = ?,account_name = ?,account_no = ?,ifsc_code = ?,branch_address= ?,account_type = ? where id = ? and institution_id = ? AND branch_id = ?";
            $insert_ledger = $conn_rjllearning_specific->prepare($sql);
            $insert_ledger->execute(array($name,$email,$phone,$address,$group_id,$date_of_joining,$print_bank_details,$account_holder_name,$account_name,$account_no,$ifsc_code,$branch_address,$account_type,$staff_id, $institution_id,$branch_id));
        

            successreturn('Staff updated successfully.');
        }
        errorreturn('Invalid request.');
