<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_user.php';

apply_cors();
$authUser = require_user();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_error('Method not allowed.', 405);
}

$input = get_json_input();
require_fields($input, ['plan_id']);

$pdo = getDbConnection();

// 1. Fetch plan securely from DB — never trust a client-supplied amount.
$planStmt = $pdo->prepare('SELECT * FROM subscriptions WHERE id = :id AND is_active = 1');
$planStmt->execute([':id' => (int) $input['plan_id']]);
$plan = $planStmt->fetch();
if (!$plan) {
    send_error('Selected plan not found or inactive.', 404);
}

$amount = (float) $plan['price'];
$validityDays = (int) $plan['validity_days'];

// 2. Fetch the currently active gateway.
$gwStmt = $pdo->prepare('SELECT * FROM payment_gateways WHERE is_active = 1 LIMIT 1');
$gwStmt->execute();
$gateway = $gwStmt->fetch();
if (!$gateway) {
    send_error('No payment gateway is currently active. Please contact support.', 503);
}

$localOrderId = 'ORD-' . strtoupper(bin2hex(random_bytes(8)));

// 3. Create a PENDING transaction row up front (idempotency anchor).
$insert = $pdo->prepare(
    'INSERT INTO payment_transactions (user_email, plan_id, plan_name, amount, gateway, order_id,
                                        status, validity_days_added)
     VALUES (:email, :plan_id, :plan_name, :amount, :gateway, :order_id, "PENDING", :validity)'
);
$insert->execute([
    ':email'    => $authUser['email'],
    ':plan_id'  => $plan['id'],
    ':plan_name' => $plan['plan_name'],
    ':amount'   => $amount,
    ':gateway'  => $gateway['gateway_name'],
    ':order_id' => $localOrderId,
    ':validity' => $validityDays,
]);
$txnId = (int) $pdo->lastInsertId();

// 4. Gateway-specific order creation.
if ($gateway['gateway_name'] === 'RAZORPAY') {
    $ch = curl_init('https://api.razorpay.com/v1/orders');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_USERPWD => $gateway['key_id'] . ':' . $gateway['key_secret'],
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT => 15,
        CURLOPT_POSTFIELDS => json_encode([
            'amount' => (int) round($amount * 100), // paise
            'currency' => 'INR',
            'receipt' => $localOrderId,
        ]),
    ]);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $rzpOrder = json_decode($response ?: '', true);

    if ($httpCode !== 200 || empty($rzpOrder['id'])) {
        send_error('Failed to create Razorpay order. Please try again.', 502);
    }

    $upd = $pdo->prepare('UPDATE payment_transactions SET payment_id = :rzp_order_id WHERE id = :id');
    $upd->execute([':rzp_order_id' => $rzpOrder['id'], ':id' => $txnId]);

    send_success([
        'gateway' => 'RAZORPAY',
        'local_order_id' => $localOrderId,
        'razorpay_order_id' => $rzpOrder['id'],
        'razorpay_key_id' => $gateway['key_id'], // publishable key, safe to send
        'amount' => $amount,
        'currency' => 'INR',
    ]);
}

if ($gateway['gateway_name'] === 'MANUAL_UPI') {
    send_success([
        'gateway' => 'MANUAL_UPI',
        'local_order_id' => $localOrderId,
        'amount' => $amount,
        'upi_id' => $gateway['upi_id'],
        'upi_name' => $gateway['upi_name'],
        'qr_image_url' => $gateway['qr_image_url'],
        'instructions' => $gateway['instructions'],
    ]);
}

if ($gateway['gateway_name'] === 'PHONEPE') {
    send_success([
        'gateway' => 'PHONEPE',
        'local_order_id' => $localOrderId,
        'amount' => $amount,
        'merchant_id' => $gateway['merchant_id'],
        'note' => 'Complete payment via PhonePe app using the merchant details, then submit for verification.',
    ]);
}

send_error('Unsupported payment gateway.', 500);
