<?php
// --- ERROR REPORTING (Debugging ke liye) ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

// conn.php include karne se 'encryptor' function apne aap aa jayega
include("conn.php"); 

// --- 1. CLEAR HISTORY ---
if (isset($_POST['clear_history'])) {
    // Delete Completed(1) or Rejected(2)
    $del_sql = "DELETE FROM hintegedukolli WHERE sthiti = '1' OR sthiti = '2'";
    if (mysqli_query($conn, $del_sql)) {
        echo '<script>alert("✅ Withdrawal History Cleared!"); window.location.href="manage_withdraw.php";</script>';
    }
}

// --- 2. FILTER LOGIC ---
// Default Query
$filter_query = "SELECT h.*, u.mobile FROM hintegedukolli h JOIN shonu_subjects u ON h.balakedara = u.id WHERE 1";
$total_amount = 0;

if (isset($_POST['apply_filter'])) {
    $start = $_POST['start_date'];
    $end = $_POST['end_date'];
    $status = $_POST['status_filter'];
    $search = trim($_POST['search_term']);

    if (!empty($start) && !empty($end)) {
        $filter_query .= " AND h.dinankavannuracisi BETWEEN '$start' AND '$end'";
    }
    if ($status != 'all') {
        $filter_query .= " AND h.sthiti = '$status'";
    }
    if (!empty($search)) {
        $filter_query .= " AND (h.dharavahi LIKE '%$search%' OR u.mobile LIKE '%$search%')";
    }
} else {
    // Default: Show Pending First
    $filter_query .= " AND h.sthiti = '0'";
}

