<?php
// File: checkout_callback.php (SERVER WEBHOOK)

require_once 'db.php';
require_once 'phonepe_config.php';
require_once 'email_helper.php';

// 1. Polyfill for getallheaders() (for GoDaddy)
if (!function_exists('getallheaders')) {
    function getallheaders() {
        $headers = [];
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $header_key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
                $headers[$header_key] = $value;
            }
        }
        return $headers;
    }
}

// 2. Get RAW POST Data from PhonePe Server
$raw_post = file_get_contents('php://input');
$data = json_decode($raw_post, true);
$decoded_response_str = $data['response'] ?? '';
if (!$decoded_response_str) {
    http_response_code(400);
    echo "Empty response payload.";
    exit();
}

// 3. Verify PhonePe's Signature
$salt_key = $PHONEPE_SALT_KEY;
$salt_index = $PHONEPE_SALT_INDEX;
$expected_hash = hash('sha256', $decoded_response_str . $salt_key) . '###' . $salt_index;
$headers = getallheaders();
$x_verify_header = $headers['x-verify'] ?? $headers['X-Verify'] ?? null;

if ($x_verify_header !== $expected_hash) {
    http_response_code(401);
    error_log("PhonePe (Checkout) Webhook Hash Mismatch.");
    echo "Invalid signature.";
    exit();
}

// 4. Decode the Data
$response = json_decode(base64_decode($decoded_response_str), true);
$merchantTransactionId = $response['data']['merchantTransactionId'] ?? null;
$payment_status_code = $response['code'] ?? 'PAYMENT_ERROR';
$phonepe_txn_id = $response['data']['transactionId'] ?? null;

if (!$merchantTransactionId) {
    http_response_code(400);
    echo "Missing merchantTransactionId.";
    exit();
}

// 5. Process the Payment
// ⭐️ Using your table's 'payment_status' column enums
if ($payment_status_code === 'PAYMENT_SUCCESS') {
    $new_status = 'completed'; // Your 'completed' status
} else {
    $new_status = 'failed'; // Your 'failed' status
}

try {
    // Find the pending order
    $stmt_find = $conn->prepare("SELECT id, user_id, shipping_name, total_amount FROM orders WHERE merchant_transaction_id = ? AND payment_status = 'pending'");
    $stmt_find->bind_param("s", $merchantTransactionId);
    $stmt_find->execute();
    $order = $stmt_find->get_result()->fetch_assoc();
    $stmt_find->close();

    if ($order) {
        // Update order status and save the PhonePe TXN ID
        // ⭐️ Using your table's column names
        $stmt_update = $conn->prepare("UPDATE orders SET payment_status = ?, payment_gateway_txn_id = ? WHERE id = ?");
        $stmt_update->bind_param("ssi", $new_status, $phonepe_txn_id, $order['id']);
        $stmt_update->execute();
        $stmt_update->close();

        // Send confirmation email ONLY on success
        if ($new_status === 'completed') {
            $stmt_user = $conn->prepare("SELECT email FROM users WHERE id = ?");
            $stmt_user->bind_param("i", $order['user_id']);
            $stmt_user->execute();
            $user = $stmt_user->get_result()->fetch_assoc();
            $stmt_user->close();

            if ($user) {
                $subject = "Your Order is Confirmed! (ID: {$order['id']})";
                $message_body = "
                    <h1>Thank You for Your Order!</h1>
                    <p>Dear {$order['shipping_name']},</p>
                    <p>Your payment of <strong>₹{$order['total_amount']}</strong> was successful.</p>
                    <p>Your Order ID is <strong>{$order['id']}</strong>. We will notify you when it ships.</p>
                ";
                // Assumes you have a sendEmail() function in email_helper.php
                sendEmail($user['email'], $subject, $message_body);
            }
        }
    }
    // If order not found, it's a duplicate webhook (already processed).
    
} catch (Exception $e) {
    error_log("PhonePe (Checkout) Webhook DB Error: " . $e->getMessage());
    http_response_code(500);
    echo "Database error.";
    exit();
}

http_response_code(200);
echo "Webhook processed.";
?>