<?php
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header("Location: login.php");
    exit;
}

$user_role = $_SESSION['role'] ?? 'Stuff';

include 'config.php';
include 'routeros_api.class.php';

$m_ip = "103.61.240.38"; 
$m_user = "test"; 
$m_pass = "test"; 
$m_port = 8729;

// ডাটাবেস থেকে কাস্টমারদের নাম ও এক্সপায়ারি ডেট নিয়ে আসা (ম্যাচিং এর জন্য)
$customerData = [];
$sql_names = "SELECT customer_id, name, status, expiry_date FROM customers";
$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();
$offline_secrets = [];

if ($api->connect($m_ip, $m_user, $m_pass, $m_port)) {
    // ১. মাইক্রোটিক থেকে সব 'Secret' (টোটাল ইউজার লিস্ট) আনা হচ্ছে
    $all_secrets = $api->comm("/ppp/secret/print");
    
    // ২. মাইক্রোটিক থেকে বর্তমানে 'Active' বা অনলাইন ইউজারদের আনা হচ্ছে
    $all_online = $api->comm("/ppp/active/print");
    $api->disconnect();
    
    // সহজে চেক করার জন্য একটিভ ইউজারদের নামের একটি অ্যারে তৈরি
    $online_usernames = [];
    foreach ($all_online as $online_user) {
        $online_usernames[] = $online_user['name'];
    }
    
    // ৩. লুপ চালিয়ে শুধুমাত্র অফলাইন সিক্রেটগুলো ফিল্টার করা
    foreach ($all_secrets as $secret) {
        $secret_name = $secret['name'];
        
        // যদি সিক্রেটটি বর্তমানে একটিভ (অনলাইন) লিস্টে না থাকে, তবেই সে অফলাইন
        if (!in_array($secret_name, $online_usernames)) {
            
            $last_logout = $secret['last-logged-out'] ?? 'unknown';
            $downtime_string = "N/A";
            
            // ডাউনটাইম বা কতক্ষণ ধরে অফলাইন আছে তা হিসাব করা
            if ($last_logout !== 'unknown' && $last_logout !== 'never') {
                $logout_time = strtotime($last_logout);
                if ($logout_time) {
                    $time_diff = time() - $logout_time;
                    
                    if ($time_diff > 0) {
                        $days = floor($time_diff / 86400);
                        $hours = floor(($time_diff % 86400) / 3600);
                        $minutes = floor(($time_diff % 3600) / 60);
                        
                        if ($days > 0) {
                            $downtime_string = "{$days}d {$hours}h {$minutes}m";
                        } elseif ($hours > 0) {
                            $downtime_string = "{$hours}h {$minutes}m";
                        } else {
                            $downtime_string = "{$minutes}m";
                        }
                    } else {
                        $downtime_string = "Just now";
                    }
                }
            } else if ($last_logout === 'never') {
                $downtime_string = "Never Connected";
            }
            
            // ডাটাবেসে তথ্য থাকলে তা নেওয়া, না থাকলে Mikrotik এর ডাটাই শো করবে
            $db_name = $customerData[$secret_name]['name'] ?? 'Not Found in DB';
            $db_status = $customerData[$secret_name]['status'] ?? 'N/A';
            $db_expiry = $customerData[$secret_name]['expiry_date'] ?? '';
            
            $offline_secrets[] = [
                'username' => $secret_name,
                'profile' => $secret['profile'] ?? 'default',
                'comment' => $secret['comment'] ?? '',
                'full_name' => $db_name,
                'status' => $db_status,
                'expiry_date' => $db_expiry,
                'last_logout' => $last_logout,
                'downtime' => $downtime_string
            ];
        }
    }
    
    // নাম অনুযায়ী সর্ট করা (A-Z)
    usort($offline_secrets, function($a, $b) {
        return strnatcasecmp($a['username'], $b['username']);
    });
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <title>Offline Secrets | RANGDHANU.NET</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    <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; }
        .badge { padding: 4px 10px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .badge-profile { background: #e0f2fe; color: #0369a1; }
        .badge-downtime { background: #fee2e2; color: #991b1b; font-weight: bold; border: 1px solid #fca5a5; }
        .status-active { background: #dcfce7; color: #166534; }
        .status-deactive { background: #f1f5f9; color: #475569; }
        .search-bar { padding: 10px 15px; border: 1px solid #cbd5e1; border-radius: 8px; width: 250px; }
    </style>
</head>
<body>

<nav class="navbar">
    <div class="logo">RANGDHANU.NET</div>
    <div class="nav-links">
        <a href="index.php">Dashboard</a>
        <a href="logout.php" style="color: #ef4444;">Logout</a>
    </div>
</nav>

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

    <div class="card">
        <table id="userTable">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Secret Name (ID)</th>
                    <th>Customer Name</th>
                    <th>Profile</th>
                    <th>Last Logged Out</th>
                    <th>Downtime (ডাউন টাইম)</th>
                    <th>DB Status</th>
                    <th>Expiry Date</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $count = 1;
                if(count($offline_secrets) > 0):
                    foreach($offline_secrets as $secret): 
                        $statusClass = (strtolower($secret['status']) == 'active') ? 'status-active' : 'status-deactive';
                ?>
                <tr>
                    <td><?php echo $count++; ?></td>
                    <td><strong><?php echo $secret['username']; ?></strong></td>
                    <td><?php echo $secret['full_name']; ?></td>
                    <td><span class="badge badge-profile"><?php echo $secret['profile']; ?></span></td>
                    <td style="color: #64748b; font-size: 13px;"><?php echo $secret['last_logout']; ?></td>
                    <td><span class="badge badge-downtime"><?php echo $secret['downtime']; ?></span></td>
                    <td><span class="badge <?php echo $statusClass; ?>"><?php echo ucfirst($secret['status']); ?></span></td>
                    <td><?php echo !empty($secret['expiry_date']) ? date("d-M-Y", strtotime($secret['expiry_date'])) : 'N/A'; ?></td>
                </tr>
                <?php 
                    endforeach; 
                else:
                ?>
                <tr>
                    <td colspan="8" style="text-align: center; color: #64748b; padding: 20px;">কোনো অফলাইন সিক্রেট পাওয়া যায়নি।</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </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";
    }
}
</script>
</body>
</html>
