<?php
session_start();
if ($_SESSION['unohs'] == null) {
    header("location:index.php?msg=unauthorized");
    exit();
}
include("conn.php");

// =================================================================
//  FULL BACKEND LOGIC (Wallet, Referral, Bonus Update)
// =================================================================

// --- 1. APPROVE LOGIC ---
if(isset($_POST['app'])){
    
    $uid = $_POST['uid']; // User ID
    $deposit = $_POST['amount'];
    $depositdup = $deposit;
    $sid = $_POST['sid']; // Transaction ID
    
    // Form se naya data jo chahiye
    $ref_num = isset($_POST['ref_num']) ? $_POST['ref_num'] : ''; 
    $dt = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d H:i:s');

    date_default_timezone_set('Asia/Kolkata');
    
    // --- A. REFERRAL LOGIC START ---
    // User ka code nikalo
    $self = mysqli_query($conn , "SELECT code FROM shonu_subjects WHERE id = '".$uid."'");
    $selfArray = mysqli_fetch_array($self);
    
    // Referrer dhundo (jisne invite kiya)
    $ref = mysqli_query($conn , "SELECT id FROM shonu_subjects WHERE owncode = '".$selfArray['code']."'");
    
    $refid = 0; // Default
    if(mysqli_num_rows($ref) > 0){
        $refArray = mysqli_fetch_array($ref);
        $refid = $refArray['id'];
    }
    
    // Bonus Calculation (aapke code ke hisaab se abhi 0 hai)
    $refbn = 0;
    if($depositdup>='500' && $depositdup<'1000'){ $refbn = 0; }
    else if($depositdup>='1000' && $depositdup<'3000'){ $refbn = 0; }
    else if($depositdup>='3000' && $depositdup<'4000'){ $refbn = 0; }
    else if($depositdup>='4000' && $depositdup<'5000'){ $refbn = 0; }
    else if($depositdup>='5000' && $depositdup<'10000'){ $refbn = 0; }
    else if($depositdup>='10000' && $depositdup<'50000'){ $refbn = 0; }
    else if($depositdup>='50000' && $depositdup<'100000'){ $refbn = 0; }
    else if($depositdup>='100000'){ $refbn = 0; }
    else { $refbn = 0; }
    
    $refbnthr = 0;
    
    // Referrer Wallet Balance Nikalo
    $refwalB = 0;
    if($refid != 0){
        $refwal = mysqli_query($conn , "SELECT motta FROM shonu_kaichila WHERE balakedara = '".$refid."'");
        if(mysqli_num_rows($refwal) > 0){
            $refwalA = mysqli_fetch_array($refwal);
            $refwalB = $refwalA['motta'];
        }
    }
    
    $refwalF = intval($refwalB) + intval($refbn);
    $refwalFthr = intval($refwalB) + intval($refbnthr);
    // --- REFERRAL LOGIC END ---

    // --- B. FIRST RECHARGE CHECK ---
    $up2 = mysqli_query($conn , "SELECT shonu FROM thevani WHERE balakedara = '".$uid."' && sthiti = '1'");
    $up2row = mysqli_num_rows($up2);
    
    $bn = '0'; // Bonus default 0

    // --- C. MAIN WALLET UPDATE (User) ---
    $up = mysqli_query($conn , "SELECT motta FROM shonu_kaichila WHERE balakedara = '".$uid."'");
    $rup = mysqli_fetch_array($up);
          
    // Naya Balance = Purana + Deposit + Bonus
    $addmoney = intval($rup['motta']) + intval($deposit) + intval($bn);

    // Update User Wallet
    $wal = mysqli_query($conn, "UPDATE shonu_kaichila SET motta = '".$addmoney."' WHERE balakedara = '".$uid."'");
    
    if($wal){
        // 1. Transaction Status Update karo (Success = 1)
        // Note: Main date aur ref_num check nahi laga raha hu taaki error na aaye, seedha ID se update kar raha hu
        $succes = mysqli_query($conn, "UPDATE thevani SET sthiti = '1' WHERE shonu = '".$sid."'");
        
        // 2. Referrer Wallet Update karo (Agar koi referrer hai)
        if($refid != 0){
            if($up2row == 0){ // First Recharge
                mysqli_query($conn, "UPDATE shonu_kaichila SET motta = '".$refwalF."' WHERE balakedara = '".$refid."'");
            }
            else if($up2row == 2){ // Example Condition
                mysqli_query($conn, "UPDATE shonu_kaichila SET motta = '".$refwalFthr."' WHERE balakedara = '".$refid."'");
            } 
        }                           
        
        echo "1~".$sid; // Success Response for JS
    } else {
        echo "2~Error"; // Error Response
    }
    exit(); // PHP yahin rok do
}

