<?php 
session_start(); 

// ১. লগইন এবং মাল্টি-টেন্যান্ট সেশন চেক
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || !isset($_SESSION['isp_id'])) {
    header("Location: login.php");
    exit;
}

// মাল্টি-টেন্যান্ট আইডি এবং রোল ভ্যারিয়েবল
$current_isp_id = $_SESSION['isp_id'];
$user_role = $_SESSION['role'] ?? 'Stuff';
$logged_in_name = $_SESSION['admin_name'] ?? 'Stuff';

include 'config.php';
include 'routeros_api.class.php'; // মাইক্রোটিক কানেকশনের জন্য
date_default_timezone_set('Asia/Dhaka'); 

// --- মাইক্রোটিক বাল্ক ব্লক লজিক (মাল্টি-টেন্যান্ট এনহ্যান্সড) ---
$sync_message = "";
if (isset($_GET['action']) && $_GET['action'] == 'sync_block') {
    
    // ডাটাবেস থেকে বর্তমান লগইন করা আইএসপি-র নিজস্ব মাইক্রোটিক সেটিংস তুলে আনা
    $settings_res = mysqli_query($conn, "SELECT * FROM isp_settings WHERE isp_id = '$current_isp_id' LIMIT 1");
    $isp_settings = mysqli_fetch_assoc($settings_res);

    if (!$isp_settings) {
        $sync_message = "<script>alert('আপনার মাইক্রোটিক সেটিংস কনফিগার করা নেই। অনুগ্রহ করে প্রোফাইল আপডেট করুন।'); window.location.href='deactivated.php';</script>";
    } else {
        $m_ip   = $isp_settings['mikrotik_ip']; 
        $m_user = $isp_settings['mikrotik_user']; 
        $m_pass = $isp_settings['mikrotik_pass']; 
        $m_port = $isp_settings['mikrotik_port'];

        $api = new RouterosAPI();
        
        // শুধুমাত্র বর্তমান ISP-র ডিঅ্যাক্টিভেটেড কাস্টমারদের কুয়েরি করা (isp_id ফিল্টার সহ)
        $deactivated_users = mysqli_query($conn, "SELECT customer_id FROM customers WHERE status='deactivated' AND isp_id = '$current_isp_id'");
        
        if (mysqli_num_rows($deactivated_users) > 0) {
            if ($api->connect($m_ip, $m_user, $m_pass, $m_port)) {
                $count = 0;
                while ($row = mysqli_fetch_assoc($deactivated_users)) {
                    $cid = $row['customer_id'];
                    
                    // ১. MikroTik-এ নির্দিষ্ট ইউজারের প্রোফাইল পরিবর্তন করে 'Block' করা
                    $api->comm("/ppp/secret/set", array("numbers" => $cid, "profile" => "Block"));
                    
                    // ২. কারেন্ট একটিভ সেশন কেটে দেওয়া
                    $online = $api->comm("/ppp/active/print", array("?name" => $cid));
                    if (!empty($online)) {
                        $api->comm("/ppp/active/remove", array(".id" => $online[0][".id"]));
                    }
                    $count++;
                }
                $api->disconnect();
                $sync_message = "<script>alert('সফলভাবে আপনার কোম্পানির $count জন ইউজারের প্রোফাইল মাইক্রোটিকে Block করা হয়েছে!'); window.location.href='deactivated.php';</script>";
            } else {
                $sync_message = "<script>alert('আপনার মাইক্রোটিক রাউটারের সাথে কানেক্ট করা যায়নি! আইপি বা পোর্ট চেক করুন।');</script>";
            }
        } else {
            $sync_message = "<script>alert('কোন ডিঅ্যাক্টিভেটেড ইউজার পাওয়া যায়নি।'); window.location.href='deactivated.php';</script>";
        }
    }
}

// সার্চ লজিক
$search = $_GET['search'] ?? '';
$search_query = "";
if ($search) {
    $search_clean = mysqli_real_escape_string($conn, $search);
    $search_query = "AND (customer_id LIKE '%$search_clean%' OR name LIKE '%$search_clean%')";
}

