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

// ২. ডাটাবেস থেকে লগইন করা আইএসপি-র নিজস্ব মাইক্রোটিক সেটিংস তুলে আনা
$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) {
    die("আপনার মাইক্রোটিক সেটিংস কনফিগার করা নেই। অনুগ্রহ করে প্রোফাইল আপডেট করুন বা অ্যাডমিনের সাথে যোগাযোগ করুন।");
}

$m_ip   = $isp_settings['mikrotik_ip']; 
$m_user = $isp_settings['mikrotik_user']; 
$m_pass = $isp_settings['mikrotik_pass']; 
$m_port = $isp_settings['mikrotik_port'];

$customerData = [];
// শুধুমাত্র বর্তমান আইএসপির কাস্টমারদের ডাটা আনা হচ্ছে (isp_id ফিল্টার সহ)
$sql_names = "SELECT customer_id, name, status, expiry_date FROM customers WHERE isp_id = '$current_isp_id'";
$res_names = mysqli_query($conn, $sql_names);
if ($res_names) {
    while ($row = mysqli_fetch_assoc($res_names)) {
        $customerData[$row['customer_id']] = [
            'name' => $row['name'], 
            'status' => $row['status'],
            'expiry_date' => $row['expiry_date']
        ];
    }
}

$api = new RouterosAPI();
$active_users = [];
$deactiveCount = 0;

