<?php
ob_start();
session_start();
include('../includes/database.php');
include('../includes/config.php');

// Set timezone
date_default_timezone_set('Asia/Kolkata');

// Check login
if (!isset($_SESSION['phone'])) {
    header('Location: ../login.php');
    exit;
}

$mobileno = $_SESSION['phone'];
$userEmail = $_SESSION['email'] ?? '';
$minAmount = 100;  // Minimum ₹100
$maxAmount = 1000; // Maximum ₹1000

// TheMonkeyPay API Credentials (Same as other sites)
$API_TOKEN = "87714ec83f555cec2264651497d4902e";
$GATEWAY_URL = "themonkeypay.in";

// TheMonkeyPay API Helper
function callMonkeyPayAPI($endpoint, $data, $gateway_url) {
    $url = "https://" . $gateway_url . $endpoint;
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

// Check if TXN ID already exists (duplicate prevention)
function txn_exists($conn, $txn_id) {
    $txn_id = mysqli_real_escape_string($conn, $txn_id);
    $result = mysqli_query($conn, "SELECT id FROM wallet WHERE txn_id = '$txn_id' AND status = 'success' LIMIT 1");
    return ($result && mysqli_num_rows($result) > 0);
}

// Check if order already processed
function order_processed($conn, $order_id) {
    $order_id = mysqli_real_escape_string($conn, $order_id);
    $result = mysqli_query($conn, "SELECT id FROM wallet WHERE txn_id LIKE '%$order_id%' AND status = 'success' LIMIT 1");
    return ($result && mysqli_num_rows($result) > 0);
}

// AJAX: Cancel Order
if (isset($_POST['cancel_order']) && isset($_POST['order_id'])) {
    ob_clean();
    header('Content-Type: application/json');
    unset($_SESSION['mp_order']);
    echo json_encode(['status' => 'cancelled']);
    exit;
}

// AJAX: Check Payment Status
if (isset($_POST['check_status']) && isset($_POST['order_id'])) {
    ob_clean();
    header('Content-Type: application/json');
    header('Cache-Control: no-cache');
    
    $order_id = trim($_POST['order_id']);
    
    if (empty($order_id)) {
        echo json_encode(['status' => 'error', 'message' => 'Order ID missing']);
        exit;
    }
    
    // Check if already processed
    if (order_processed($ahk_conn, $order_id)) {
        unset($_SESSION['mp_order']);
        echo json_encode(['status' => 'already_done', 'message' => 'Already processed']);
        exit;
    }
    
    // Call TheMonkeyPay API
    $res = callMonkeyPayAPI("/api/check_order_sts", [
        "user_token" => $API_TOKEN,
        "order_id" => $order_id
    ], $GATEWAY_URL);
    
    if (!$res) {
        echo json_encode(['status' => 'pending', 'message' => 'Waiting...']);
        exit;
    }
    
    // Status can be at root level OR in result
    $txnStatus = $res['result']['status'] ?? $res['status'] ?? '';
    
    // Check if PENDING at root level
    if ($txnStatus == 'PENDING') {
        echo json_encode(['status' => 'pending', 'message' => $res['message'] ?? 'Waiting...']);
        exit;
    }
    
    if ($txnStatus == "TXN_SUCCESS" || $txnStatus == "SUCCESS" || $txnStatus == "COMPLETED") {
        $amt = floatval($res['result']['amount'] ?? 0);
        $utr = $res['result']['utr'] ?? $res['result']['bank_txn_id'] ?? '';
        $dt = date("Y-m-d H:i:s");
        
        // Check duplicate UTR
        if (!empty($utr) && txn_exists($ahk_conn, $utr)) {
            unset($_SESSION['mp_order']);
            echo json_encode(['status' => 'duplicate', 'message' => 'Payment already added']);
            exit;
        }
        
        // Check duplicate order
        if (order_processed($ahk_conn, $order_id)) {
            unset($_SESSION['mp_order']);
            echo json_encode(['status' => 'duplicate', 'message' => 'Order already processed']);
            exit;
        }
        
        $txnId = !empty($utr) ? $utr : $order_id;
        
        // Insert wallet record (matching existing table structure)
        $phone_esc = mysqli_real_escape_string($ahk_conn, $mobileno);
        $email_esc = mysqli_real_escape_string($ahk_conn, $userEmail);
        $txnId_esc = mysqli_real_escape_string($ahk_conn, $txnId);
        
        $insert = mysqli_query($ahk_conn, "INSERT INTO wallet (phone, txn_id, amount, email, status, txn_date) 
                                           VALUES ('$phone_esc', '$txnId_esc', '$amt', '$email_esc', 'success', '$dt')");
        
        if ($insert) {
            // Update user balance
            mysqli_query($ahk_conn, "UPDATE users SET balance = balance + $amt WHERE phone = '$phone_esc'");
            
            unset($_SESSION['mp_order']);
            
            echo json_encode([
                'status' => 'success',
                'message' => 'Payment Successful!',
                'amount' => $amt,
                'utr' => $txnId
            ]);
            exit;
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Database error: ' . mysqli_error($ahk_conn)]);
            exit;
        }
        
    } elseif ($txnStatus == "TXN_FAILURE" || $txnStatus == "FAILED") {
        unset($_SESSION['mp_order']);
        echo json_encode(['status' => 'failed', 'message' => 'Payment Failed']);
        exit;
    }
    
    echo json_encode(['status' => 'pending', 'message' => 'Waiting...']);
    exit;
}

// Include header
include('../template/ahkweb/header.php');

// Get user data
$udata = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM users WHERE phone = '$mobileno'"));

// Clear session on fresh page load
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    unset($_SESSION['mp_order']);
}

// Create Order
$qr_data = null;
$error_msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['amount']) && !isset($_POST['check_status']) && !isset($_POST['cancel_order'])) {
    $amount = intval($_POST['amount']);
    
    if ($amount < $minAmount) {
        $error_msg = "Minimum amount ₹$minAmount required!";
    } elseif ($amount > $maxAmount) {
        $error_msg = "Maximum amount ₹$maxAmount allowed!";
    } else {
        $order_id = "W" . time() . rand(1000, 9999);
        
        $res = callMonkeyPayAPI("/api/create-order", [
            "customer_mobile" => $mobileno,
            "user_token" => $API_TOKEN,
            "amount" => $amount,
            "order_id" => $order_id,
            "redirect_url" => "https://" . $_SERVER['SERVER_NAME'] . "/admin/wallet.php",
            "remark1" => $udata['name'] ?? 'User',
            "remark2" => "Wallet"
        ], $GATEWAY_URL);
        
        if (isset($res['status']) && $res['status'] == true) {
            $_SESSION['mp_order'] = [
                'id' => $res['result']['orderId'],
                'amount' => $amount,
                'qr' => $res['result']['qr_data']['qr'] ?? '',
                'created_at' => time()
            ];
            $qr_data = $_SESSION['mp_order'];
        } else {
            $error_msg = $res['message'] ?? 'Gateway error! Please try again.';
        }
    }
}

