<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(0);

require_once 'wallet_common.php';

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        walletJson(['success' => false, 'message' => 'Method not allowed. Use POST.'], 405);
    }

    $pdo = getDBConnection();
    walletEnsureSchema($pdo);
    $input = walletReadInput();
    $action = $input['action'] ?? 'create_order';

    if ($action === 'create_order') {
        $userId = (int)($input['user_id'] ?? 0);
        $amount = (float)($input['amount'] ?? 0);
        if ($userId <= 0 || $amount <= 0) {
            walletJson(['success' => false, 'message' => 'Valid user_id and amount are required'], 400);
        }

        $merchantOrderId = 'WALLET_' . $userId . '_' . time() . '_' . random_int(1000, 9999);
        $phonePe = walletCreatePhonePeSdkOrder($amount, $userId, $merchantOrderId);
        $currentBalance = walletCurrentBalance($pdo, $userId);

        $stmt = $pdo->prepare("
            INSERT INTO wallet_transactions (
                user_id, type, amount, description, payment_method, transaction_time,
                balance_after, transaction_id, reference_id, status, created_at
            ) VALUES (?, 'credit', ?, 'Wallet Recharge Pending PhonePe', 'PhonePe', NOW(), ?, ?, ?, 'pending', NOW())
        ");
        $stmt->execute([$userId, $amount, $currentBalance, $merchantOrderId, $phonePe['order_id']]);

        walletJson([
            'success' => true,
            'message' => 'PhonePe order created',
            'merchant_order_id' => $merchantOrderId,
            'phonepe_order_id' => $phonePe['order_id'],
            'amount' => $amount,
            'amount_paise' => (int)round($amount * 100),
            'merchant_id' => PhonePeConfig::getMerchantId(),
            'environment' => walletPhonePeEnvironment(),
            'payment_request' => $phonePe['payment_request']
        ]);
    }

    if ($action === 'verify_payment') {
        $merchantOrderId = trim((string)($input['merchant_order_id'] ?? ''));
        if ($merchantOrderId === '') {
            walletJson(['success' => false, 'message' => 'merchant_order_id is required'], 400);
        }

        $status = walletCheckPhonePeOrderStatus($merchantOrderId);
        $phonePeState = strtoupper($status['state']);
        $successStates = ['COMPLETED', 'SUCCESS', 'PAYMENT_SUCCESS'];
        $failedStates = ['FAILED', 'CANCELLED', 'EXPIRED', 'PAYMENT_ERROR'];

        $pdo->beginTransaction();
        try {
            $stmt = $pdo->prepare("
                SELECT *
                FROM wallet_transactions
                WHERE transaction_id = ?
                ORDER BY id DESC
                LIMIT 1
                FOR UPDATE
            ");
            $stmt->execute([$merchantOrderId]);
            $transaction = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$transaction) {
                throw new Exception('Wallet recharge transaction not found');
            }

            $userId = (int)$transaction['user_id'];
            if ($transaction['status'] === 'completed') {
                $balance = walletCurrentBalance($pdo, $userId);
                walletSyncUserBalance($pdo, $userId, $balance);
                $pdo->commit();
                walletJson([
                    'success' => true,
                    'message' => 'Wallet already credited',
                    'status' => 'completed',
                    'new_balance' => $balance,
                    'phonepe_state' => $phonePeState
                ]);
            }

            if (in_array($phonePeState, $successStates, true)) {
                $amount = (float)$transaction['amount'];
                $newBalance = walletCurrentBalance($pdo, $userId) + $amount;
                $update = $pdo->prepare("
                    UPDATE wallet_transactions
                    SET status = 'completed',
                        description = 'Wallet Recharge via PhonePe',
                        balance_after = ?,
                        payment_method = 'PhonePe',
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $update->execute([$newBalance, (int)$transaction['id']]);
                walletSyncUserBalance($pdo, $userId, $newBalance);
                $pdo->commit();

                walletJson([
                    'success' => true,
                    'message' => 'Wallet credited successfully',
                    'status' => 'completed',
                    'phonepe_state' => $phonePeState,
                    'amount' => $amount,
                    'new_balance' => $newBalance,
                    'transaction_id' => $merchantOrderId
                ]);
            }

            if (in_array($phonePeState, $failedStates, true)) {
                $update = $pdo->prepare("
                    UPDATE wallet_transactions
                    SET status = 'failed', description = 'Wallet Recharge PhonePe Failed', updated_at = NOW()
                    WHERE id = ?
                ");
                $update->execute([(int)$transaction['id']]);
                $pdo->commit();
                walletJson([
                    'success' => false,
                    'message' => 'PhonePe payment failed',
                    'status' => 'failed',
                    'phonepe_state' => $phonePeState
                ], 400);
            }

            $pdo->commit();
            walletJson([
                'success' => false,
                'message' => 'PhonePe payment is pending',
                'status' => 'pending',
                'phonepe_state' => $phonePeState
            ], 202);
        } catch (Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            throw $e;
        }
    }

    walletJson(['success' => false, 'message' => 'Unknown action'], 400);
} catch (Exception $e) {
    walletJson(['success' => false, 'message' => $e->getMessage()], 500);
}
?>
