<?php
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";
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_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";

global $conn_rjllearning, $paymentGatewayCredentialKey;

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    errorreturn("Invalid request method");
}

// Step 1: Capture encrypted response from POST
$encResp = $_POST['encResp'] ?? '';
if (!$encResp) {
    errorreturn("encResp not found");
}

// Step 2: Extract order_id parts first (encResp is still encrypted)
// ⚠️ You can’t JSON decode encResp – it’s not JSON
// Instead, decrypt first to get order_id
// But if you appended order_id separately in webhook payload, use it
$order_id = $_POST['orderNo'] ?? '';  // sometimes CCAvenue sends this

if (!$order_id) {
    // fallback: decrypt early just to get order_id
    // Temporarily fetch CCAvenue credentials first
    // You need workspace/institution/branch to fetch working_key
    // So best practice: always append order_id in your checkout req
    errorreturn("order_id not found in request");
}

// Split order_id to get workspace, institution, branch
$parts = explode('_', $order_id);
if (count($parts) < 5) {
    errorreturn("Invalid order_id format");
}
list($workspace_id, $institution_id, $branch_id, $student_id, $unique_id) = $parts;

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

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

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

if (empty($pg_credentials['working_key'])) {
    errorreturn("Incomplete CCAvenue credentials");
}

// Step 4: Decrypt encResp using working_key
$rcvdString = ccavenuedecrypt($encResp, $pg_credentials['working_key']);
parse_str($rcvdString, $data);

file_put_contents(__DIR__ . '/ccavenue_webhook_log.txt', 
    "\nDecrypted Response:\n" . print_r($data, true), FILE_APPEND);

// Step 5: Extract important fields
$status_text = strtolower($data['order_status'] ?? '');
$amount      = $data['amount'] ?? '0.00';
$txn_ref     = $data['tracking_id'] ?? '';
$order_id    = $data['order_id'] ?? $order_id; // fallback

$final_status = (in_array($data['order_status'], ['Success', 'Successful']) 
    ? "Successful" 
    : "Aborted");

// Step 6: Verify order_id parts again
$parts = explode('_', $order_id);
if (count($parts) < 5) {
    errorreturn("Invalid order_id format");
}
list($order_workspace_id, $order_institution_id, $order_branch_id, $student_id, $unique_id) = $parts;

if ($order_workspace_id != $workspace_id || $order_institution_id != $institution_id) {
    errorreturn("order_id mismatch with workspace/institution");
}

// Step 7: Process transaction
$conn_rjllearning->beginTransaction();

if (!checkFinwareStatusInitiatedTransaction($conn_rjllearning, $workspace_id, $institution_id, $order_id)) {
    if ($final_status === 'Successful') {
        $transaction_data = [
            'order_id' => $order_id,
            'amount'   => $amount,
            'payment_gateway' => 'ccavenue',
        ];

        createPaymentGatewayTransactionFinware(
            $conn_rjllearning,
            $workspace_id,
            $institution_id,
            $student_id,
            $transaction_data,
            $branch_id,
            'webhook'
        );
    } else {
        $sql = "UPDATE initiated_transactions 
                   SET finware_verification = ? 
                 WHERE workspace_id = ? AND institution_id = ? AND order_id = ?";
        $update = $conn_rjllearning->prepare($sql);
        $update->execute([-1, $workspace_id, $institution_id, $order_id]);
    }
}

if (!checkTransactionStatusLearningTable($conn_rjllearning, $workspace_id, $institution_id, $order_id)) {
    $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,
        $pg_vendor['id'],
        $order_id,
        'CCAvenue Webhook Order : ' . $order_id,
        $final_status === 'Successful' ? 1 : 0
    ]);

    $sql = "UPDATE initiated_transactions 
               SET status = ? 
             WHERE workspace_id = ? AND institution_id = ? AND order_id = ?";
    $update = $conn_rjllearning->prepare($sql);
    $update->execute([
        $final_status === 'Successful' ? 1 : -1,
        $workspace_id,
        $institution_id,
        $order_id
    ]);
}

$conn_rjllearning->commit();

exit;
