<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');

// Debugging on rakhein taaki koi error ho to dikh jaye
error_reporting(E_ALL);
ini_set('display_errors', 1);

/* ==========================================
   1. AJAX BACKEND (Handle "Get QR" Request)
   ========================================== */
if (isset($_POST['action']) && $_POST['action'] == 'get_qr') {
    header('Content-Type: application/json');
    
    $amount = mysqli_real_escape_string($tng_conn, $_POST['amount']);
    $phone = $udata['phone'];

    if (is_numeric($amount) && $amount >= 100) {
        $order_id = "TXN" . time() . rand(100, 999);
        
        // 1. Insert into database
        $ins_query = "INSERT INTO `wallet` (`phone`, `amount`, `order_id`, `status`, `txn_date`, `description`) 
                      VALUES ('$phone', '$amount', '$order_id', 'pending', NOW(), 'Recharge via SmartUPI')";
        
        if (mysqli_query($tng_conn, $ins_query)) {
            
            // 2. Prepare API Call
            $post_data = array(
                'customer_mobile' => $phone,
                'user_token'      => 'cb2cb0beedd8b9a4873bf19c695aa5b9', // Aapka Direct Token
                'amount'          => $amount,
                'order_id'        => $order_id,
                'redirect_url'    => "https://" . $_SERVER['SERVER_NAME'] . "/wallet.php",
                'remark1'         => $phone
            );

            // Aapka Direct Gateway URL
            $api_url = "https://pg.world365.in/payment/create-order";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $api_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // SSL error bypass
            $response = curl_exec($ch);
            curl_close($ch);

            $resArray = json_decode($response, true);

            if (isset($resArray['result']['payment_url'])) {
                $payment_url = $resArray['result']['payment_url'];
                
                // QR Data nikalne ke liye curl use karein (file_get_contents se behtar hai)
                $ch2 = curl_init();
                curl_setopt($ch2, CURLOPT_URL, $payment_url);
                curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
                $qr_resp = curl_exec($ch2);
                curl_close($ch2);
                
                $qrData = json_decode($qr_resp, true);

                if (isset($qrData['qrimage'])) {
                    echo json_encode([
                        'status'      => 'success',
                        'qrImg'       => $qrData['qrimage'],
                        'orderId'     => $qrData['orderUnicID'],
                        'amount'      => $amount,
                        'paymentUrl'  => $payment_url,
                        'redirectUrl' => $qrData['payment_url']
                    ]);
                } else {
                    echo json_encode(['status' => 'error', 'message' => 'QR Generation Failed']);
                }
            } else {
                echo json_encode(['status' => 'error', 'message' => $resArray['message'] ?? 'Gateway Timeout']);
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => 'DB Error: ' . mysqli_error($tng_conn)]);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Minimum amount ₹100 required']);
    }
    exit;
}

/* ==========================================
   2. FRONTEND UI
   ========================================== */
$phone = $udata['phone'];
$balance = number_format($udata['balance'] ?? 0, 2);
$res = mysqli_query($tng_conn, "SELECT * FROM wallet WHERE phone='$phone' ORDER BY id DESC LIMIT 10");
?>

