<?php
// Enable error display for debugging
ini_set('display_errors', 1);

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

// 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']);

// Set default ID card settings if not provided
if (!isset($postdata['id_card_setting'])) {
    $id_card_settings_array = [
        // 'id_card' => 1,
        'template_id' => 1
    ];
} else {
    $id_card_settings_array = $postdata['id_card_setting'];
}

// print_r($id_card_settings_array);


$id_card_setting_json = json_encode($id_card_settings_array); // JSON encode the ID card settings

// 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.");
}

if ($postdata['function_type'] == "update_id_card_setting") {
    $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.");
    }

    // Update setting
    $sql = "UPDATE institution_global_settings SET id_card_setting = ?, last_modified_by=?, last_updated_time=? WHERE institution_id = ? AND branch_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);

    // Get the current timestamp and format it as a date string
    $last_updated_time = date("Y-m-d H:i:s", time());

    // Execute the SQL query with the formatted date string
    $stmt->execute([$id_card_setting_json, $username, $last_updated_time, $institution_id, $branch_id]);

    // Return success message
    successreturn("Updated institution global settings successfully.");
} else {
    errorreturn("Invalid Function Type");
}
