<?php
// Immediately acknowledge to webhook sender (CCAvenue)
http_response_code(200);

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 . "payment_gateway/whitelist/function.php";
require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_function_branch_students.php';
require_once $base_path_to_learning_resources . "external_requests/finware_curl/student/curl_student_transaction_finware.php";
require_once $base_path_to_learning_resources . "payment_gateway/student_payment_gateway_finware_transaction.php";
require_once $base_path_to_learning_resources . "payment_gateway/ccavenue/ccavenue_bank_function.php";
require_once $base_path_to_learning_resources . "includes/pg_credentials_encryption_key.php";

function errorreturnFileLog($x)
{
    file_put_contents('ccavenue_webhook_log.txt', "\n Error : \n" . $x, FILE_APPEND);
}

// Check method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    errorreturnFileLog('Invalid request method');
}

// Capture raw POST data (for logging and parsing)
$data = $_POST;

$order_id = $data['order_id'] ?? null;

$gateway = 'ccavenue';

if (empty($order_id)) {
    errorreturnFileLog("$order_id Unable to extract order ID");
}

// Parse order_id
$parts = explode('_', $order_id);
if (count($parts) < 5) {
    errorreturnFileLog("$order_id Invalid order_id format");
}

list($workspace_id, $institution_id, $branch_id, $student_id, $unique_id) = $parts;

// Fetch PG vendor setup
$stmt = $conn_rjllearning->prepare("SELECT id, pg_vendor, credentials FROM payment_gateway_setup WHERE workspace_id = ? AND institution_id = ? AND branch_id = ?  AND status = ? LIMIT 1");
$stmt->execute([$workspace_id, $institution_id, $branch_id, 1]);
$pg_vendor = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$pg_vendor) {
    errorreturnFileLog("$order_id PG Vendor not found for this branch");
}


global $paymentGatewayCredentialKey;
global $gateway;
try {

    $pg_credentials = json_decode(aes128Decrypt($pg_vendor['credentials'], $paymentGatewayCredentialKey), true);

    if (
        empty($pg_credentials['merchant_data']) ||
        empty($pg_credentials['access_code']) ||
        empty($pg_credentials['working_key'])
    ) {
        errorreturnFileLog("$order_id Incomplete CCAvenue credentials.");
    }

    if (!isset($data['encResp'])) {
        errorreturnFileLog("$order_id Ivalid response from CCAvenue");
    }

    $encResp = $data['encResp'];
    $decrypted_response = ccavenuedecrypt($encResp, $pg_credentials['working_key']);
    parse_str($decrypted_response, $response);

    if (!isset($response['order_id'], $response['order_status'], $response['tracking_id'])) {
        errorreturnFileLog("$order_id Incomplete response from CCAvenue");
    }

    file_put_contents('ccavenue_webhook_log.txt', "\nObject Response\n" . print_r($response, true), FILE_APPEND);


    $order_id = $response['order_id'] ?? null;
    $order_status = $response['order_status'] ?? 'Unknown';
    $amount = $response['amount'] ?? 0;

    $status = (strtolower($order_status) === 'success') ? 1 :  0;
} catch (Exception $e) {
    errorreturnFileLog("Error : $order_id " . $e->getMessage());
}


$pg_vendor = 'ccavenue';

// STEP 3: Begin DB Transaction
$conn_rjllearning->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
$conn_rjllearning->beginTransaction();

$stmt = $conn_rjllearning->prepare("SELECT * FROM transactions WHERE reference_no = ?");
$stmt->execute([$order_id]);
$existing = $stmt->fetch(PDO::FETCH_ASSOC);

// Get gateway_id if not already
$stmt = $conn_rjllearning->prepare("SELECT id FROM payment_gateway_setup WHERE pg_vendor = ?");
$stmt->execute([$pg_vendor]);
$pg_row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$pg_row) {
    errorreturn("Gateway vendor '$pg_vendor' not found");
}
$gateway_id = $pg_row['id'];

if ($status == 1) {
    if (!$existing) {

        $remarks = $pg_vendor . ' response for order_id : ' . $order_id . '. Status : ' . $_POST['status'];

        // also insert in createPaymentGatewayTransaction
        $transaction_data = [
            'order_id' => $order_id,
            'amount' => $amount,
            'payment_gateway' => "ccavenue",
        ];

        $student_id = $parts[3];

        $create_finware_transaction_response = createPaymentGatewayTransactionFinware($conn_rjllearning, $workspace_id, $institution_id, $student_id, $transaction_data, $branch_id, 'webhook'); // admission number is sent in student id her
        
        file_put_contents('ccavenue_webhook_log.txt', "\n FINWARE RESPONSE : \n" . print_r($create_finware_transaction_response, true), FILE_APPEND);

        // INSERT new transaction
        $insert = $conn_rjllearning->prepare("INSERT INTO transactions 
            (workspace_id, institution_id, branch_id, amount, gateway_id, reference_no, remarks, status, created_at, updated_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");

        $insert->execute([
            $workspace_id,
            $institution_id,
            $branch_id,
            $amount,
            $gateway_id,
            $order_id,
            $remarks,
            $status
        ]);

        // update initiated_transactions with positive response
        $sql = "UPDATE initiated_transactions set status = ? where workspace_id = ? and institution_id = ? and order_id = ?";
        $update = $conn_rjllearning->prepare($sql);
        $update->execute(array(1, $workspace_id, $institution_id, $order_id));
    } elseif ($existing['status'] != $status) {
    }
} else {
    $sql = "UPDATE initiated_transactions set status = ?, finware_verification = ? where workspace_id = ? and institution_id = ? and order_id = ?";
    $update = $conn_rjllearning->prepare($sql);
    $update->execute(array(1, 1, $workspace_id, $institution_id, $order_id));
    
        if (!$existing) {

    // INSERT new transaction
        $insert = $conn_rjllearning->prepare("INSERT INTO transactions 
            (workspace_id, institution_id, branch_id, amount, gateway_id, reference_no, remarks, status, created_at, updated_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");

        $insert->execute([
            $workspace_id,
            $institution_id,
            $branch_id,
            $amount,
            $gateway_id,
            $order_id,
            $remarks,
            -1
        ]);
        } else {

        $sql = "UPDATE transactions set status = ? where workspace_id = ? and institution_id = ? and reference_no = ?";
        $update = $conn_rjllearning->prepare($sql);
        $update->execute(array(-1, $workspace_id, $institution_id, $order_id));
    }
}

// COMMIT transaction
$conn_rjllearning->commit();

exit;
