<?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;

$input         = json_decode(file_get_contents('php://input'), true) ?? [];
$tracking_code = trim($input['tracking_code'] ?? '');
$amount        = $input['amount']   ?? '';
$currency      = strtoupper($input['currency'] ?? 'INR');

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

try {
    // Get submission_id using BINARY — avoids collation mismatch on SELECT
    $stmt = db()->prepare("SELECT submission_id FROM submissions WHERE BINARY tracking_code = ?");
    $stmt->execute([$tracking_code]);
    $sub = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$sub) { throw new RuntimeException('Submission not found'); }
    $submission_id = (int)$sub['submission_id'];

    $api = new Api(RAZORPAY_KEY_ID, RAZORPAY_SECRET);

    // VND has no sub-unit; all others multiply by 100
    $smallest = ($currency === 'VND')
        ? (int)$amount
        : (int)(round((float)$amount, 2) * 100);

    $order = $api->order->create([
        'receipt'         => 'CGBL-' . $tracking_code,
        'amount'          => $smallest,
        'currency'        => $currency,
        'payment_capture' => 1,
    ]);

    // INSERT using submission_id (integer) to avoid collation issues on string columns
    db()->prepare("
        INSERT INTO payments
            (submission_id, tracking_code, invoice_no, gateway, gateway_order_id, status, amount, currency)
        VALUES (?, ?, ?, 'razorpay', ?, 'CREATED', ?, ?)
    ")->execute([
        $submission_id,
        $tracking_code,
        'CGBL-' . $tracking_code,
        $order['id'],
        $amount,
        $currency,
    ]);

    echo json_encode([
        'success'  => true,
        'order_id' => $order['id'],
        'amount'   => $smallest,
        'currency' => $currency,
    ]);

} catch (Throwable $e) {
    logPaymentError('Razorpay create: ' . $e->getMessage(), $tracking_code);
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}