<?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';

// ২. CSV ডাউনলোড লজিক (আইএসপি ডাটা ফিল্টারিং সহ)
if(isset($_GET['export'])) {
    // সিকিউরিটি চেক: শুধুমাত্র Super Admin ডাউনলোড করতে পারবে
    if ($user_role !== 'Super Admin') {
        die("আপনার এই ফাইলটি ডাউনলোড করার অনুমতি নেই!");
    }

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=active_customer_list.csv');
    
    $output = fopen('php://output', 'w');
    
    // CSV হেডার
    fputcsv($output, array('ID', 'Customer ID', 'Name', 'Phone', 'NID No', 'Bill Amount', 'Connection Date', 'Expiry Date', 'Balance', 'Address', 'Status'));
    
    // ডাটা কুয়েরি (এখানে isp_id = $current_isp_id যুক্ত করা হয়েছে)
    $query = "SELECT id, customer_id, name, phone, nid_no, bill_amount, connection_date, expiry_date, balance, address, status 
              FROM customers 
              WHERE status = 'active' AND isp_id = '$current_isp_id'";
    $result = mysqli_query($conn, $query);
    
    while($row = mysqli_fetch_assoc($result)) {
        fputcsv($output, $row);
    }
    fclose($output);
    exit();
}

// ৩. টেবিলের জন্য ডাটা আনা (এখানেও isp_id ফিল্টার যুক্ত করা হয়েছে)
$sql = "SELECT * FROM customers WHERE status = 'active' AND isp_id = '$current_isp_id' ORDER BY id ASC";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Active Customer List | SaaS 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; z-index: 1000; }
        .sidebar.open { left: 0; }
        .sidebar-brand { padding: 24px 20px; font-size: 20px; font-weight: 700; 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; }
        .sidebar-item a:hover, .sidebar-item.active a { color: #fff; background: var(--sidebar-hover); border-left: 4px solid var(--primary); }
        .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; }
        
        .main-content { flex: 1; display: flex; flex-direction: column; height: 100%; overflow: hidden; }
        .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 { font-size: 22px; cursor: pointer; }
        .dashboard-body { padding: 40px; overflow-y: auto; flex: 1; }
        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; }
        .btn-csv { background: var(--success); color: white; padding: 10px 18px; border-radius: 8px; text-decoration: none; font-size: 14px; font-weight: 600; display: inline-flex; align-items: center; gap: 8px; }
        
        .table-box { background: white; border-radius: 12px; overflow-x: auto; border: 1px solid #e5e7eb; }
        table { width: 100%; border-collapse: collapse; min-width: 1100px; }
        th, td { padding: 16px 20px; text-align: left; border-bottom: 1px solid #f3f4f6; }
        th { background: #f9fafb; font-size: 12px; color: #4b5563; text-transform: uppercase; }
        .badge-active { background: #d1fae5; color: #065f46; padding: 6px 12px; border-radius: 20px; font-size: 11px; font-weight: 600; }
        .sidebar-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.4); z-index: 995; }
        .sidebar-overlay.active { display: block; }
    </style>
</head>
<body>

<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 active"><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"><a href="deactivated.php"><i class="fa-solid fa-user-slash"></i> Deactivated</a></li>
        </ul>
    </div>
    <div class="sidebar-footer">
        <div style="padding: 10px; color: #9ca3af; font-size: 12px; text-align: center;">Logged in: <b><?php echo $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 class="menu-toggle" onclick="toggleSidebar()"><i class="fa-solid fa-bars"></i></div>
        <div style="color: var(--primary); font-weight: 600;"><i class="fa-solid fa-shield-halved"></i> Tenant Session Active</div>
    </header>

    <div class="dashboard-body">
        <div class="page-header">
            <h2>Active Customer List</h2>
            
            <?php if ($user_role === 'Super Admin'): ?>
                <a href="?export=true" class="btn-csv"><i class="fa-solid fa-file-csv"></i> Download Active CSV File</a>
            <?php endif; ?>
        </div>

        <div class="table-box">
            <table>
                <thead>
                    <tr><th>ID</th><th>Customer ID</th><th>Name</th><th>Phone</th><th>Bill Amount</th><th>Expiry Date</th><th>Status</th></tr>
                </thead>
                <tbody>
                    <?php
                    if ($result && $result->num_rows > 0) {
                        $counter = 1;
                        while($row = $result->fetch_assoc()) {
                            echo "<tr>
                                    <td>".$counter++."</td>
                                    <td><strong>".$row["customer_id"]."</strong></td>
                                    <td>".$row["name"]."</td>
                                    <td>".$row["phone"]."</td>
                                    <td><strong>".number_format($row["bill_amount"], 0)." TK</strong></td>
                                    <td>".date("d-M-Y", strtotime($row["expiry_date"]))."</td>
                                    <td><span class='badge-active'>".strtoupper($row["status"])."</span></td>
                                  </tr>";
                        }
                    } else {
                        echo "<tr><td colspan='7' style='text-align:center; padding: 30px;'>কোনো অ্যাক্টিভ কাস্টমার ডাটা পাওয়া যায়নি।</td></tr>";
                    }
                    $conn->close();
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

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

</body>
</html>