// --- 2. REJECT LOGIC ---
if(isset($_POST['rej'])){
    
    $sid = $_POST['sid'];
    $uid = $_POST['uid'];
    $deposit = $_POST['amount'];
    
    // Status 2 = Rejected
    $reject = mysqli_query($conn, "UPDATE thevani SET sthiti = '2' WHERE shonu = '".$sid."'");
    
    if($reject){
        echo "1~".$sid;
    }
    else{
        echo "2~Error";
    }
    exit();
}

// --- 3. CLEAR HISTORY LOGIC ---
if (isset($_POST['clear_history'])) {
    $del_sql = "DELETE FROM thevani WHERE sthiti = '1' OR sthiti = '2'"; 
    if (mysqli_query($conn, $del_sql)) {
        echo '<script>alert("✅ History Cleared Successfully!"); window.location.href="deposit_update.php";</script>';
    }
}

// --- 4. FILTER LOGIC ---
$filter_query = "SELECT * FROM thevani WHERE 1"; 
$total_amount = 0;

if (isset($_POST['apply_filter'])) {
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $status = $_POST['status_filter'];

    if (!empty($start_date) && !empty($end_date)) {
        $filter_query .= " AND dinankavannuracisi BETWEEN '$start_date' AND '$end_date'";
    }
    if ($status != 'all') {
        $filter_query .= " AND sthiti = '$status'";
    }
}
$filter_query .= " ORDER BY shonu DESC";
$filter_res = mysqli_query($conn, $filter_query);

