<?php
session_start();

// 1. Database Connection Fix 
if (file_exists('includes/database.php')) {
    include('includes/database.php');
} elseif (file_exists('../includes/database.php')) {
    include('../includes/database.php');
} else {
    die("Error: database.php not found in includes folder!");
}

// Variable Mapping
if (isset($tng_conn)) {
    $db = $tng_conn;
} elseif (isset($ahk_conn)) {
    $db = $ahk_conn;
} elseif (isset($conn)) {
    $db = $conn;
} else {
    die("Error: Database connection variable not found!");
}

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

$user_phone = $_SESSION['phone'];
$show_success = false;
$error_min = false;
$submitted_amount = "";
$submitted_utr = "";

// 2. ADMIN SETTINGS
$admin_whatsapp = "919835672647"; 
$upi_id = "9835672647kotak811@rbl"; 
$brand_name = "EMITRA SOLUTION";

// 3. Table Auto-Create
mysqli_query($db, "CREATE TABLE IF NOT EXISTS `wallet_requests` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `phone` varchar(50) NOT NULL,
  `amount` varchar(50) NOT NULL,
  `utr_number` varchar(100) NOT NULL,
  `status` varchar(20) DEFAULT 'pending',
  `date` timestamp DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;");

// 4. Submit Logic
if(isset($_POST['submit_payment'])){
    $amount = mysqli_real_escape_string($db, $_POST['pay_amount']);
    
    if($amount < 100){
        $error_min = true;
    } else {
        $utr = mysqli_real_escape_string($db, $_POST['utr_code']);
        $submitted_amount = $amount;
        $submitted_utr = $utr;

        $sql = "INSERT INTO wallet_requests (phone, amount, utr_number, status) VALUES ('$user_phone', '$amount', '$utr', 'pending')";
        if(mysqli_query($db, $sql)) {
            $show_success = true;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Money | <?php echo $brand_name; ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        :root { --primary: #00d2ff; --secondary: #9200ff; --bg: #050811; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Plus Jakarta Sans', sans-serif; }
        body { background: var(--bg); color: #fff; display: flex; justify-content: center; align-items: center; min-height: 100vh; overflow-x: hidden; padding: 20px; }
        .bg-glow { position: fixed; inset: 0; z-index: -1; background: radial-gradient(circle at center, #102a43 0%, #050811 100%); }
        .card { width: 100%; max-width: 420px; background: rgba(15, 23, 42, 0.8); backdrop-filter: blur(20px); padding: 40px 30px; border-radius: 30px; border: 1px solid rgba(255, 255, 255, 0.1); text-align: center; box-shadow: 0 50px 100px rgba(0,0,0,0.5); position: relative; }
        .qr-wrapper { background: #fff; padding: 15px; border-radius: 20px; margin: 25px auto; width: 190px; height: 190px; display: flex; align-items: center; justify-content: center; border: 4px solid var(--primary); box-shadow: 0 0 20px rgba(0, 210, 255, 0.2); }
        input { width: 100%; padding: 15px; margin: 12px 0; background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1); color: #fff; border-radius: 15px; text-align: center; outline: none; font-size: 16px; transition: 0.3s; }
        input:focus { border-color: var(--primary); background: rgba(255, 255, 255, 0.1); }
        .btn-neon-container { position: relative; width: 100%; height: 60px; border-radius: 15px; overflow: hidden; display: flex; align-items: center; justify-content: center; margin-top: 20px; }
        .btn-neon-container::before { content: ''; position: absolute; width: 150%; height: 400%; background: conic-gradient(transparent, transparent, transparent, var(--primary), var(--secondary), var(--primary)); animation: rotate 4s linear infinite; }
        @keyframes rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        .inner-btn { position: absolute; inset: 2px; background: #0f172a; border: none; border-radius: 13px; color: #fff; font-weight: 800; font-size: 15px; letter-spacing: 1px; cursor: pointer; z-index: 5; transition: 0.3s; }
        .inner-btn:hover { background: transparent; letter-spacing: 2px; }
        .note-box { text-align: left; background: rgba(0, 210, 255, 0.08); padding: 15px; border-radius: 15px; margin: 20px 0; border-left: 4px solid var(--primary); }
        .note-box p { font-size: 13px; margin-bottom: 5px; color: #cbd5e1; }
    </style>
</head>
<body>
    <div class="bg-glow"></div>
    <div class="card">
        <h2 style="font-family:'Orbitron'; color:var(--primary); font-size: 24px;">RECHARGE WALLET</h2>
        <p style="font-size: 13px; color: #64748b; margin-top: 5px;">Secure UPI Payment Gateway</p>

        <form method="POST">
            <input type="number" name="pay_amount" placeholder="Min. ₹100 Required" required min="100" oninput="genQR(this.value)">
            
            <div class="qr-wrapper" id="qr_area">
                <div style="color:#e74c3c; font-size:12px; font-weight:bold;">MINIMUM ₹100<br>REQUIRED FOR QR</div>
            </div>

            <div class="note-box">
                <p>✅ Minimum Add Money: ₹100</p>
                <p>✅ Copy **12 Digit UTR / Ref No.**</p>
                <p>✅ Submit & Send Screenshot to WhatsApp</p>
            </div>

            <input type="text" name="utr_code" placeholder="Enter 12 Digit UTR Number" required maxlength="12" minlength="12">
            
            <div class="btn-neon-container">
                <button type="submit" name="submit_payment" class="inner-btn">SUBMIT PAYMENT</button>
            </div>
        </form>
    </div>
 
    <script>
    function genQR(amt) {
        let area = document.getElementById('qr_area');
        // Check if amount is 100 or more
        if(amt >= 100) {
            let upi = "upi://pay?pa=<?php echo $upi_id; ?>&pn=<?php echo $brand_name; ?>&am=" + amt + "&cu=INR";
            let qr_url = "https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=" + encodeURIComponent(upi);
            area.innerHTML = '<img src="'+qr_url+'" style="width:100%; border-radius:10px;">';
        } else {
            // QR hides and shows error message if less than 499
            area.innerHTML = '<div style="color:#e74c3c; font-size:12px; font-weight:bold;">MINIMUM ₹100<br>REQUIRED FOR QR</div>';
        }
    }

    <?php if($error_min){ ?>
        Swal.fire({
            icon: 'error',
            title: 'Minimum ₹100 Required',
            text: 'You cannot add less than ₹100 to wallet.',
            background: '#0f172a',
            color: '#fff'
        });
    <?php } ?>

    <?php if($show_success){ 
        $msg = "Hi Admin, I added money to my wallet.%0A%0A*Payment Details:*%0AMobile: $user_phone%0AAmount: ₹$submitted_amount%0AUTR: $submitted_utr%0A%0A_Attached is my payment screenshot._";
        $link = "https://wa.me/$admin_whatsapp?text=$msg";
    ?>
        Swal.fire({
            title: '<strong>Payment Submitted!</strong>',
            icon: 'success',
            html: 'Your request is pending for verification.<br><br><b>Please send the Payment Screenshot on WhatsApp for instant activation.</b>',
            background: '#0f172a',
            color: '#fff',
            showCloseButton: false,
            confirmButtonText: '<i class="bi bi-whatsapp"></i> SEND SCREENSHOT',
            confirmButtonColor: '#25D366',
            allowOutsideClick: false
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = "<?php echo $link; ?>";
            }
        });
    <?php } ?>
    </script>
</body>
</html>