<?php

ini_set('display_errors', 1);

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';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning . 'admin_api/global_settings/otp_settings/functions.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

checkIfNoPhpContentsReceive();

if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_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  !isset($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}
validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$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);
}


function fetchTemplates_details($workspace_id, $institution_id, $branch_id, $conn_rjllearning)
{
    $static_path = 'https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/';

    $sql = "SELECT * 
            FROM template_info WHERE workspace_id = ? OR workspace_id IS NULL 
            AND institution_id = ? OR institution_id IS NULL
            AND branch_id = ? OR branch_id IS NULL";
    $params = [$workspace_id, $institution_id, $branch_id];
    
    // $sql = "SELECT * 
    //         FROM template_info WHERE workspace_id = ? OR workspace_id IS NULL
    //         AND institution_id = ? OR institution_id IS NULL";
    // $params = [$workspace_id, $institution_id];
    
    // if ($institution_id != 'all' && $institution_id != null) {
    //     $sql .= " AND institution_id = ?";
    //     $params[] = $institution_id;
    // }
    
    // if ($branch_id != 'all' && $branch_id != null) {
    //     $sql .= " AND branch_id = ?";
    //     $params[] = $branch_id;
    // }

    $stmt = $conn_rjllearning->prepare($sql);
    $stmt->execute($params);
    $result_total = $stmt->fetchAll();

    $templates = [];

    foreach ($result_total as $row) {
        $preview_image_path = $static_path . $row['template_name'] . '/' . $row['preview_image'];
        $templates[] = [
            'template_id' => $row['id'],
            'preview' => $preview_image_path,
            'template_name' => $row['template_name'],
            'template_description' => $row['description'],
            'pattern' => $row['pattern'],
            'workspace_id' => $row['workspace_id'],
            'institution_id' => $row['institution_id'],
            'branch_id' => $row['branch_id'],
            'label' => $row['label']
        ];
    }

    return $templates;
}

if ($postdata['function_type'] == "fetch_Templates") {
    $institution_id = trim($postdata['institution_id']);
    $branch_id = isset($postdata['branch_id']) && !empty($postdata['branch_id']) ? trim($postdata['branch_id']) : null;
    $templates= fetchTemplates_details($workspace_id, $institution_id, $branch_id, $conn_rjllearning);
    successreturn($templates);
}