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


require_once '/home/rejoicebilldesk/public_html/rjllearning_development/resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
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';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning_resources . "includes/pg_credentials_encryption_key.php";
$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();

// Required Fields
$required_fields = ['institution_id', 'branch_id', 'pg_vendor', 'pg_vendor_version', 'redirection_url', 'return_url', 'credentials', 'api_signature', 'jwt_token'];

foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || empty($postdata[$field])) {
        errorreturn("Missing or empty required field: $field");
    }
}

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

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

if (!$jwt_validate) {
    errorreturn("Invalid JWT Token");
}

// Extract User Info from JWT
$userid       = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username     = $jwt_validate->data->username;
$role         = $jwt_validate->data->role;

// Extract Post Data
$institution_id   = $postdata['institution_id'];
$branch_id        = $postdata['branch_id'];
$pg_vendor        = $postdata['pg_vendor'];
$pg_vendor_version = $postdata['pg_vendor_version'];
$redirection_url  = $postdata['redirection_url'];
$return_url       = $postdata['return_url'];


// **VALIDATIONS**
if (!is_numeric($institution_id) || $institution_id <= 0) {
    errorreturn("Invalid institution_id. Must be a positive integer.");
}

if (!is_numeric($branch_id) || $branch_id <= 0) {
    errorreturn("Invalid branch_id. Must be a positive integer.");
}

// Validate pg_vendor_version Format (e.g., 1.0.0)
if (!preg_match('/^\d+\.\d+\.\d+$/', $pg_vendor_version)) {
    errorreturn("Invalid pg_vendor_version format. Expected format: x.x.x (e.g., 1.0.0)");
}

// Validate Credentials as JSON
// Check if credentials is a valid JSON object
if (!isset($postdata['credentials']) || !is_array($postdata['credentials'])) {
    errorreturn("Invalid credentials format. Expected JSON object.");
}

// Required credential fields

// Encrypt Credentials
$credentials_json = json_encode($postdata['credentials']);
$encrypted_credentials = aes128Encrypt($credentials_json, $paymentGatewayCredentialKey);

// Validate User Access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin', 'admin'], null);
if (!$specific_db_name) {
    errorreturn("Access denied.");
}

// Establish Database Connection
$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

// Check Function Type
if ($postdata['function_type'] !== 'create_payment_gateway') {
    errorreturn("Invalid function type");
}


$checkStmt = $conn_rjllearning->prepare("
    SELECT id FROM payment_gateway_setup 
    WHERE workspace_id = ? AND institution_id = ? AND branch_id = ?  AND status = 1
");
$checkStmt->execute([$workspace_id, $institution_id, $branch_id]);
$existing = $checkStmt->fetch(PDO::FETCH_ASSOC);

if ($existing) {
    errorreturn("Payment gateway already exists for this workspace, institution, branch, and vendor. Please delete it first to re-add.");
}

// **INSERT INTO DATABASE**
$stmt = $conn_rjllearning->prepare("INSERT INTO payment_gateway_setup 
    (workspace_id, institution_id, branch_id, pg_vendor, pg_vendor_version, credentials, redirection_url, return_url, created_on, created_by, last_modified_on, last_modified_by, status) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, NOW(), ?, 1)");

$result = $stmt->execute([
    $workspace_id,
    $institution_id,
    $branch_id,
    $pg_vendor,
    $pg_vendor_version,
    $encrypted_credentials,
    $redirection_url,
    $return_url,
    $username,
    $username
]);

// Return Response
if ($result) {
    successreturn("Payment gateway details saved successfully", ["id" => $conn_rjllearning->lastInsertId()]);
} else {
    errorreturn("Error saving payment gateway details");
}