<div class="page-wrapper">
    <div class="page-content">
        <div class="row">
            <div class="col-md-5">
                <div class="card shadow-sm border-0" style="background: linear-gradient(135deg,#667eea,#764ba2); color:white; border-radius:15px;">
                    <div class="card-body p-4">
                        <h5 class="mb-1">Available Balance</h5>
                        <h2 class="display-5 fw-bold">₹<?= $balance ?></h2>
                        <p class="mb-0 opacity-75">Linked to: <?= $phone ?></p>
                    </div>
                </div>
            </div>
            
            <div class="col-md-7">
                <div class="card shadow-sm border-0 p-2" style="border-radius:15px;">
                    <div class="card-body">
                        <h5>Add Money to Wallet</h5>
                        <form id="payForm">
                            <div class="input-group input-group-lg mt-3">
                                <span class="input-group-text bg-light border-0">₹</span>
                                <input type="number" id="amt" class="form-control bg-light border-0" placeholder="100" min="100" required>
                                <button type="submit" class="btn btn-primary px-4">Generate QR</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mt-4 shadow-sm border-0" style="border-radius:15px;">
            <div class="card-body">
                <h6 class="mb-3 text-uppercase fw-bold text-muted">Recent Transactions</h6>
                <div class="table-responsive">
                    <table class="table align-middle">
                        <thead class="table-light">
                            <tr><th>Order ID</th><th>Amount</th><th>Status</th><th>Date</th></tr>
                        </thead>
                        <tbody>
                            <?php while($row = mysqli_fetch_assoc($res)): ?>
                            <tr>
                                <td><small class="text-muted"><?= $row['order_id'] ?></small></td>
                                <td class="fw-bold">₹<?= number_format($row['amount'],2) ?></td>
                                <td><span class="badge rounded-pill <?= $row['status']=='success'?'bg-success':'bg-warning text-dark' ?>"><?= strtoupper($row['status']) ?></span></td>
                                <td><small><?= date('d M Y, h:i A', strtotime($row['txn_date'])) ?></small></td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(document).ready(function() {
    $('#payForm').on('submit', function(e) {
        e.preventDefault();
        const amount = $('#amt').val();

        Swal.fire({
            title: 'Please Wait',
            text: 'Connecting to Secure Server...',
            allowOutsideClick: false,
            didOpen: () => { Swal.showLoading(); }
        });

        $.ajax({
            url: 'wallet.php',
            type: 'POST',
            data: { action: 'get_qr', amount: amount },
            dataType: 'json',
            success: function(res) {
                if(res.status === 'success') {
                    showPaymentModal(res);
                } else {
                    Swal.fire("Gateway Error", res.message, "error");
                }
            },
            error: function(xhr) {
                console.log(xhr.responseText); // Log actual error to console
                Swal.fire("Server Error", "Could not connect to API. Check console for logs.", "error");
            }
        });
    });
});

function showPaymentModal(data) {
    const isUTR = data.paymentUrl.includes("/payment3/");
    
    let html = `
        <div class="text-center">
            <img src="${data.qrImg}" style="max-width:220px; border:8px solid #f8f9fa; border-radius:15px;" class="mb-3">
            <p class="text-muted mb-3">Scan & Pay using any UPI App</p>
            
            <div id="utrBox" style="display:${isUTR ? 'block' : 'none'}; background:#f4f7ff; padding:15px; border-radius:10px;">
                <input type="text" id="utr_val" class="form-control text-center mb-2" placeholder="Enter 12-Digit UTR" maxlength="12">
                <button id="btnV" class="btn btn-primary w-100">Verify Payment</button>
            </div>

            <div id="successBox" style="display:none;">
                <div class="text-success mb-2"><i class="fa fa-check-circle fa-3x"></i></div>
                <h5 class="text-success">Payment Success!</h5>
            </div>

            <div id="pStatus" class="mt-3 fw-bold text-primary">${isUTR ? 'Action Required: Enter UTR' : '⏳ Waiting for payment...'}</div>
        </div>
    `;

    Swal.fire({
        title: `Amount: ₹${data.amount}`,
        html: html,
        showConfirmButton: false,
        allowOutsideClick: false,
        didOpen: () => {
            if (isUTR) {
                document.getElementById('btnV').onclick = async () => {
                    const utr = document.getElementById('utr_val').value;
                    if(utr.length < 12) return Swal.showValidationMessage('Enter valid 12-digit UTR');
                    
                    document.getElementById('pStatus').innerText = "Verifying...";
                    const v = await fetch(`verify_utr_proxy.php?utr=${utr}&TransactionId=${data.orderId}`).then(r => r.json());
                    
                    if(v.status?.toUpperCase() === "SUCCESS") {
                        handleSuccess(data);
                    } else {
                        document.getElementById('pStatus').innerText = "Verification Failed!";
                    }
                };
            } else {
                let check = setInterval(async () => {
                    const s = await fetch(`check_status_proxy.php?order=${data.orderId}`).then(r => r.json());
                    if(s.success && s.status?.toUpperCase() === "SUCCESS") {
                        clearInterval(check);
                        handleSuccess(data);
                    }
                }, 4000);
                Swal.getPopup().addEventListener('close', () => clearInterval(check));
            }
        }
    });
}

function handleSuccess(data) {
    document.getElementById('utrBox').style.display = 'none';
    document.getElementById('qrContainer')?.style.setProperty('display', 'none');
    document.getElementById('successBox').style.display = 'block';
    document.getElementById('pStatus').innerText = "Updating Balance...";
    
    fetch("wallet-cron.php?orderid=" + data.orderId).finally(() => {
        setTimeout(() => window.location.reload(), 2000);
    });
}
</script>

<?php include('../template/tngweb/footer.php'); ?>