<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

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_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . 'admin_api/modules/students/student_functions.php';
require_once $base_path_to_learning_resources . 'lib/cron_jobs/function/function.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 . 'admin_api/global_settings/otp_settings/functions.php';
require_once $base_path_to_learning_resources . 'lib/cron_jobs/sms_function/sms_function.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

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

validateApiSignature($postdata['api_signature']);

// Validate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

// Extract user details from JWT
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$jwt_name = $jwt_validate->data->name;
$jwt_email = $jwt_validate->data->email;

$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$otp_authorisation = trim($postdata['otp_authorisation']);

if ($otp_authorisation !== "self") {
    if (!isset($postdata['first_party']) || !checkIfIssetAndNotEmpty($postdata['first_party'])) {
        errorreturn("Field 'first_party' is required");
    }
    $first_party = $postdata['first_party']; // "student_id" or "vendor name"
} else {
    $first_party = null;
}

// Validate user access and get specific database name
$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);
}

if ($postdata['function_type'] == "generate_inventorysale_otp") {
    $userToken = generate_inventorysale_otp(
        $conn_rjllearning,
        $conn_rjllearning_specific,
        $institution_id,
        $branch_id,
        $otp_authorisation,
        $username,
        $workspace_id,
        $web_app_title,
        $first_party, 
        $userid, 
        $jwt_email
    );

    // Return the success response with the user_token
    successreturn(array(
        'user_Token' => $userToken,
    ));
} else {
    errorreturn("Invalid Function Type.");
}
