<?php
/* =========================================================
   BANNED USERS MANAGER - PRO MAX (WITH FILTERS & JOIN)
   ========================================================= */

// --- 1. CONFIGURATION ---
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");
    exit();
}

include("conn.php");

$msg = "";
$msg_type = "";

// --- 2. HANDLE ACTIONS ---

// A. SINGLE UNBAN (Only Unban, Keep History)
if (isset($_GET['unban_id'])) {
    $uid = intval($_GET['unban_id']);
    mysqli_query($conn, "UPDATE shonu_subjects SET status = 1 WHERE id = '$uid'");
    $msg = "✅ User Unbanned (History Kept)!";
    $msg_type = "success";
}

// B. SINGLE DELETE (Delete Record Only)
if (isset($_GET['del_id'])) {
    $id = intval($_GET['del_id']);
    mysqli_query($conn, "DELETE FROM banned_users WHERE id = '$id'");
    $msg = "🗑️ History Record Deleted!";
    $msg_type = "success";
}

// C. BULK UNBAN ALL (Only Status Update)
if (isset($_POST['unban_all'])) {
    // List me jitne users hain unko active karo
    $sql = "UPDATE shonu_subjects SET status = 1 WHERE id IN (SELECT user_id FROM banned_users)";
    if(mysqli_query($conn, $sql)) {
        $msg = "✅ All Users Unbanned Successfully!";
        $msg_type = "success";
    }
}

// D. BULK DELETE ALL (Truncate Table)
if (isset($_POST['delete_all'])) {
    if (mysqli_query($conn, "TRUNCATE TABLE banned_users")) {
        $msg = "🗑️ All Ban History Deleted!";
        $msg_type = "error"; // Red color for delete
    }
}

// --- 3. FILTER LOGIC (SEARCH & DATE) ---
$where_clause = "WHERE 1=1";

// Search (UID, Mobile, IP)
if(isset($_GET['search_term']) && !empty($_GET['search_term'])) {
    $term = mysqli_real_escape_string($conn, $_GET['search_term']);
    // Joining with main table to search mobile/ip
    $where_clause .= " AND (b.user_id LIKE '%$term%' OR s.mobile LIKE '%$term%' OR s.ishonup LIKE '%$term%')";
}

// Date Filters
if(isset($_GET['filter_type'])) {
    $type = $_GET['filter_type'];
    
    if($type == 'today') {
        $today = date('Y-m-d');
        $where_clause .= " AND DATE(b.created_at) = '$today'";
    }
    elseif($type == 'custom' && !empty($_GET['custom_date'])) {
        $date = $_GET['custom_date'];
        $where_clause .= " AND DATE(b.created_at) = '$date'";
    }
    elseif($type == 'month' && !empty($_GET['custom_month'])) {
        $month = $_GET['custom_month']; // Format YYYY-MM
        $where_clause .= " AND DATE_FORMAT(b.created_at, '%Y-%m') = '$month'";
    }
}

// --- 4. FETCH DATA (JOIN QUERY) ---
// Note: Assuming 'shonu_subjects' table has 'mobile' and 'ishonup' (IP) columns
$query = "SELECT b.*, s.mobile, s.ishonup, s.status as current_status 
          FROM banned_users b 
          LEFT JOIN shonu_subjects s ON b.user_id = s.id 
          $where_clause 
          ORDER BY b.created_at DESC";