while ($row = mysqli_fetch_assoc($filter_res)) {
    $total_amount += $row['motta'];
}
mysqli_data_seek($filter_res, 0); 
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=1200, initial-scale=0.1"> <title>Deposit Pro | Admin</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;600;700;800;900&family=Rajdhani:wght@700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
    
    <link rel="stylesheet" href="css/style.css">
    <link rel="shortcut icon" href="images/favicon.png" />

    <style>
        /* =========================================
           3D RESPONSIVE UI
           ========================================= */
        :root {
            --primary: #6c5ce7;
            --success: #00b894;
            --danger: #d63031;
            --dark: #2d3436;
            --bg-body: #f4f7f6;
            --white: #ffffff;
        }

        body {
            background-color: var(--bg-body) !important;
            font-family: 'Poppins', sans-serif;
            color: var(--dark);
            font-weight: 600;
            overflow-x: hidden; /* Prevent horizontal scroll on body */
        }

        /* --- NAVBAR MOBILE FIX --- */
        .navbar { background: #fff !important; box-shadow: 0 2px 10px rgba(0,0,0,0.1) !important; }
        .navbar-toggler { border: none !important; outline: none !important; }
        .fa-bars { font-size: 1.5rem; color: #333 !important; }

        /* --- 3D CARDS --- */
        .pro-card {
            background: var(--white);
            border-radius: 15px;
            padding: 20px;
            border-bottom: 5px solid #dcdcdc;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            margin-bottom: 20px;
            transition: 0.3s;
        }
        .pro-card:hover { transform: translateY(-2px); }

        .card-header-flex {
            display: flex; justify-content: space-between; align-items: center;
            margin-bottom: 15px; border-bottom: 2px dashed #eee; padding-bottom: 10px;
            flex-wrap: wrap; /* Allow wrapping on mobile */
            gap: 10px;
        }
        .card-title {
            font-size: 1.2rem; font-weight: 800; color: var(--dark);
            text-transform: uppercase; letter-spacing: 0.5px;
            display: flex; align-items: center; gap: 10px;
        }

        /* --- 3D BUTTONS --- */
        .btn-3d {
            border: none; border-radius: 10px;
            padding: 10px 15px;
            font-weight: 800; text-transform: uppercase; font-size: 0.8rem;
            cursor: pointer; position: relative; top: 0;
            transition: all 0.1s; color: #fff;
            display: inline-flex; align-items: center; gap: 5px; justify-content: center;
        }
        .btn-approve { background: var(--success); box-shadow: 0 4px 0 #008f72; }
        .btn-reject { background: var(--danger); box-shadow: 0 4px 0 #ab2526; }
        .btn-filter { background: var(--primary); box-shadow: 0 4px 0 #4834d4; width: 100%; }
        
        .btn-3d:active { top: 4px; box-shadow: 0 0 0; }

        /* --- FILTER PANEL (RESPONSIVE) --- */
        .filter-panel {
            background: #eef2f7; padding: 15px; border-radius: 12px;
            border: 2px solid #dde1e7; 
            display: flex; gap: 10px; flex-wrap: wrap; /* Wrap on small screens */
            align-items: flex-end;
        }
        .form-group-custom { flex: 1; min-width: 150px; } /* Min width for mobile */
        
        .modern-input {
            width: 100%; padding: 10px; border: 2px solid #ccc; border-radius: 8px;
            font-weight: 700; outline: none; background: #fff;
        }
        .modern-input:focus { border-color: var(--primary); }

        /* --- TABLES (SCROLLABLE) --- */
        .table-responsive {
            overflow-x: auto; /* Horizontal Scroll on Mobile */
            -webkit-overflow-scrolling: touch;
        }
        
        table.dataTable { width: 100% !important; border-collapse: collapse !important; }
        table.dataTable thead th {
            background-color: #2d3436 !important; color: #fff !important; 
            padding: 12px !important; font-size: 0.85rem; border: none; white-space: nowrap;
        }
        table.dataTable tbody td {
            padding: 12px !important; font-weight: 600; font-size: 0.9rem; 
            border-bottom: 1px solid #eee; vertical-align: middle; white-space: nowrap; /* Prevent breaking lines */
        }

        .utr-badge { background: #e3f2fd; color: #0984e3; padding: 4px 8px; border-radius: 6px; font-size: 0.85rem; }
        .amt-text { font-family: 'Rajdhani', sans-serif; font-size: 1.2rem; font-weight: 800; color: var(--success); }

        /* --- MOBILE SPECIFIC CSS --- */
        @media (max-width: 768px) {
            .content-wrapper { padding: 10px !important; }
            .pro-card { padding: 15px; }
            
            /* Filter inputs stack on mobile */
            .filter-panel { flex-direction: column; align-items: stretch; }
            .form-group-custom { width: 100%; }
            
            /* Table Actions stack */
            .action-buttons { display: flex; flex-direction: column; gap: 5px; }
            .btn-3d { width: 100%; } 
            
            /* Clear History Button on Mobile */
            .card-header-flex { flex-direction: column; align-items: flex-start; }
            .card-header-flex form { width: 100%; margin-top: 10px; }
            .card-header-flex button { width: 100%; }
        }
    </style>
</head>

<body>
    <div class="container-scroller">
        
        <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
            <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center" style="background:#fff;">
                <a class="navbar-brand brand-logo" href="dashboard.php">
                    <h4 style="color:var(--primary); font-weight:900; margin:0;">DEPOSIT<span style="color:#333;">PRO</span></h4>
                </a>
                <a class="navbar-brand brand-logo-mini" href="dashboard.php"><img src="images/logo-mini.png" alt="logo"/></a>
            </div>
            <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end">
                <button class="navbar-toggler navbar-toggler align-self-center" type="button" data-toggle="minimize">
                    <i class="fa-solid fa-bars" style="font-size: 1.5rem;"></i>
                </button>
                
                <ul class="navbar-nav navbar-nav-right">
                    <li class="nav-item dropdown d-flex mr-4">
                        <a class="nav-link count-indicator dropdown-toggle d-flex align-items-center justify-content-center" id="notificationDropdown" href="#" data-toggle="dropdown">
                            <i class="fa-solid fa-gear" style="color:#333; font-size:1.2rem;"></i>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list">
                            <a class="dropdown-item preview-item" href="logout.php">
                                <i class="fa-solid fa-power-off"></i> Logout
                            </a>
                        </div>
                    </li>
                </ul>
                
                <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-toggle="offcanvas">
                    <i class="fa-solid fa-bars" style="color:#333;"></i>
                </button>
            </div>
        </nav>

        <div class="container-fluid page-body-wrapper">
            
            <nav class="sidebar sidebar-offcanvas" id="sidebar" style="background:#fff;">
                <div class="user-profile" style="background:#fff; border-bottom:2px dashed #eee;">
                    <div class="user-image"><img src="images/faces/face28.png" style="border:3px solid var(--primary);"></div>
                    <div class="user-name" style="color:#333; font-size:1.1rem;">AB Coders</div>
                    <div class="user-designation" style="color:#777; font-weight:600;">Super Admin</div>
                </div>
                <?php include 'compass.php'; ?>
            </nav>

            <div class="main-panel">
                <div class="content-wrapper">
                    
                    <div class="pro-card">
                        <div class="card-header-flex">
                            <div class="card-title">
                                <i class="fa-solid fa-hourglass-half" style="color:#fdcb6e;"></i> Pending Requests
                            </div>
                            <div style="background:#fff3cd; color:#856404; padding:5px 12px; border-radius:8px; font-weight:800; font-size:0.8rem;">
                                ACTION NEEDED
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                            <table id="gameSpots" class="table table-bordered" style="width:100%">
                                <thead>
                                    <tr>
                                        <th>User</th>
                                        <th>UTR No</th>
                                        <th>Amount</th>
                                        <th>Date</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sqq = mysqli_query($conn, "SELECT * FROM `thevani` WHERE `sthiti` = '0' ORDER BY `shonu` DESC");
                                    while ($row = mysqli_fetch_array($sqq)) {
                                        $row_id = $row['shonu']; 
                                    ?>
                                    <tr id="row_<?php echo $row_id;?>">
                                        <td>
                                            <div><?php echo $row['balakedara'];?></div>
                                            <small style="color:#777;"><?php echo $row['duravani'];?></small>
                                        </td>
                                        <td><span class="utr-badge"><?php echo $row['ullekha'];?></span></td>
                                        <td><span class="amt-text">₹<?php echo $row['motta'];?></span></td>
                                        <td><small><?php echo $row['dinankavannuracisi'];?></small></td>
                                        <td>
                                            <div class="action-buttons" style="display:flex; gap:5px;">
                                                <form class="approval-form" style="flex:1;" data-id="<?php echo $row_id; ?>">
                                                    <input type="hidden" name="uid" value="<?php echo $row['balakedara'];?>">
                                                    <input type="hidden" name="amount" value="<?php echo $row['motta'];?>">
                                                    <input type="hidden" name="sid" value="<?php echo $row['shonu'];?>">
                                                    <input type="hidden" name="date" value="<?php echo $row['dinankavannuracisi'];?>">
                                                    <input type="hidden" name="ref_num" value="<?php echo $row['ullekha'];?>">
                                                    
                                                    <input type="hidden" name="app" value="1">
                                                    <button class="btn-3d btn-approve" type="submit">
                                                        <i class="fa-solid fa-check"></i>
                                                    </button>
                                                </form>
                                                
                                                <form class="reject-form" style="flex:1;" data-id="<?php echo $row_id; ?>">
                                                    <input type="hidden" name="uid" value="<?php echo $row['balakedara'];?>">
                                                    <input type="hidden" name="amount" value="<?php echo $row['motta'];?>">
                                                    <input type="hidden" name="sid" value="<?php echo $row['shonu'];?>">
                                                    <input type="hidden" name="rej" value="1">
                                                    <button class="btn-3d btn-reject" type="submit">
                                                        <i class="fa-solid fa-xmark"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="pro-card" style="border-bottom-color: var(--primary);">
                        <div class="card-header-flex">
                            <div class="card-title">
                                <i class="fa-solid fa-list-check" style="color:var(--primary);"></i> History & Filter
                            </div>
                            <form method="post" onsubmit="return confirm('⚠️ DELETE ALL HISTORY? This cannot be undone!');">
                                <button type="submit" name="clear_history" class="btn-3d btn-reject" style="font-size:0.7rem;">
                                    <i class="fa-solid fa-trash"></i> CLEAR ALL
                                </button>
                            </form>
                        </div>

                        <form method="post" class="filter-panel mb-4">
                            <div class="form-group-custom">
                                <label style="font-size:0.8rem; font-weight:700; color:#555;">Start Date</label>
                                <input type="date" name="start_date" class="modern-input">
                            </div>
                            <div class="form-group-custom">
                                <label style="font-size:0.8rem; font-weight:700; color:#555;">End Date</label>
                                <input type="date" name="end_date" class="modern-input">
                            </div>
                            <div class="form-group-custom">
                                <label style="font-size:0.8rem; font-weight:700; color:#555;">Status</label>
                                <select name="status_filter" class="modern-input">
                                    <option value="all">All</option>
                                    <option value="1">Completed</option>
                                    <option value="2">Rejected</option>
                                    <option value="0">Pending</option>
                                </select>
                            </div>
                            <div class="form-group-custom" style="flex:0 0 auto;">
                                <button type="submit" name="apply_filter" class="btn-3d btn-filter">
                                    <i class="fa-solid fa-filter"></i> Apply
                                </button>
                            </div>
                        </form>

                        <div style="background:#e3f2fd; padding:12px; border-radius:10px; margin-bottom:15px; border:2px solid #fff; display:flex; justify-content:space-between; align-items:center;">
                            <span style="font-weight:800; color:#555;">Total Found:</span>
                            <span style="font-size:1.3rem; font-weight:900; color:var(--primary);">₹<?php echo number_format($total_amount, 2); ?></span>
                        </div>

                        <div class="table-responsive">
                            <table id="historyTable" class="table table-bordered" style="width:100%">
                                <thead>
                                    <tr>
                                        <th>User</th>
                                        <th>UTR</th>
                                        <th>Amount</th>
                                        <th>Date</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    if(mysqli_num_rows($filter_res) > 0){
                                        while($h_row = mysqli_fetch_assoc($filter_res)){
                                            $st_val = $h_row['sthiti'];
                                            $st_badge = ($st_val == '1') 
                                                ? '<span style="color:#00b894;">Success</span>' 
                                                : (($st_val == '2') ? '<span style="color:#d63031;">Rejected</span>' : '<span style="color:#fdcb6e;">Pending</span>');
                                    ?>
                                    <tr>
                                        <td><?php echo $h_row['balakedara']; ?></td>
                                        <td><small><?php echo $h_row['ullekha']; ?></small></td>
                                        <td><b>₹<?php echo $h_row['motta']; ?></b></td>
                                        <td><small><?php echo $h_row['dinankavannuracisi']; ?></small></td>
                                        <td><?php echo $st_badge; ?></td>
                                    </tr>
                                    <?php } } else { echo "<tr><td colspan='5' class='text-center'>No Data Found</td></tr>"; } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                </div>
                
                <footer class="footer" style="padding:15px; text-align:center; color:#999; font-size:0.8rem;">
                    <span>© 2026 AB Coders</span>
                </footer>

            </div>
        </div>
    </div>

    <script src="vendors/base/vendor.bundle.base.js"></script>
    <script src="js/off-canvas.js"></script>
    <script src="js/hoverable-collapse.js"></script>
    <script src="js/template.js"></script>
    <script src="vendors/chart.js/Chart.min.js"></script>
    <script src="js/dashboard.js"></script>
    <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>

    <script>
    // FIXED AJAX LOGIC - NOW POINTS TO SELF (deposit_update.php)
    
    // 1. APPROVE
    document.querySelectorAll('.approval-form').forEach(function(form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            var btn = this.querySelector('button');
            var originalContent = btn.innerHTML;
            btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i>'; // Loader
            
            var formData = new FormData(this);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'deposit_update.php', true); // Sending to SAME page
            xhr.onload = function() {
                if (xhr.status >= 200 && xhr.status < 400) {
                    var arr = xhr.responseText.split('~');
                    if (arr[0] == 1) { 
                        // IMMEDIATE REMOVAL FROM UI
                        var rowId = form.getAttribute('data-id');
                        var row = document.getElementById('row_' + rowId);
                        if(row) {
                            row.style.display = 'none'; // Hide immediately
                            row.remove(); // Remove from DOM
                        }
                    } else { 
                        alert("Error: " + xhr.responseText); 
                        btn.innerHTML = originalContent;
                    }
                }
            };
            xhr.send(formData);
        });
    });

    // 2. REJECT
    document.querySelectorAll('.reject-form').forEach(function(form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            if(!confirm("⚠️ Confirm Reject?")) return;
            
            var btn = this.querySelector('button');
            var originalContent = btn.innerHTML;
            btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i>'; // Loader

            var formData = new FormData(this);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'deposit_update.php', true); // Sending to SAME page
            xhr.onload = function() {
                if (xhr.status >= 200 && xhr.status < 400) {
                    var arr = xhr.responseText.split('~');
                    if (arr[0] == 1) { 
                         // IMMEDIATE REMOVAL FROM UI
                        var rowId = form.getAttribute('data-id');
                        var row = document.getElementById('row_' + rowId);
                        if(row) {
                            row.style.display = 'none'; // Hide immediately
                            row.remove(); // Remove from DOM
                        }
                    } else { 
                        alert("Error: " + xhr.responseText); 
                        btn.innerHTML = originalContent;
                    }
                }
            };
            xhr.send(formData);
        });
    });

    $(document).ready(function() {
        $('#gameSpots').DataTable({ "searching": true, "pageLength": 10, "ordering": false });
        $('#historyTable').DataTable({ "searching": true, "pageLength": 25, "order": [[ 3, "desc" ]] });
    });

    if (window.history.replaceState) {
        window.history.replaceState(null, null, window.location.href);
    }
    </script>
</body>
</html>