<?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_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
if (
    // !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    // !isset($postdata['print_id']) or !checkIfIssetAndNotEmpty($postdata['print_id']) or
// !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or
!isset($postdata['primary_color']) or !checkIfIssetAndNotEmpty($postdata['primary_color']) or
!isset($postdata['secondary_color']) or !checkIfIssetAndNotEmpty($postdata['secondary_color']) or
!isset($postdata['id_card_template_selected']) or !checkIfIssetAndNotEmpty($postdata['id_card_template_selected']) 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.");
}

// 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;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

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

// $setting_id = trim($postdata['print_id']);
// $institution_id = trim($postdata['institution_id']);
// $branch_id = trim($postdata['branch_id']);
$primary_color = trim($postdata['primary_color']);
$secondary_color = trim($postdata['secondary_color']);
$id_card_template_selected = trim($postdata['id_card_template_selected']);
$status = trim($postdata['status']);
$last_updated_time = date("Y-m-d H:i:s", time());
// 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.");
}

if ($postdata['function_type'] == "update_print_settings") {
    
    $ExecuteSqlTemplate = $conn_rjllearning->prepare("SELECT id FROM id_cards_template WHERE id = ? ");
    $ExecuteSqlTemplate->execute([$id_card_template_selected]);
    $ResultTemplate = $ExecuteSqlTemplate->fetchAll();
    if (count($ResultTemplate) != 1) {
        errorreturn("Id Card Template not exists.");
    }
 
    $ExecuteSqlSettings = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM print_settings WHERE institution_id = ? AND branch_id = ?");
    $ExecuteSqlSettings->execute([$institution_id,$branch_id]);
    $ResultSettings = $ExecuteSqlSettings->fetchAll();
 
    if ($ResultSettings < 1) {
        errorreturn("Institution print setting not exists.");
    }

    $sql = "UPDATE print_settings SET  primary_color=?,secondary_color= ?,id_card_template_selected = ?,status = ?, last_modified_by=?, last_updated_time=?,last_modified_at = ? WHERE  institution_id = ? and branch_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$primary_color,$secondary_color,$id_card_template_selected,$status, $username,$last_updated_time,date('Y-m-d'),$institution_id,$branch_id]);
    successreturn("Updated print settings successfully.");

}
?>