$result = $conn->query($query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=1200, initial-scale=0.5">
    <title>Banned Users Manager</title>
    
    <link rel="stylesheet" href="vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="vendors/feather/feather.css">
    <link rel="stylesheet" href="vendors/base/vendor.bundle.base.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="shortcut icon" href="images/favicon.png" />
    
    <style>
        body { background-color: #f4f7f6; min-width: 1200px; }
        .admin-card { background: #fff; border-radius: 15px; padding: 25px; box-shadow: 0 10px 30px rgba(0,0,0,0.08); border-top: 5px solid #d63031; margin-bottom: 30px; }
        
        .card-header-flex { display: flex; justify-content: space-between; align-items: center; border-bottom: 2px dashed #eee; padding-bottom: 15px; margin-bottom: 20px; }
        .card-title { font-size: 1.5rem; font-weight: 900; color: #d63031; text-transform: uppercase; }
        
        /* SEARCH BAR STYLES */
        .filter-box { background: #f8f9fa; padding: 20px; border-radius: 12px; margin-bottom: 25px; border: 1px solid #eee; }
        .modern-input { width: 100%; padding: 12px; border: 2px solid #ddd; border-radius: 8px; font-weight: 600; outline: none; transition: 0.3s; }
        .modern-input:focus { border-color: #d63031; background: #fff; }
        .btn-search { background: #2d3436; color: white; border: none; padding: 12px 20px; border-radius: 8px; cursor: pointer; font-weight: bold; }
        .btn-today { background: #6c5ce7; color: white; border: none; padding: 12px 20px; border-radius: 8px; cursor: pointer; font-weight: bold; }

        /* BUTTONS */
        .btn-bulk-unban { background: #00b894; color: white; border: none; padding: 12px 20px; border-radius: 8px; font-weight: bold; cursor: pointer; margin-left: 10px; }
        .btn-bulk-del { background: #d63031; color: white; border: none; padding: 12px 20px; border-radius: 8px; font-weight: bold; cursor: pointer; margin-left: 10px; }
        
        .btn-sm-unban { background: #00b894; color: white; padding: 6px 12px; border-radius: 5px; font-size: 0.8rem; text-decoration: none; font-weight: bold; }
        .btn-sm-del { background: #d63031; color: white; padding: 6px 12px; border-radius: 5px; font-size: 0.8rem; text-decoration: none; font-weight: bold; }

        /* TABLE */
        .custom-table { width: 100%; border-collapse: collapse; }
        .custom-table th { background: #2d3436; color: #fff; padding: 15px; text-transform: uppercase; font-size: 0.85rem; }
        .custom-table td { padding: 15px; border-bottom: 1px solid #eee; font-weight: 600; color: #444; }
        
        .badge-ip { background: #dfe6e9; color: #2d3436; padding: 4px 8px; border-radius: 4px; font-family: monospace; }
        .badge-reason { background: #fee2e2; color: #d63031; padding: 4px 8px; border-radius: 4px; font-size: 0.8rem; }
        
        .status-dot { height: 10px; width: 10px; background-color: #bbb; border-radius: 50%; display: inline-block; margin-right: 5px; }
        .dot-green { background-color: #00b894; } /* Active */
        .dot-red { background-color: #d63031; } /* Banned */

        .alert-box { padding: 15px; border-radius: 10px; margin-bottom: 20px; text-align: center; font-weight: 700; }
        .alert-success { background: #d1fae5; color: #065f46; border: 1px solid #34d399; }
        .alert-error { background: #fee2e2; color: #991b1b; border: 1px solid #f87171; }
    </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">
                <a class="navbar-brand brand-logo" href="dashboard.php"><h4 style="color:#d63031; font-weight:900; margin:0;">ADMIN<span style="color:#2d3436;">PANEL</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"><span class="icon-menu"></span></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" href="#" data-toggle="dropdown"><i class="icon-cog"></i></a>
                        <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list">
                            <a class="dropdown-item preview-item" href="logout.php"><i class="icon-inbox"></i> Logout</a>
                        </div>
                    </li>
                </ul>
            </div>
        </nav>

        <div class="container-fluid page-body-wrapper">
            <nav class="sidebar sidebar-offcanvas" id="sidebar">
                <div class="user-profile">
                    <div class="user-image"><img src="images/faces/face28.png"></div>
                    <div class="user-name">AB Coders</div>
                    <div class="user-designation">Admin</div>
                </div>
                <?php include 'compass.php'; ?>
            </nav>

            <div class="main-panel">
                <div class="content-wrapper">
                    
                    <div class="admin-card">
                        <div class="card-header-flex">
                            <div>
                                <div class="card-title"><i class="fa-solid fa-ban"></i> Banned Users History</div>
                            </div>
                            <div style="display:flex;">
                                <form method="post" onsubmit="return confirm('Confirm: This will active ALL users?');">
                                    <button type="submit" name="unban_all" class="btn-bulk-unban">
                                        <i class="fa-solid fa-lock-open"></i> Unban All
                                    </button>
                                </form>

                                <form method="post" onsubmit="return confirm('Confirm: Delete entire history?');">
                                    <button type="submit" name="delete_all" class="btn-bulk-del">
                                        <i class="fa-solid fa-trash"></i> Delete History
                                    </button>
                                </form>
                            </div>
                        </div>

                        <?php if($msg != "") { ?>
                            <div class="alert-box alert-<?php echo $msg_type; ?>"><?php echo $msg; ?></div>
                        <?php } ?>

                        <div class="filter-box">
                            <form method="get">
                                <div class="row align-items-end">
                                    <div class="col-md-3">
                                        <label>Search (UID/Mobile/IP)</label>
                                        <input type="text" name="search_term" class="modern-input" placeholder="Enter ID, Phone or IP" value="<?php echo isset($_GET['search_term']) ? $_GET['search_term'] : ''; ?>">
                                    </div>
                                    <div class="col-md-2">
                                        <label>Date</label>
                                        <input type="date" name="custom_date" class="modern-input" value="<?php echo isset($_GET['custom_date']) ? $_GET['custom_date'] : ''; ?>">
                                        <input type="hidden" name="filter_type" value="custom">
                                    </div>
                                    <div class="col-md-2">
                                        <label>Month</label>
                                        <input type="month" name="custom_month" class="modern-input" value="<?php echo isset($_GET['custom_month']) ? $_GET['custom_month'] : ''; ?>">
                                    </div>
                                    <div class="col-md-5" style="display:flex; gap:10px;">
                                        <button type="submit" class="btn-search"><i class="fa-solid fa-magnifying-glass"></i> Search</button>
                                        
                                        <a href="?filter_type=today" class="btn-today" style="text-decoration:none; display:inline-block; text-align:center;">
                                            <i class="fa-solid fa-calendar-day"></i> Today
                                        </a>
                                        
                                        <a href="bannedusers.php" style="padding:12px; color:#666; font-weight:bold; text-decoration:none;">Reset</a>
                                    </div>
                                </div>
                            </form>
                        </div>

                        <div class="table-responsive">
                            <table class="custom-table">
                                <thead>
                                    <tr>
                                        <th>User Info</th>
                                        <th>IP Address</th>
                                        <th>Reason</th>
                                        <th>Banned Date</th>
                                        <th>Current Status</th>
                                        <th style="text-align:right;">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    if ($result->num_rows > 0) {
                                        while ($row = $result->fetch_assoc()) { 
                                            // Check current status from joined table
                                            $is_active = ($row['current_status'] == 1);
                                    ?>
                                    <tr>
                                        <td>
                                            UID: <b><?php echo $row['user_id']; ?></b><br>
                                            <small style="color:#6c5ce7;"><?php echo !empty($row['mobile']) ? $row['mobile'] : 'N/A'; ?></small>
                                        </td>
                                        <td>
                                            <span class="badge-ip"><?php echo !empty($row['ishonup']) ? $row['ishonup'] : 'Unknown'; ?></span>
                                        </td>
                                        <td><span class="badge-reason"><?php echo $row['reason']; ?></span></td>
                                        <td><?php echo date('d-M-Y h:i A', strtotime($row['created_at'])); ?></td>
                                        <td>
                                            <?php if($is_active) { ?>
                                                <span class="dot-green"></span> Active
                                            <?php } else { ?>
                                                <span class="dot-red"></span> Banned
                                            <?php } ?>
                                        </td>
                                        <td style="text-align:right;">
                                            <?php if(!$is_active) { ?>
                                            <a href="?unban_id=<?php echo $row['user_id']; ?>" class="btn-sm-unban" title="Unban User">
                                                <i class="fa-solid fa-lock-open"></i>
                                            </a>
                                            <?php } ?>
                                            
                                            <a href="?del_id=<?php echo $row['id']; ?>" class="btn-sm-del" title="Delete Record" onclick="return confirm('Delete log?');">
                                                <i class="fa-solid fa-trash"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php 
                                        }
                                    } else { 
                                    ?>
                                    <tr>
                                        <td colspan="6" style="text-align:center; padding:50px; color:#999;">
                                            <i class="fa-solid fa-filter-circle-xmark" style="font-size:3rem; margin-bottom:15px; color:#d63031;"></i>
                                            <h3>No Records Found</h3>
                                            <p>Try changing filters or no users are banned.</p>
                                        </td>
                                    </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>

                    </div>
                </div>
                
                <footer class="footer">
                    <div class="d-sm-flex justify-content-center justify-content-sm-between">
                        <span class="text-muted d-block text-center text-sm-left d-sm-inline-block">Copyright © 2026 AB Coders</span>
                    </div>
                </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="js/dashboard.js"></script>
    
    <script>
    
    </script>
</body>
</html>