<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../inc/payment_helpers.php';
require_once __DIR__ . '/../lib/razorpay-php/Razorpay.php';

use Razorpay\Api\Api;
use Razorpay\Api\Errors\SignatureVerificationError;

$input         = json_decode(file_get_contents('php://input'), true) ?? [];
$tracking_code = trim($input['tracking_code']       ?? '');
$payment_id    = trim($input['razorpay_payment_id'] ?? '');
$order_id      = trim($input['razorpay_order_id']   ?? '');
$signature     = trim($input['razorpay_signature']  ?? '');

if (!$tracking_code || !$payment_id || !$order_id || !$signature) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Missing parameters']);
    exit;
}

try {
    $api = new Api(RAZORPAY_KEY_ID, RAZORPAY_SECRET);

    // 1. Verify signature first
    $api->utility->verifyPaymentSignature([
        'razorpay_order_id'   => $order_id,
        'razorpay_payment_id' => $payment_id,
        'razorpay_signature'  => $signature,
    ]);

    // 2. Fetch payment details from Razorpay
    $payment = $api->payment->fetch($payment_id);

    $actual_amount   = ($payment['currency'] === 'VND')
        ? (float)$payment['amount']
        : (float)$payment['amount'] / 100;
    $actual_currency = strtoupper($payment['currency']);
    $payer_email     = $payment['email']   ?? '';
    $payer_contact   = $payment['contact'] ?? '';
    $payer_name      = $payment['notes']['name'] ?? $payer_contact;
    $rzp_status      = $payment['status'];
    $db_status       = in_array($rzp_status, ['captured', 'authorized']) ? 'COMPLETED' : strtoupper($rzp_status);

    $raw = json_encode([
        'input'   => $input,
        'payment' => json_decode(json_encode($payment), true),
    ]);

    // 3. Idempotency check using BINARY
    $exists = db()->prepare("SELECT payment_id FROM payments WHERE BINARY gateway_capture_id = ? LIMIT 1");
    $exists->execute([$payment_id]);
    if ($exists->fetch()) {
        echo json_encode(['success' => true, 'message' => 'Already recorded']);
        exit;
    }

    // 4. Find CREATED row by order_id using BINARY
    $find = db()->prepare("SELECT payment_id FROM payments WHERE BINARY gateway_order_id = ? LIMIT 1");
    $find->execute([$order_id]);
    $row = $find->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        // Update by primary key — zero collation risk
        db()->prepare("
            UPDATE payments SET
                gateway_capture_id = ?,
                status             = ?,
                payer_email        = ?,
                payer_name         = ?,
                amount             = ?,
                currency           = ?,
                raw_response       = ?,
                paid_at            = IF(? = 'COMPLETED', NOW(), paid_at)
            WHERE payment_id = ?
        ")->execute([
            $payment_id, $db_status, $payer_email, $payer_name,
            $actual_amount, $actual_currency, $raw, $db_status,
            $row['payment_id'],
        ]);
    }

    // 5. Mark submission paid
    if ($db_status === 'COMPLETED') {
        db()->prepare("UPDATE submissions SET submission_status = 'submitted' WHERE BINARY tracking_code = ?")
            ->execute([$tracking_code]);
    }

    logPaymentError("Razorpay OK | order=$order_id | payment=$payment_id | status=$db_status", $tracking_code, 'info');
    echo json_encode(['success' => true, 'status' => $db_status]);

} catch (SignatureVerificationError $e) {
    logPaymentError('Razorpay signature FAIL: ' . $e->getMessage(), $tracking_code);
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Signature verification failed']);
} catch (Throwable $e) {
    logPaymentError('Razorpay capture error: ' . $e->getMessage(), $tracking_code);
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}