// Get wallet history
$phone_esc = mysqli_real_escape_string($ahk_conn, $mobileno);
$history = mysqli_query($ahk_conn, "SELECT * FROM wallet WHERE phone='$phone_esc' ORDER BY id DESC LIMIT 20");

// Get fresh balance
$bal = number_format($udata['balance'] ?? 0, 2);
?>

<style>
.wallet-card { border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.1); }
.balance-box { background: linear-gradient(135deg, #667eea, #764ba2); color: white; padding: 25px; border-radius: 15px; text-align: center; }
.balance-box h2 { font-size: 36px; margin: 10px 0; }
.btn-add { background: linear-gradient(135deg, #11998e, #38ef7d); border: none; padding: 12px 25px; font-size: 16px; }
.btn-add:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(17,153,142,0.4); }
.history-table th { background: #f8f9fa; font-size: 12px; }
.history-table td { font-size: 12px; vertical-align: middle; }
.quick-btn { padding: 8px 20px; margin: 3px; border-radius: 20px; }
.status-success { color: green; font-weight: bold; }
.status-pending { color: #e0a800; font-weight: bold; }
.status-failed, .status-rejected { color: red; font-weight: bold; }
</style>

<div class="page-wrapper">
    <div class="page-content">
        <!-- Breadcrumb -->
        <div class="page-breadcrumb d-flex align-items-center justify-content-between mb-4 p-3 bg-white rounded shadow-sm">
            <div class="d-flex align-items-center">
                <div class="breadcrumb-title pe-3">💰 Wallet</div>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0 ps-2">
                        <li class="breadcrumb-item active text-muted">Add Money & View Transactions</li>
                    </ol>
                </nav>
            </div>
            <div class="btn-group">
                <a href="wallet_history" class="btn btn-success btn-sm">
                    <i class="bi bi-list-ul me-1"></i> History
                </a>
                <a href="index.php" class="btn btn-outline-primary btn-sm">
                    <i class="bi bi-arrow-left me-1"></i> Back
                </a>
            </div>
        </div>

        <div class="row">
            <!-- Add Money Card -->
            <div class="col-lg-4 mb-4">
                <div class="card wallet-card">
                    <div class="card-header bg-primary text-white">
                        <h6 class="mb-0">💳 Add Money to Wallet</h6>
                    </div>
                    <div class="card-body">
                        <div class="balance-box mb-4">
                            <small>Current Balance</small>
                            <h2>₹<?= $bal ?></h2>
                        </div>

                        <?php if ($error_msg): ?>
                            <div class="alert alert-danger py-2"><?= htmlspecialchars($error_msg) ?></div>
                        <?php endif; ?>

                        <form method="POST" id="walletForm">
                            <div class="mb-3">
                                <label class="form-label">Amount (Min ₹<?= $minAmount ?> - Max ₹<?= $maxAmount ?>)</label>
                                <input type="number" name="amount" id="amtInput" class="form-control form-control-lg" placeholder="Enter Amount" min="<?= $minAmount ?>" max="<?= $maxAmount ?>" required>
                            </div>
                            
                            <div class="text-center mb-3">
                                <button type="button" class="btn btn-outline-primary quick-btn" onclick="setAmt(100)">₹100</button>
                                <button type="button" class="btn btn-outline-primary quick-btn" onclick="setAmt(500)">₹500</button>
                                <button type="button" class="btn btn-outline-primary quick-btn" onclick="setAmt(1000)">₹1000</button>
                            </div>
                            
                            <button type="submit" class="btn btn-success btn-add w-100">
                                <i class="bx bx-plus-circle me-2"></i> Add Money
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Transaction History -->
            <div class="col-lg-8 mb-4">
                <div class="card wallet-card">
                    <div class="card-header bg-white d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">📜 Transaction History</h6>
                        <small class="text-muted">Last 20 transactions</small>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover history-table mb-0">
                                <thead class="table-dark">
                                    <tr>
                                        <th>#</th>
                                        <th>TXN ID</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($history && mysqli_num_rows($history) > 0): ?>
                                        <?php $i = 1; while ($row = mysqli_fetch_assoc($history)): ?>
                                            <?php 
                                                $st = strtolower($row['status'] ?? '');
                                                if ($st == 'success') {
                                                    $stClass = 'status-success';
                                                    $stText = 'SUCCESS';
                                                } elseif ($st == 'pending') {
                                                    $stClass = 'status-pending';
                                                    $stText = 'PENDING';
                                                } else {
                                                    $stClass = 'status-failed';
                                                    $stText = 'FAILED';
                                                }
                                            ?>
                                            <tr>
                                                <td><?= $i++ ?></td>
                                                <td><code><?= htmlspecialchars(strtoupper($row['txn_id'] ?? '-')) ?></code></td>
                                                <td><strong class="text-success">₹<?= number_format($row['amount'] ?? 0, 2) ?></strong></td>
                                                <td><span class="<?= $stClass ?>"><?= $stText ?></span></td>
                                                <td><?= $row['txn_date'] ? date('d M, h:i A', strtotime($row['txn_date'])) : '-' ?></td>
                                            </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="5" class="text-center py-4 text-muted">
                                                <i class="bx bx-inbox bx-lg d-block mb-2"></i>
                                                No transactions yet
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php if ($qr_data): ?>
<!-- QR Modal -->
<div class="modal fade show" id="qrModal" tabindex="-1" style="display: block; background: rgba(0,0,0,0.8);">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content" style="border-radius: 15px;">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">💳 Scan & Pay</h5>
                <button type="button" class="btn-close btn-close-white" onclick="closeModal()"></button>
            </div>
            <div class="modal-body text-center py-4">
                <h2 class="text-success mb-3">₹<?= $qr_data['amount'] ?></h2>
                
                <?php if (!empty($qr_data['qr'])): ?>
                    <div class="mb-3">
                        <img src="data:image/png;base64,<?= $qr_data['qr'] ?>" style="width: 220px; height: 220px; border: 3px solid #eee; border-radius: 15px;" alt="QR Code">
                    </div>
                <?php endif; ?>
                
                <p class="text-muted mb-2">Scan with any UPI app (GPay, PhonePe, Paytm)</p>
                
                <div id="payStatus" class="p-3 bg-light rounded">
                    <div class="spinner-border spinner-border-sm text-primary me-2"></div>
                    <span>Waiting for payment...</span>
                </div>
            </div>
            <div class="modal-footer justify-content-center">
                <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
            </div>
        </div>
    </div>
</div>

<script>
(function() {
    const orderId = "<?= $qr_data['id'] ?>";
    const statusEl = document.getElementById('payStatus');
    let checkCount = 0;
    const maxChecks = 120;
    let isChecking = false;
    let checkInterval;
    let paymentCompleted = false;
    
    async function checkPayment() {
        if (isChecking || paymentCompleted) return;
        isChecking = true;
        checkCount++;
        
        try {
            const formData = new FormData();
            formData.append('check_status', '1');
            formData.append('order_id', orderId);
            
            const response = await fetch(window.location.pathname, {
                method: 'POST',
                body: formData,
                cache: 'no-store'
            });
            
            const text = await response.text();
            let data;
            try { data = JSON.parse(text); } catch(e) { isChecking = false; return; }
            
            if (data.status === 'success') {
                paymentCompleted = true;
                clearInterval(checkInterval);
                statusEl.className = 'p-3 bg-success text-white rounded';
                statusEl.innerHTML = `
                    <div style="font-size: 50px;">✅</div>
                    <div style="font-size: 20px; font-weight: bold;">Payment Successful!</div>
                    <div style="font-size: 28px; margin-top: 5px;">₹${data.amount}</div>
                    <div style="font-size: 12px;">UTR: ${data.utr}</div>
                `;
                setTimeout(() => { window.location.href = 'wallet.php?success=1'; }, 2000);
                return;
            } else if (data.status === 'duplicate' || data.status === 'already_done') {
                paymentCompleted = true;
                clearInterval(checkInterval);
                statusEl.className = 'p-3 bg-warning rounded';
                statusEl.innerHTML = `<div style="font-size: 30px;">⚠️</div><div>${data.message}</div>`;
                setTimeout(() => { window.location.href = 'wallet.php'; }, 2000);
                return;
            } else if (data.status === 'failed') {
                paymentCompleted = true;
                clearInterval(checkInterval);
                statusEl.className = 'p-3 bg-danger text-white rounded';
                statusEl.innerHTML = `<div style="font-size: 50px;">❌</div><div>Payment Failed!</div>`;
                setTimeout(() => { window.location.href = 'wallet.php'; }, 2500);
                return;
            } else {
                statusEl.innerHTML = `<div class="spinner-border spinner-border-sm text-primary me-2"></div><span>Checking... (${checkCount})</span>`;
            }
            
            if (checkCount >= maxChecks) {
                clearInterval(checkInterval);
                statusEl.className = 'p-3 bg-warning rounded';
                statusEl.innerHTML = `<div>⚠️ Timeout</div><div style="font-size: 12px;">Check transaction history</div>`;
            }
        } catch (error) {
            statusEl.innerHTML = `<div class="spinner-border spinner-border-sm text-primary me-2"></div><span>Retrying...</span>`;
        }
        isChecking = false;
    }
    
    checkPayment();
    checkInterval = setInterval(checkPayment, 3000);
    
    window.closeModal = function() {
        clearInterval(checkInterval);
        if (!paymentCompleted) {
            const formData = new FormData();
            formData.append('cancel_order', '1');
            formData.append('order_id', orderId);
            fetch(window.location.pathname, { method: 'POST', body: formData });
        }
        document.getElementById('qrModal').style.display = 'none';
        window.location.href = 'wallet.php';
    };
})();
</script>
<?php endif; ?>

<?php if (isset($_GET['success'])): ?>
<script>
    Swal.fire({
        icon: 'success',
        title: 'Wallet Recharged! 🎉',
        text: 'Amount added successfully to your wallet.',
        timer: 2500,
        showConfirmButton: false
    });
</script>
<?php endif; ?>

<script>
function setAmt(a) { document.getElementById('amtInput').value = a; }
</script>

<?php include('footer.php'); ?>