// শুধুমাত্র বর্তমান ISP-র ডিঅ্যাক্টিভেটেড কাস্টমার ডাটা কুয়েরি (isp_id ফিল্টার সহ)
$customers = mysqli_query($conn, "SELECT * FROM customers WHERE status='deactivated' AND isp_id = '$current_isp_id' $search_query ORDER BY id DESC");
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Deactivated Customers | SaaS ISP Portal</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { 
            --primary: #4f46e5; 
            --primary-hover: #4338ca;
            --success: #10b981; 
            --danger: #ef4444; 
            --dark: #1f2937; 
            --sidebar-bg: #111827;
            --sidebar-hover: #1f2937;
            --warning: #f59e0b; 
            --bg-light: #f3f4f6;
        }
        
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Inter', sans-serif; background: var(--bg-light); color: var(--dark); display: flex; height: 100vh; overflow: hidden; }
        
        .sidebar { position: fixed; left: -260px; top: 0; bottom: 0; width: 260px; background: var(--sidebar-bg); color: #fff; display: flex; flex-direction: column; justify-content: space-between; height: 100%; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); z-index: 1000; }
        .sidebar.open { left: 0; }
        
        .sidebar-brand { padding: 24px 20px; font-size: 20px; font-weight: 700; letter-spacing: 1px; border-bottom: 1px solid #1f2937; color: #fff; text-decoration: none; display: flex; align-items: center; gap: 10px; }
        .sidebar-menu { list-style: none; padding: 20px 0; flex-grow: 1; overflow-y: auto; }
        .sidebar-item a { display: flex; align-items: center; gap: 15px; padding: 12px 24px; color: #9ca3af; text-decoration: none; font-size: 14px; font-weight: 500; transition: all 0.2s; }
        .sidebar-item a:hover, .sidebar-item.active a { color: #fff; background: var(--sidebar-hover); border-left: 4px solid var(--primary); }
        .sidebar-item a i { width: 20px; text-align: center; font-size: 16px; }
        
        .sidebar-footer { padding: 20px; border-top: 1px solid #1f2937; }
        .btn-logout { display: flex; align-items: center; justify-content: center; gap: 10px; background: #dc2626; color: white; padding: 12px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px; transition: 0.2s; }
        .btn-logout:hover { background: #b91c1c; }

        .main-content { flex: 1; display: flex; flex-direction: column; height: 100%; overflow: hidden; position: relative; width: 100%; }
        
        .top-navbar { background: #fff; height: 70px; display: flex; align-items: center; justify-content: space-between; padding: 0 40px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
        .menu-toggle { display: block; font-size: 22px; cursor: pointer; color: var(--dark); padding: 5px 10px; border-radius: 6px; transition: background 0.2s; z-index: 101; }
        .menu-toggle:hover { background: #f3f4f6; }
        
        .search-box { margin-left: 20px; flex: 1; max-width: 400px; }
        .search-box input { padding: 10px 16px; border-radius: 8px; border: 1px solid #e5e7eb; width: 100%; font-family: 'Inter'; font-size: 14px; outline: none; transition: 0.2s; }
        .search-box input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1); }
        
        .btn-sync { background: var(--warning); color: #fff; padding: 10px 16px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 13px; display: flex; align-items: center; gap: 8px; transition: 0.2s; border: none; cursor: pointer; }
        .btn-sync:hover { background: #d97706; }

        .dashboard-body { padding: 40px; overflow-y: auto; flex: 1; }

        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; gap: 15px; flex-wrap: wrap; }
        .page-title-area { display: flex; align-items: center; gap: 12px; }
        .page-header h2 { font-size: 22px; font-weight: 700; color: var(--dark); }
        .dot { height: 11px; width: 11px; background-color: var(--danger); border-radius: 50%; display: inline-block; }

        .table-box { background: white; border-radius: 12px; overflow-x: auto; box-shadow: 0 1px 3px rgba(0,0,0,0.05); border: 1px solid #e5e7eb; }
        table { width: 100%; border-collapse: collapse; min-width: 900px; }
        th, td { padding: 16px 20px; text-align: left; border-bottom: 1px solid #f3f4f6; white-space: nowrap; }
        th { background: #f9fafb; font-size: 12px; color: #4b5563; font-weight: 600; text-transform: uppercase; }
        tr:hover td { background-color: #f9fafb; }
        
        .badge { padding: 6px 12px; border-radius: 20px; font-size: 11px; font-weight: 600; text-transform: uppercase; background: #fee2e2; color: #991b1b; }

        .sidebar-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.4); z-index: 995; backdrop-filter: blur(2px); }
        .sidebar-overlay.active { display: block; }

        @media (max-width: 768px) {
            .top-navbar { padding: 0 10px; }
            .search-box { max-width: 140px; margin-left: 5px; }
            .dashboard-body { padding: 20px; }
            .page-header h2 { font-size: 18px; }
            .btn-sync { padding: 8px 10px; font-size: 11px; }
        }
    </style>
</head>
<body>

<?php if(!empty($sync_message)) echo $sync_message; ?>

<div class="sidebar-overlay" id="sidebarOverlay" onclick="toggleSidebar()"></div>

<aside class="sidebar" id="sidebar">
    <div>
        <a href="index.php" class="sidebar-brand">
            <i class="fa-solid fa-cloud"></i> CloudISP
        </a>
        <ul class="sidebar-menu">
            <li class="sidebar-item">
                <a href="index.php"><i class="fa-solid fa-gauge"></i> Dashboard</a>
            </li>
            <li class="sidebar-item">
                <a href="all.php"><i class="fa-solid fa-users"></i> All Clients</a>
            </li>
            <li class="sidebar-item">
                <a href="active.php"><i class="fa-solid fa-user-check"></i> Active Clients</a>
            </li>
            <li class="sidebar-item">
                <a href="live_clients.php"><i class="fa-solid fa-circle-dot"></i> Live Online</a>
            </li>
            <li class="sidebar-item active">
                <a href="deactivated.php"><i class="fa-solid fa-user-slash"></i> Deactivated</a>
            </li>
            <li class="sidebar-item">
                <a href="today.php"><i class="fa-solid fa-calendar-day"></i> Today Collect</a>
            </li>
            <li class="sidebar-item">
                <a href="monthly.php"><i class="fa-solid fa-calendar-days"></i> Monthly Collect</a>
            </li>
        </ul>
    </div>
    <div class="sidebar-footer">
        <div style="padding: 5px 10px; color: #9ca3af; font-size: 12px; text-align: center;">Logged in: <b><?php echo htmlspecialchars($logged_in_name); ?></b></div>
        <a href="logout.php" class="btn-logout" onclick="return confirm('আপনি কি নিশ্চিতভাবে লগআউট করতে চান?')">
            <i class="fa-solid fa-right-from-bracket"></i> Logout
        </a>
    </div>
</aside>

<main class="main-content">
    
    <header class="top-navbar">
        <div style="display: flex; align-items: center; flex: 1;">
            <div class="menu-toggle" onclick="toggleSidebar()">
                <i class="fa-solid fa-bars"></i>
            </div>
            <div class="search-box">
                <form method="GET">
                    <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Search Deactivated User...">
                </form>
            </div>
        </div>
        
        <div style="display: flex; align-items: center; gap: 15px;">
            <a href="deactivated.php?action=sync_block" class="btn-sync" onclick="return confirm('আপনি কি নিশ্চিতভাবে আপনার সকল ডিঅ্যাক্টিভেটেড ইউজারকে মাইক্রোটিকে Block প্রোফাইল করতে চান?')">
                <i class="fa-solid fa-rotate"></i> Sync MicroTik Block
            </a>
            <div style="font-weight: 600; font-size: 14px; color: var(--danger);" class="panel-title-desktop">
                <i class="fa-solid fa-user-slash"></i> Deactivated Panel
            </div>
        </div>
    </header>

    <div class="dashboard-body">

        <div class="page-header">
            <div class="page-title-area">
                <span class="dot"></span>
                <h2>Deactivated Customers List</h2>
            </div>
        </div>

        <div class="table-box">
            <table>
                <thead>
                    <tr>
                        <th>User ID</th>
                        <th>Full Name</th>
                        <th>Mobile</th>
                        <th>Monthly Bill</th>
                        <th>Expiry Date</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(mysqli_num_rows($customers) > 0): ?>
                        <?php while($row = mysqli_fetch_assoc($customers)): ?>
                        <tr>
                            <td><strong><?php echo $row['customer_id']; ?></strong></td>
                            <td><?php echo $row['name']; ?></td>
                            <td><?php echo !empty($row['phone']) ? $row['phone'] : (!empty($row['mobile']) ? $row['mobile'] : 'N/A'); ?></td>
                            <td><strong><?php echo number_format($row['bill_amount'], 0); ?></strong> TK</td>
                            <td><?php echo !empty($row['expiry_date']) ? date("d-M-Y", strtotime($row['expiry_date'])) : 'N/A'; ?></td>
                            <td><span class="badge">EXPIRED</span></td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6" style="text-align: center; padding: 40px; color: #9ca3af;">No deactivated customers found.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<script>
function toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('open');
    document.getElementById('sidebarOverlay').classList.toggle('active');
}
</script>

</body>
</html>
