<?php
require_once('../db.php');

define('ESEWA_SECRET', '8gBm/:&EnhH.1/q'); // CRITICAL: Matches eSewa dashboard
// STEP 1: Check for Base64 encoded `data`
if (!isset($_GET['data'])) {
    $error_message = "Invalid response from eSewa.";
    error_log("eSewa Callback Error: Missing 'data' parameter");
    $status = "error";
} else {
    // STEP 2: Decode base64 JSON
    $decoded_json = base64_decode($_GET['data']);
    $response_data = json_decode($decoded_json, true);

    if (!$response_data || !isset($response_data['transaction_uuid'])) {
        $error_message = "Failed to decode or missing required data.";
        error_log("eSewa Callback Error: Invalid JSON or missing transaction_uuid");
        $status = "error";
    } else {
        // STEP 3: Validate the signature
        $signed_fields = explode(',', $response_data['signed_field_names']);
        $signature_string = '';
        foreach ($signed_fields as $field) {
            if (!isset($response_data[$field])) {
                $error_message = "Missing field in signed data: $field";
                error_log("eSewa Callback Error: Missing signed field - $field");
                $status = "error";
                break;
            }
            $signature_string .= $field . '=' . $response_data[$field] . ',';
        }
        $signature_string = rtrim($signature_string, ',');

        // Generate HMAC-SHA256 signature
        $generated_signature = base64_encode(hash_hmac('sha256', $signature_string, ESEWA_SECRET, true));

        // Log for debugging (disable in production)
        error_log("eSewa Callback: Signature String: $signature_string");
        error_log("eSewa Callback: Generated Signature: $generated_signature");
        error_log("eSewa Callback: Received Signature: " . ($response_data['signature'] ?? 'N/A'));

        // Validate signature
        if ($generated_signature !== $response_data['signature']) {
            $error_message = "Invalid signature. Potential tampering.";
            error_log("eSewa Callback Error: Signature mismatch.");
            $status = "error";
        } else {
            // STEP 4: Update the DB only if status is COMPLETE
            $txn_uuid = $response_data['transaction_uuid'];
            $payment_status = $response_data['status'];

            if ($payment_status === 'COMPLETE') {
                // Start a transaction to ensure data consistency
                $conn->begin_transaction();

                try {
                    // Update saving table status to 'Success'
                    $stmt = $conn->prepare("UPDATE saving SET Status = 'Success' WHERE TransactionUUID = ?");
                    $stmt->bind_param("s", $txn_uuid);
                    $stmt->execute();
                    $stmt->close();

                    // Get the amount from response_data (assuming 'total_amount' is the field name)
                    $amount = isset($response_data['total_amount']) ? floatval($response_data['total_amount']) : null;
                    if ($amount === null || $amount <= 0) {
                        throw new Exception("Invalid or missing amount in eSewa response.");
                    }

// Step 1: Check if TransactionUUID already exists
$stmt = $conn->prepare("SELECT COUNT(*) as count FROM balance WHERE TransactionUUID = ?");
$stmt->bind_param("s", $txn_uuid);
$stmt->execute();
$result = $stmt->get_result();
$txn_exists = $result->fetch_assoc()['count'] > 0;
$stmt->close();

if ($txn_exists) {
    // TransactionUUID exists → update Amount only
    $stmt = $conn->prepare("UPDATE balance SET Amount = ? WHERE TransactionUUID = ?");
    $stmt->bind_param("ds", $amount, $txn_uuid);
    if ($stmt->execute()) {
        echo "Amount updated for TransactionUUID: $txn_uuid";
    } else {
        echo "Error updating by TransactionUUID: " . $stmt->error;
    }
    $stmt->close();

} else {
    // TransactionUUID does not exist → check if Mid exists
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM balance WHERE Mid = ?");
    $stmt->bind_param("s", $mid);
    $stmt->execute();
    $result = $stmt->get_result();
    $mid_exists = $result->fetch_assoc()['count'] > 0;
    $stmt->close();

    if ($mid_exists) {
        // Mid exists → update that row with new TransactionUUID and Amount
        $stmt = $conn->prepare("UPDATE balance SET Amount = ?, TransactionUUID = ? WHERE Mid = ?");
        $stmt->bind_param("dss", $amount, $txn_uuid, $mid);
        if ($stmt->execute()) {
            echo "Updated Amount and TransactionUUID for existing Mid: $mid";
        } else {
            echo "Error updating by Mid: " . $stmt->error;
        }
        $stmt->close();

    } else {
        // Neither TransactionUUID nor Mid found → reject
        echo "Payment not accepted. No matching TransactionUUID or Mid.";
    }
}



                    // Commit the transaction
                    $conn->commit();
                    echo "Payment processed successfully.".$amount;

                    $success_message = "Payment successful! Transaction ID: " . htmlspecialchars($txn_uuid) . ", Amount: " . htmlspecialchars($amount);
                    $status = "success";
                } catch (Exception $e) {
                    // Rollback transaction on error
                    $conn->rollback();
                    $error_message = "Database update error: " . $e->getMessage();
                    error_log("eSewa Callback Error: DB update failed - " . $e->getMessage());
                    $status = "error";
                }
            } else {
                $error_message = "Payment was not completed. Status: " . htmlspecialchars($payment_status);
                error_log("eSewa Callback Error: Payment status not COMPLETE - $payment_status");
                $status = "error";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>eSewa Payment Status</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">
    <?php include '../includes/navbar.php'; ?>
    <div class="bg-white p-8 rounded-lg shadow-lg max-w-md w-full text-center">
        <?php if ($status === "success"): ?>
            <div class="text-green-600 mb-4">
                <svg class="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                </svg>
                <h2 class="text-2xl font-bold mb-2">Payment Successful</h2>
                <p class="text-gray-700"><?php echo $success_message; ?></p>
            </div>
        <?php else: ?>
            <div class="text-red-600 mb-4">
                <svg class="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
                <h2 class="text-2xl font-bold mb-2">Payment Failed</h2>
                <p class="text-gray-700"><?php echo $error_message; ?></p>
            </div>
        <?php endif; ?>
        <a href="saving.php" class="mt-6 inline-block bg-blue-600 text-white px-6 py-2 rounded hover:bg-blue-700 transition">
            Return to Savings Page
        </a>
    </div>
</body>
</html>