<?php
// Enable error display for debugging
ini_set('display_errors', 1);
ini_set('max_execution_time', 0);
// Include necessary files
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';
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 . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.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/book/curl_alter_institution_setting_finware.php';



// Decode JSON input data
$postdata = json_decode(file_get_contents("php://input"), true);

// Check if no data was received
checkIfNoPhpContentsReceive();

// Validate required fields
$requiredFields = ['branch_id', 'institution_id', 'api_signature', 'function_type', 'jwt_token'];
foreach ($requiredFields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.");
    }
}

// Validate API signature
validateApiSignature($postdata['api_signature']);

// Authenticate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
// Extract user details from JWT token
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

// Validate user access and get specific database name
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["superadmin","admin","principal","teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

// Sanitize input data
$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$branch = getBranchDetails($conn_rjllearning_specific, $branch_id, $institution_id);
if ($branch === null) {
    // If branch details are null, editing is not allowed
    errorreturn("Finware database connection is not established with learning.");
}


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


$isBranchClassSubjectValid = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, null, null, $institution_id);
if (!$isBranchClassSubjectValid) {
    errorreturn("Invalid branch_id.");
}
// Validate attendance settings
// if (!isset($postdata['accounting_setting'])) {
//     errorreturn("Accounting settings are required.");
// }

// // Validate attendance settings
// if (!isset($postdata['accounting_setting']) || empty($postdata['accounting_setting'])) {
//     errorreturn("accounting setting are required.");
// }

// $accounting_setting = $postdata['accounting_setting'];
$send_sms_on_fee_receipt = $postdata['send_sms_on_fee_receipt'];

// Define valid values for each field
// $valid_accounting_setting  = [0, 1];

// Validate `generate_fee` and `transaction_value`
// if (!isset($accounting_setting['student_ledger_display']) || !in_array((int)$accounting_setting['student_ledger_display'], $valid_accounting_setting)) {
//     errorreturn("Invalid value for student display ledger. Must be 0 or 1.");
// }

// if (!isset($accounting_setting['student_receipt_mail_alert']) || !in_array((int)$accounting_setting['student_receipt_mail_alert'], $valid_accounting_setting)) {
//     errorreturn("Invalid value for student receipt mail. Must be 0 or 1.");
// }
// if (!isset($accounting_setting['send_sms_on_fee_receipt']) || !in_array((int)$accounting_setting['send_sms_on_fee_receipt'], $valid_accounting_setting)) {
//     errorreturn("Invalid value for student receipt sms. Must be 0 or 1.");
// }

// // Ensure that both cannot be 1 simultaneously
// if ((int)$accounting_setting['display_ledger_bool'] === 1 && (int)$accounting_setting['student_receipt_mail'] === 1) {
//     errorreturn("Both display ledger and student receipt mail value cannot be 1 at the same time.");
// }
// Create the accounting settings array
// $accounting_settings_array = [
//     'student_ledger_display' => (int)$accounting_setting['student_ledger_display'],
//     'student_receipt_mail_alert' => (int)$accounting_setting['student_receipt_mail_alert']
// ];

// $accounting_setting_json = json_encode($accounting_settings_array);

$fee_concession_application = $postdata['fee_concession_application'];


// // Validate attendance settings
if (!isset($postdata['fee_concession_application'])) {
    errorreturn("fees processing setting are required.");
}

if (!isset($postdata['send_sms_on_fee_receipt'])) {
    errorreturn("SMS fee receipt setting are required.");
}

// // Define valid values for each field
// $valid_values = [0, 1];

// // Validate `generate_fee` and `transaction_value`
// if (!isset($fees_processing_setting['generate_fee']) || !in_array((int)$fees_processing_setting['generate_fee'], $valid_values)) {
//     errorreturn("Invalid value for generate_fee. Must be 0 or 1.");
// }

// if (!isset($fees_processing_setting['transaction_value']) || !in_array((int)$fees_processing_setting['transaction_value'], $valid_values)) {
//     errorreturn("Invalid value for transaction_value. Must be 0 or 1.");
// }

// // Ensure that both cannot be 1 simultaneously
// if ((int)$fees_processing_setting['generate_fee'] === 1 && (int)$fees_processing_setting['transaction_value'] === 1) {
//     errorreturn("Both generate fee and transaction value cannot be 1 at the same time.");
//}

// $fees_processing_setting_array = [
//     'generate_fee' => (int)$fees_processing_setting['generate_fee'],
//     'transaction_value' => (int)$fees_processing_setting['transaction_value']
// ];
// $fees_processing_setting_json = json_encode($fees_processing_setting_array);

// Check if the function type is for updating global settings
if ($postdata['function_type'] == "update_institution_global_settings") {
    // Validate branch existence
    $sql = $conn_rjllearning_specific->prepare("SELECT id FROM branch WHERE id = ? AND institution_id = ?");
    $sql->execute([$branch_id, $institution_id]);
    $result = $sql->fetchAll();

    if (count($result) != 1) {
        errorreturn("Branch not found.");
    }
    $conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
    $conn_rjllearning_specific->beginTransaction();
    try {
    // Prepare and execute the update statement
    $sql = "UPDATE institution_global_settings 
            SET  fee_concession_application = ?,send_sms_on_fee_receipt = ?, last_modified_by = ?, last_updated_time = ? 
            WHERE institution_id = ? AND branch_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);

    // Get the current timestamp for last_updated_time
    $last_updated_time = date("Y-m-d H:i:s");

    // Execute the update query
    $stmt->execute([$fee_concession_application,$send_sms_on_fee_receipt,$username, $last_updated_time, $institution_id, $branch_id]);
    $accounting_setting = json_encode([
            'student_ledger_display' => 0,
            'student_receipt_mail_alert' => 0,
            'custom_sms_header' => ''
        ]);
    $branch = getBranchDetails($conn_rjllearning_specific, $branch_id, $institution_id);
    if (!empty($branch)) {
         $formattedData = array(
                "workspace_id" => $workspace_id,   
                "accounting_setting"=>$accounting_setting,
                "fee_concession_application" => $fee_concession_application,
                "send_sms_on_fee_receipt" => $send_sms_on_fee_receipt,
                "branch" => $branch
            );
       
        curlAlterInstitutionSettingsFinware($formattedData);
    }
    $conn_rjllearning_specific->commit();
    // Return success message
    successreturn("Updated institution global settings successfully.");
    
    } catch (Exception $e) {
        $conn_rjllearning_specific->rollBack();
        errorreturn("Error : " . $e->getMessage());
    }
}
?>

?>