if ($api->connect($m_ip, $m_user, $m_pass, $m_port)) {
    $all_online = $api->comm("/ppp/active/print");
    $api->disconnect();
    
    if (is_array($all_online)) {
        foreach ($all_online as $user) {
            // মাইক্রোটিক থেকে আসা $user['name'] যদি এই database এর customer_id হয়
            if (array_key_exists($user['name'], $customerData)) {
                $user['customer_id'] = $user['name']; 
                $user['full_name'] = $customerData[$user['name']]['name'];
                $user['status'] = $customerData[$user['name']]['status'];
                $user['expiry_date'] = $customerData[$user['name']]['expiry_date'];
                
                if (strtolower($user['status']) !== 'active') {
                    $deactiveCount++;
                }
                
                $active_users[] = $user;
            }
        }
    }
    
    usort($active_users, function($a, $b) {
        return strnatcasecmp($a['customer_id'], $b['customer_id']);
    });
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <title>Live Monitoring | SaaS ISP Portal</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.canvasjs.com/canvasjs.min.js"></script>
    <style>
        body { font-family: 'Inter', sans-serif; background: #f8fafc; margin: 0; color: #334155; }
        .navbar { background: #fff; padding: 15px 5%; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
        .logo { font-weight: 700; font-size: 20px; color: #4f46e5; }
        .nav-links a { text-decoration: none; color: #64748b; margin-left: 20px; font-size: 14px; font-weight: 600; }
        .container { max-width: 1200px; margin: 30px auto; padding: 0 20px; }
        .header-section { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .card { background: #fff; border-radius: 12px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); overflow: hidden; }
        table { width: 100%; border-collapse: collapse; }
        th { background: #f1f5f9; padding: 15px; text-align: left; font-size: 13px; color: #475569; }
        td { padding: 15px; border-top: 1px solid #e2e8f0; font-size: 14px; position: relative; }
        .badge { padding: 4px 10px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .ip { background: #dcfce7; color: #166534; }
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
        .search-bar { padding: 10px 15px; border: 1px solid #cbd5e1; border-radius: 8px; width: 250px; }

        /* --- ড্রপডাউন মেনু স্টাইল --- */
        .dropdown { position: relative; display: inline-block; }
        .btn-action { background: none; border: none; font-size: 20px; cursor: pointer; color: #4f46e5; letter-spacing: 2px; padding: 5px; }
        .dropdown-content { display: none; position: absolute; right: 0; background-color: #2563eb; min-width: 150px; box-shadow: 0px 8px 16px rgba(0,0,0,0.2); border-radius: 6px; z-index: 100; padding: 5px 0; }
        .dropdown-content a, .dropdown-content button { color: white; padding: 10px 15px; text-decoration: none; display: flex; align-items: center; gap: 8px; width: 100%; background: none; border: none; text-align: left; font-size: 13px; cursor: pointer; box-sizing: border-box; font-family: inherit; }
        .dropdown-content a:hover, .dropdown-content button:hover { background-color: #1d4ed8; }
        .show { display: block; }

        /* --- পপআপ মডাল উইন্ডো স্টাইল --- */
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.4); justify-content: center; align-items: center; }
        .modal-content { background-color: #fff; border-radius: 12px; width: 500px; box-shadow: 0 10px 25px rgba(0,0,0,0.2); overflow: hidden; animation: fadeIn 0.2s ease-out; }
        .modal-header { padding: 15px 20px; background: #fff; border-bottom: 1px solid #f1f5f9; display: flex; justify-content: space-between; align-items: center; font-weight: bold; font-size: 15px; }
        .modal-close { font-size: 20px; cursor: pointer; color: #94a3b8; border: none; background: none; }
        .modal-body { padding: 20px; font-size: 14px; line-height: 1.8; color: #334155; }
        .modal-body div { margin-bottom: 8px; }
        .modal-body strong { color: #64748b; display: inline-block; width: 100px; }

        .live-speed-box { display: flex; justify-content: center; gap: 15px; font-size: 12px; font-weight: 600; margin-top: 10px; border-top: 1px solid #f1f5f9; padding-top: 10px; }
        .speed-up { color: #2563eb; display: flex; align-items: center; gap: 4px; }
        .speed-down { color: #ef4444; display: flex; align-items: center; gap: 4px; }
        .speed-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }

        @keyframes fadeIn {
            from { transform: scale(0.95); opacity: 0; }
            to { transform: scale(1); opacity: 1; }
        }
    </style>
</head>
<body>

<nav class="navbar">
    <div class="logo"><i class="fa-solid fa-cloud"></i> CloudISP Portal</div>
    <div class="nav-links">
        <a href="index.php">Dashboard</a>
        <a href="all.php">Clients Panel</a>
        <a href="logout.php" style="color: #ef4444;">Logout (<?php echo htmlspecialchars($logged_in_name); ?>)</a>
    </div>
</nav>

<div class="container">
    <div class="header-section">
        <h2>সক্রিয় ইউজার (<?php echo count($active_users); ?>)</h2>
        <input type="text" id="searchInput" onkeyup="filterTable()" class="search-bar" placeholder="সার্চ করুন...">
    </div>

    <div class="card">
        <table id="userTable">
            <thead>
                <tr>
                    <th>#</th>
                    <th>User Name / ID</th>
                    <th>Name</th>
                    <th>IP Address</th>
                    <th>Uptime</th>
                    <th>Status</th>
                    <th>Expiry Date</th>
                    <th>অ্যাকশন</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $count = 1;
                foreach($active_users as $user): 
                    $statusClass = (strtolower($user['status']) == 'active') ? 'status-active' : 'status-inactive';
                    $fullNameDisplay = !empty($user['full_name']) ? $user['full_name'] : $user['customer_id'];
                    // ড্রপডাউন আইডি সঠিকভাবে ইউনিক করার জন্য $count ভ্যারিয়েবলটি লুপের ভেতরে ব্যবহার করা হয়েছে
                    $dropdownId = "drop-" . $count;
                ?>
                <tr>
                    <td><?php echo $count; ?></td>
                    <td><strong><?php echo $user['customer_id']; ?></strong></td>
                    <td><?php echo $user['full_name']; ?></td>
                    <td><span class="badge ip"><?php echo $user['address']; ?></span></td>
                    <td><?php echo $user['uptime']; ?></td>
                    <td><span class="badge <?php echo $statusClass; ?>"><?php echo ucfirst($user['status']); ?></span></td>
                    <td><?php echo !empty($user['expiry_date']) ? date("d-M-Y", strtotime($user['expiry_date'])) : 'N/A'; ?></td>
                    <td>
                        <div class="dropdown">
                            <button onclick="toggleDropdown(event, '<?php echo $dropdownId; ?>')" class="btn-action">•••</button>
                            <div id="<?php echo $dropdownId; ?>" class="dropdown-content">
                                <button onclick="openPingModal('<?php echo htmlspecialchars($user['customer_id']); ?>', '<?php echo htmlspecialchars($user['address']); ?>')">⚡ Live Ping</button>
                                <button onclick="openBandwidthModal('<?php echo htmlspecialchars($user['customer_id']); ?>', '<?php echo htmlspecialchars($fullNameDisplay); ?>')">📊 Live Traffic</button>
                                <button onclick="alert('ম্যাক-বাইন্ডিং ফিচারটি প্রক্রিয়াধীন।')">🔒 MAC-Binding</button>
                                
                                <?php if($user_role === 'Super Admin' && strtolower($user['status']) !== 'active'): ?>
                                    <a href="kick_user.php?username=<?php echo urlencode($user['customer_id']); ?>" 
                                       onclick="return confirm('এই ইউজারকে কি সত্যিই ডিসকানেক্ট করতে চান?');" style="color: #fee2e2;">❌ সংযোগ বিচ্ছিন্ন</a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </td>
                </tr>
                <?php 
                $count++; 
                endforeach; 
                ?>
            </tbody>
        </table>
    </div>
</div>

<div id="pingModal" class="modal">
    <div class="modal-content" style="width: 400px;">
        <div class="modal-header">
            <span id="pingTitle">পিং মনিটর</span>
            <button class="modal-close" onclick="closeModal('pingModal')">&times;</button>
        </div>
        <div class="modal-body">
            <div><strong>Mikrotik:</strong> Router Server</div>
            <div><strong>Host:</strong> <span id="pingIp"></span></div>
            <div><strong>Lost Ping:</strong> 0</div>
            <div><strong>Up Time:</strong> 1ms513us</div>
        </div>
    </div>
</div>

<div id="bandwidthModal" class="modal">
    <div class="modal-content" style="width: 500px;">
        <div class="modal-header">
            <span id="bandwidthTitle">ব্যান্ডউইথ গ্রাফ</span>
            <button class="modal-close" onclick="closeModal('bandwidthModal')">&times;</button>
        </div>
        <div class="modal-body">
            <div id="chartContainer" style="height: 250px; width: 100%; display: block;"></div>
            <div class="live-speed-box">
                <span class="speed-up">
                    <span class="speed-dot" style="background-color: #2563eb;"></span>
                    Upload: <span id="liveUpload">0.00 Mbps</span>
                </span>
                <span class="speed-down">
                    <span class="speed-dot" style="background-color: #ef4444;"></span>
                    Download: <span id="liveDownload">0.00 Mbps</span>
                </span>
            </div>
        </div>
    </div>
</div>

<script>
function filterTable() {
    let filter = document.getElementById("searchInput").value.toUpperCase();
    let rows = document.getElementById("userTable").getElementsByTagName("tr");
    for (let i = 1; i < rows.length; i++) {
        rows[i].style.display = rows[i].innerText.toUpperCase().includes(filter) ? "" : "none";
    }
}

function toggleDropdown(event, id) {
    event.stopPropagation();
    closeAllDropdowns();
    document.getElementById(id).classList.toggle("show");
}

function closeAllDropdowns() {
    let dropdowns = document.getElementsByClassName("dropdown-content");
    for (let i = 0; i < dropdowns.length; i++) {
        dropdowns[i].classList.remove("show");
    }
}

function openPingModal(username, ip) {
    document.getElementById("pingTitle").innerText = username + " পিং";
    document.getElementById("pingIp").innerText = ip;
    document.getElementById("pingModal").style.display = "flex";
    closeAllDropdowns();
}

let chartInterval;
function openBandwidthModal(customerId, fullName) {
    document.getElementById("bandwidthTitle").innerText = fullName + " ব্যান্ডউইথ";
    document.getElementById("bandwidthModal").style.display = "flex";
    closeAllDropdowns();

    let dps = []; 
    let chart = new CanvasJS.Chart("chartContainer", {
        theme: "light2",
        title: { text: "Live Speed Usage", fontSize: 13, fontColor: "#64748b" },
        axisY: { title: "Speed (Mbps)", includeZero: true },
        axisX: { labelVisibilityMode: "none", tickLength: 0 },
        data: [{ 
            type: "area", 
            color: "rgba(37, 99, 235, 0.15)", 
            markerSize: 0, 
            lineThickness: 2, 
            lineColor: "#2563eb", 
            dataPoints: dps 
        }]
    });

    let xVal = 0;
    let updateInterval = 2000; 
    let dataLength = 25; 

    function updateChart() {
        // এখানে get_traffic.php ফাইলে ট্রাফিক ডাটা রিকোয়েস্ট পাঠানো হচ্ছে
        fetch(`get_traffic.php?customer_id=${encodeURIComponent(customerId)}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    let download = parseFloat(data.download);
                    let upload = parseFloat(data.upload);

                    dps.push({ x: xVal, y: download });
                    xVal++;

                    if (dps.length > dataLength) { dps.shift(); }
                    chart.render();

                    if (upload < 1) {
                        document.getElementById("liveUpload").innerText = (upload * 1024).toFixed(2) + " Kbps";
                    } else {
                        document.getElementById("liveUpload").innerText = upload.toFixed(2) + " Mbps";
                    }

                    if (download < 1) {
                        document.getElementById("liveDownload").innerText = (download * 1024).toFixed(2) + " Kbps";
                    } else {
                        document.getElementById("liveDownload").innerText = download.toFixed(2) + " Mbps";
                    }
                } else {
                    console.error("Traffic Error:", data.message);
                }
            })
            .catch(err => console.error("Fetch Error:", err));
    }

    setTimeout(updateChart, 400);
    chartInterval = setInterval(updateChart, updateInterval);
}

function closeModal(id) {
    document.getElementById(id).style.display = "none";
    if (id === 'bandwidthModal') {
        clearInterval(chartInterval);
    }
}

window.onclick = function(event) {
    closeAllDropdowns();
    if (event.target.classList.contains('modal')) {
        event.target.style.display = "none";
        clearInterval(chartInterval);
    }
}
</script>
</body>
</html>