$filter_query .= " ORDER BY h.shonu DESC";
$filter_res = mysqli_query($conn, $filter_query);

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

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no">
    <title>Withdrawal Manager</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>
        /* =========================================
           WITHDRAWAL PRO THEME (3D & Clean)
           ========================================= */
        :root {
            --primary: #4834d4;
            --success: #20bf6b;
            --danger: #eb3b5a;
            --warning: #f7b731;
            --dark: #2d3436;
            --light: #f4f7f6;
            --white: #ffffff;
        }

        body {
            background-color: var(--light);
            font-family: 'Poppins', sans-serif;
            color: var(--dark);
            font-weight: 600;
        }

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

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

        /* --- 3D BUTTONS --- */
        .btn-3d {
            border: none; border-radius: 8px; padding: 10px 18px;
            font-weight: 700; text-transform: uppercase; font-size: 0.8rem;
            cursor: pointer; position: relative; top: 0; color: #fff;
            transition: all 0.1s; display: inline-flex; align-items: center; gap: 5px; text-decoration: none;
        }
        .btn-approve { background: var(--success); box-shadow: 0 4px 0 #169352; }
        .btn-reject { background: var(--danger); box-shadow: 0 4px 0 #b32a43; }
        .btn-edit { background: var(--primary); box-shadow: 0 4px 0 #33239e; }
        .btn-filter { background: var(--dark); box-shadow: 0 4px 0 #000; width: 100%; justify-content: center; }
        
        .btn-3d:active { top: 4px; box-shadow: 0 0 0; }
        .btn-3d:hover { color: #fff; }

        /* --- FILTER PANEL --- */
        .filter-panel {
            background: #dfe6e9; padding: 15px; border-radius: 12px;
            border: 2px solid #b2bec3; display: flex; gap: 10px; flex-wrap: wrap; align-items: flex-end;
        }
        .form-grp { flex: 1; min-width: 160px; }
        .form-label { font-size: 0.75rem; font-weight: 700; color: #636e72; margin-bottom: 5px; display: block; }
        
        .modern-input {
            width: 100%; padding: 10px; border: 2px solid #ccc; border-radius: 8px;
            font-weight: 700; outline: none; transition: 0.3s;
        }
        .modern-input:focus { border-color: var(--primary); background: #fff; }

        /* --- TABLE --- */
        .table-responsive { overflow-x: auto; }
        table.dataTable { width: 100% !important; border-collapse: collapse !important; }
        table.dataTable thead th {
            background-color: var(--dark) !important; color: #fff !important; padding: 12px !important; font-size: 0.9rem; 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;
        }
        
        .amt-text { font-family: 'Rajdhani', sans-serif; font-size: 1.2rem; font-weight: 800; color: var(--success); }
        .status-badge { padding: 4px 10px; border-radius: 20px; font-size: 0.75rem; font-weight: 800; text-transform: uppercase; }
        .st-pending { background: #ffeaa7; color: #d35400; }
        .st-success { background: #55efc4; color: #006266; }
        .st-rejected { background: #fab1a0; color: #b33939; }

        /* Navbar Fixes */
        .navbar { background: #fff !important; box-shadow: 0 4px 15px rgba(0,0,0,0.05) !important; }
        .navbar-toggler { border:none !important; outline:none !important; }
        .fa-bars { font-size: 1.5rem; color: #333; }

        /* Mobile Fix */
        @media (max-width: 768px) {
            .content-wrapper { padding: 10px !important; }
            .filter-panel { flex-direction: column; }
            .form-grp { width: 100%; }
            .btn-3d { width: 100%; justify-content: center; margin-bottom: 5px; }
        }
    </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(--danger); font-weight:900; margin:0;">WITHDRAW<span style="color:var(--dark);">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"></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:var(--dark); 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"></i>
                </button>
            </div>
        </nav>

        <div class="container-fluid page-body-wrapper">
            
            <nav class="sidebar sidebar-offcanvas" id="sidebar">
                <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(--danger);"></div>
                    <div class="user-name" style="color:var(--dark); font-size:1.1rem;">AB Coders</div>
                    <div class="user-designation" style="color:#888;">Admin</div>
                </div>
                <?php include 'compass.php'; ?>
            </nav>

            <div class="main-panel">
                <div class="content-wrapper">
                    
                    <div class="wd-card">
                        <div class="card-header-flex">
                            <div class="card-title">
                                <i class="fa-solid fa-filter" style="color:var(--primary);"></i> Advanced Search
                            </div>
                            <form method="post" onsubmit="return confirm('⚠️ Delete ALL Completed/Rejected records?');">
                                <button type="submit" name="clear_history" class="btn-3d btn-reject" style="font-size:0.7rem;">
                                    <i class="fa-solid fa-trash"></i> CLEAR HISTORY
                                </button>
                            </form>
                        </div>

                        <form method="post" class="filter-panel">
                            <div class="form-grp">
                                <label class="form-label">Search (Order ID/Mobile)</label>
                                <input type="text" name="search_term" class="modern-input" placeholder="Enter ID...">
                            </div>
                            <div class="form-grp">
                                <label class="form-label">Start Date</label>
                                <input type="date" name="start_date" class="modern-input">
                            </div>
                            <div class="form-grp">
                                <label class="form-label">End Date</label>
                                <input type="date" name="end_date" class="modern-input">
                            </div>
                            <div class="form-grp">
                                <label class="form-label">Status</label>
                                <select name="status_filter" class="modern-input">
                                    <option value="0">⏳ Pending</option>
                                    <option value="1">✅ Success</option>
                                    <option value="2">❌ Rejected</option>
                                    <option value="all">Show All</option>
                                </select>
                            </div>
                            <div class="form-grp" style="flex:0 0 auto;">
                                <label class="form-label">&nbsp;</label>
                                <button type="submit" name="apply_filter" class="btn-3d btn-filter">
                                    <i class="fa-solid fa-search"></i> Find
                                </button>
                            </div>
                        </form>
                    </div>

                    <div class="wd-card" style="border-bottom-color: var(--success);">
                        <div class="card-header-flex">
                            <div class="card-title">
                                <i class="fa-solid fa-list-ul" style="color:var(--success);"></i> Requests List
                            </div>
                            <div style="background:#dff9fb; padding:10px 15px; border-radius:10px; border:2px solid #fff; box-shadow:0 5px 15px rgba(0,0,0,0.05);">
                                <span style="font-weight:700; color:#555;">Total Filtered:</span>
                                <span style="font-size:1.2rem; font-weight:900; color:var(--primary);">₹<?php echo number_format($total_amount, 2); ?></span>
                            </div>
                        </div>

                        <div class="table-responsive">
                            <table id="example1" class="table table-bordered" style="width:100%">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>User Mobile</th>
                                        <th>Amount</th>
                                        <th>Order ID</th>
                                        <th>Date</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                        $i=0;
                                        if(mysqli_num_rows($filter_res) > 0){
                                            while($row = mysqli_fetch_array($filter_res)){
                                                $i++;
                                                $status = $row['sthiti'];
                                                $badge_cls = ($status == '1') ? 'st-success' : (($status == '2') ? 'st-rejected' : 'st-pending');
                                                $status_txt = ($status == '1') ? 'Success' : (($status == '2') ? 'Rejected' : 'Pending');
                                    ?>
                                    <tr>
                                        <td><?php echo $i; ?></td>
                                        <td><?php echo $row['mobile']; ?></td>
                                        <td><span class="amt-text">₹<?php echo number_format($row['motta'], 2); ?></span></td>
                                        <td><?php echo $row['dharavahi']; ?></td>
                                        <td><?php echo date('d-M-Y', strtotime($row['dinankavannuracisi'])); ?></td>
                                        <td><span class="status-badge <?php echo $badge_cls; ?>"><?php echo $status_txt; ?></span></td>
                                        <td>
                                            <div style="display:flex; gap:5px; flex-wrap:wrap;">
                                                <a href="withdrawal-accept-reject.php?id=<?php echo encryptor('encrypt', $row['shonu']); ?>" class="btn-3d btn-approve" title="Process">
                                                    <i class="fa-solid fa-eye"></i> View
                                                </a>
                                                
                                                <a href="edit_bank.php?uid=<?php echo $row['balakedara']; ?>" class="btn-3d btn-edit" title="Edit Bank">
                                                    <i class="fa-solid fa-pen"></i> Bank
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php } } else { echo "<tr><td colspan='7' class='text-center'>No Records Found</td></tr>"; } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                </div>
                
                <footer class="footer" style="padding:20px; 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>
    $(document).ready(function() {
        $('#example1').DataTable({
            "paging": true,
            "lengthChange": false,
            "searching": false, 
            "ordering": false,
            "info": true,
            "autoWidth": true,
            "pageLength": 10
        });
    });

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