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

date_default_timezone_set('Asia/Dhaka'); 

// ৩. কাস্টমার এবং স্ট্যাটাস আপডেট লজিক (নিরাপত্তার জন্য isp_id ভ্যালিডেশন সহ)
if (isset($_POST['update_customer'])) {
    if ($user_role !== 'Super Admin') {
        $_SESSION['msg_error'] = "আপনার এই কাজটি করার অনুমতি নেই!";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    $cid     = mysqli_real_escape_string($conn, $_POST['customer_id']);
    $name    = mysqli_real_escape_string($conn, $_POST['name']);
    $phone   = mysqli_real_escape_string($conn, $_POST['phone']);
    $password = mysqli_real_escape_string($conn, $_POST['password']); 
    $area    = mysqli_real_escape_string($conn, $_POST['area']); 
    $address = mysqli_real_escape_string($conn, $_POST['address']);
    $bill    = mysqli_real_escape_string($conn, $_POST['bill_amount']);
    $expiry  = mysqli_real_escape_string($conn, $_POST['expiry_date']);
    $status  = mysqli_real_escape_string($conn, $_POST['status']);

    // ডাটাবেস আপডেট (WHERE ক্লজে isp_id যুক্ত করা হয়েছে যাতে নিজের কাস্টমার ছাড়া অন্য কারও ডাটা এডিট না হয়)
    $update_sql = "UPDATE customers SET 
                   name = '$name', 
                   phone = '$phone', 
                   password = '$password',
                   area = '$area',
                   address = '$address', 
                   bill_amount = '$bill', 
                   expiry_date = '$expiry',
                   status = '$status'
                   WHERE customer_id = '$cid' AND isp_id = '$current_isp_id'";
    
    if (mysqli_query($conn, $update_sql)) {
        $api = new RouterosAPI();
        if ($api->connect($m_ip, $m_user, $m_pass, $m_port)) {
            $user_data = $api->comm("/ppp/secret/print", array("?name" => $cid));
            if (!empty($user_data)) {
                $mid = $user_data[0][".id"];
                if ($status == 'deactivated' || $status == 'deactive') {
                    $api->comm("/ppp/secret/disable", array(".id" => $mid));
                    $active_user = $api->comm("/ppp/active/print", array("?name" => $cid));
                    if (!empty($active_user)) {
                        $api->comm("/ppp/active/remove", array(".id" => $active_user[0][".id"]));
                    }
                } else {
                    $api->comm("/ppp/secret/enable", array(".id" => $mid));
                }
            }
            $api->disconnect();
        }
        $_SESSION['msg'] = "Customer & Status updated successfully!";
    }
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// ৪. কুইক অ্যাকশন (একটিভ / ডি-একটিভ লজিক)
if (isset($_GET['action']) && isset($_GET['id'])) {
    if ($user_role !== 'Super Admin') {
        $_SESSION['msg_error'] = "আপনার এই কাজটি করার অনুমতি নেই!";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    $cid = mysqli_real_escape_string($conn, $_GET['id']);
    $action = $_GET['action']; 

    // সিকিউরিটি চেক: কাস্টমারটি এই আইএসপি-র কিনা তা নিশ্চিত হওয়া
    $check_cust = mysqli_query($conn, "SELECT id FROM customers WHERE customer_id = '$cid' AND isp_id = '$current_isp_id'");
    if (mysqli_num_rows($check_cust) > 0) {
        $api = new RouterosAPI();
        if ($api->connect($m_ip, $m_user, $m_pass, $m_port)) {
            $user_data = $api->comm("/ppp/secret/print", array("?name" => $cid));
            if (!empty($user_data)) {
                $mid = $user_data[0][".id"];
                if ($action == 'deactive') {
                    $api->comm("/ppp/secret/disable", array(".id" => $mid));
                    $active_user = $api->comm("/ppp/active/print", array("?name" => $cid));
                    if (!empty($active_user)) {
                        $api->comm("/ppp/active/remove", array(".id" => $active_user[0][".id"]));
                    }
                    mysqli_query($conn, "UPDATE customers SET status = 'deactivated' WHERE customer_id = '$cid' AND isp_id = '$current_isp_id'");
                    $_SESSION['msg'] = "Deactivated successfully!";
                } else {
                    $api->comm("/ppp/secret/enable", array(".id" => $mid));
                    mysqli_query($conn, "UPDATE customers SET status = 'active' WHERE customer_id = '$cid' AND isp_id = '$current_isp_id'");
                    $_SESSION['msg'] = "Activated successfully!";
                }
            }
            $api->disconnect();
        }
    }
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// ৫. ডিলিট ফাংশন (আইএসপি আইসোলেশন সহ)
if (isset($_GET['delete'])) {
    if ($user_role !== 'Super Admin') {
        $_SESSION['msg_error'] = "আপনার এই কাজটি করার অনুমতি নেই!";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    $cid = mysqli_real_escape_string($conn, $_GET['delete']);
    
    // নিজের কাস্টমার কিনা যাচাই করা
    $check_cust = mysqli_query($conn, "SELECT id FROM customers WHERE customer_id = '$cid' AND isp_id = '$current_isp_id'");
    if (mysqli_num_rows($check_cust) > 0) {
        $api = new RouterosAPI();
        if ($api->connect($m_ip, $m_user, $m_pass, $m_port)) {
            $user_data = $api->comm("/ppp/secret/print", array("?name" => $cid));
            if (!empty($user_data)) {
                $api->comm("/ppp/secret/remove", array(".id" => $user_data[0][".id"]));
            }
            $api->disconnect();
        }
        mysqli_query($conn, "DELETE FROM customers WHERE customer_id = '$cid' AND isp_id = '$current_isp_id'");
        $_SESSION['msg'] = "Customer deleted successfully!";
    }
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// এডিট ডাটা ফেচ (শুধুমাত্র নিজের আইএসপি এর ডেটা আসবে)
$edit_data = null;
if (isset($_GET['edit_id']) && $user_role === 'Super Admin') {
    $eid = mysqli_real_escape_string($conn, $_GET['edit_id']);
    $res = mysqli_query($conn, "SELECT * FROM customers WHERE customer_id = '$eid' AND isp_id = '$current_isp_id'");
    $edit_data = mysqli_fetch_assoc($res);
}

// এরিয়া লিস্ট ড্রপডাউন (আইএসপি ভিত্তিক এরিয়া ফিল্টারিং এর জন্য, এরিয়া টেবিলেও isp_id থাকা আবশ্যক)
// যদি আপনার 'area_list' টেবিলে isp_id থাকে তবে নিচের কুয়েরি ব্যবহার করুন, অন্যথায় রানিং কুয়েরি রাখুন।
$area_list_query = mysqli_query($conn, "SELECT * FROM area_list WHERE isp_id = '$current_isp_id' ORDER BY area_name ASC");
$areas_for_filter = [];
while($a_row = mysqli_fetch_assoc($area_list_query)) {
    $areas_for_filter[] = $a_row;
}

// শুধুমাত্র বর্তমান আইএসপির কাস্টমার লিস্ট লোড করা হচ্ছে
$customers = mysqli_query($conn, "SELECT * FROM customers WHERE isp_id = '$current_isp_id' ORDER BY id ASC");
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer Management | 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">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <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 ease; 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; transition: 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; }
        
        .main-content { flex: 1; display: flex; flex-direction: column; height: 100%; overflow: hidden; 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 { font-size: 22px; cursor: pointer; color: var(--dark); padding: 5px 10px; border-radius: 6px; }
        
        .search-box { margin-left: 20px; flex: 1; max-width: 300px; }
        .search-box input { padding: 10px 16px; border-radius: 8px; border: 1px solid #e5e7eb; width: 100%; outline: none; }
        .area-filter-box { margin-left: 15px; }
        .area-filter-box select { padding: 10px 16px; border-radius: 8px; border: 1px solid #e5e7eb; background-color: #fff; cursor: pointer; min-width: 180px; }

        .dashboard-body { padding: 40px; overflow-y: auto; flex: 1; }
        .edit-section { background: #fff; padding: 25px; border-radius: 12px; margin-bottom: 30px; border: 2px solid var(--primary); box-shadow: 0 4px 15px rgba(79, 70, 229, 0.1); }
        .edit-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; margin-top: 15px; }
        .form-input { display: flex; flex-direction: column; }
        .form-input label { font-size: 12px; font-weight: 600; color: #4b5563; margin-bottom: 5px; }
        .form-input input, .form-input select { padding: 10px; border: 1px solid #ddd; border-radius: 8px; outline: none; font-size: 14px; }
        
        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; }
        .page-header h2 { font-size: 22px; font-weight: 700; color: var(--dark); }
        .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 #cbd5e1; }
        table { width: 100%; border-collapse: collapse; min-width: 1000px; }
        th, td { padding: 16px 20px; text-align: left; border: 1px solid #cbd5e1; white-space: nowrap; }
        th { background: #f1f5f9; font-size: 12px; color: #334155; font-weight: 700; text-transform: uppercase; border-bottom: 2px solid #94a3b8; }
        tr:hover td { background-color: #e2e8f0 !important; }
        
        .badge { padding: 6px 12px; border-radius: 20px; font-size: 11px; font-weight: 600; }
        .badge-active { background: #d1fae5; color: #065f46; }
        .badge-expired { background: #fee2e2; color: #991b1b; }
        
        .btn-action { padding: 6px 12px; border-radius: 6px; text-decoration: none; font-size: 11px; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 4px; margin-right: 5px; }
        .btn-del { background: var(--danger); color: white; }
        .btn-active { background: var(--success); color: white; }
        .btn-deactive { background: var(--warning); color: white; }
        .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> SaaS ISP Portal</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 active"><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"><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 as: <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 style="display: flex; align-items: center; width: 100%;">
            <div class="menu-toggle" onclick="toggleSidebar()"><i class="fa-solid fa-bars"></i></div>
            <div class="search-box"><input type="text" id="searchInput" onkeyup="searchTable()" placeholder="কাস্টমার সার্চ করুন..."></div>
            <div class="area-filter-box">
                <select id="areaFilter" onchange="searchTable()">
                    <option value="">সব এরিয়া (All Areas)</option>
                    <?php foreach ($areas_for_filter as $area_row): ?>
                        <option value="<?php echo htmlspecialchars($area_row['area_name']); ?>">
                            <?php echo htmlspecialchars($area_row['area_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
    </header>

    <div class="dashboard-body">
        
        <?php if ($edit_data && $user_role === 'Super Admin'): ?>
        <div class="edit-section">
            <h3 style="margin: 0 0 5px 0; color: var(--primary); font-size: 16px;"><i class="fa-regular fa-pen-to-square"></i> Update Profile: <?php echo $edit_data['customer_id']; ?></h3>
            <form method="POST">
                <input type="hidden" name="customer_id" value="<?php echo $edit_data['customer_id']; ?>">
                <div class="edit-grid">
                    <div class="form-input"><label>Full Name</label><input type="text" name="name" value="<?php echo $edit_data['name']; ?>" required></div>
                    <div class="form-input"><label>Phone</label><input type="text" name="phone" value="<?php echo $edit_data['phone']; ?>" required></div>
                    <div class="form-input"><label>Password</label><input type="text" name="password" value="<?php echo $edit_data['password'] ?? ''; ?>"></div>
                    <div class="form-input">
                        <label>Area</label>
                        <select name="area">
                            <option value="">Select Area</option>
                            <?php foreach ($areas_for_filter as $area_row): ?>
                                <option value="<?php echo htmlspecialchars($area_row['area_name']); ?>" <?php echo ($edit_data['area'] == $area_row['area_name']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($area_row['area_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-input"><label>Address</label><input type="text" name="address" value="<?php echo $edit_data['address']; ?>"></div>
                    <div class="form-input"><label>Bill (TK)</label><input type="number" name="bill_amount" value="<?php echo $edit_data['bill_amount']; ?>" required></div>
                    <div class="form-input"><label>Expiry Date</label><input type="date" name="expiry_date" value="<?php echo $edit_data['expiry_date']; ?>" required></div>
                    <div class="form-input">
                        <label>Status</label>
                        <select name="status">
                            <option value="active" <?php echo ($edit_data['status'] == 'active') ? 'selected' : ''; ?>>Active</option>
                            <option value="deactivated" <?php echo ($edit_data['status'] == 'deactivated' || $edit_data['status'] == 'deactive') ? 'selected' : ''; ?>>Deactive</option>
                        </select>
                    </div>
                    <div style="display: flex; align-items: flex-end; gap: 15px;">
                        <button type="submit" name="update_customer" class="btn-save"><i class="fa-solid fa-floppy-disk"></i> Update</button>
                        <a href="?" style="text-decoration:none; color:#6b7280; font-size:14px; margin-bottom:18px;">Close</a>
                    </div>
                </div>
            </form>
        </div>
        <?php endif; ?>

        <div class="page-header">
            <h2>Customer Management Panel</h2>
            <?php if ($user_role === 'Super Admin'): ?>
                <a href="export.php" class="btn-csv"><i class="fa-solid fa-file-csv"></i> Export CSV</a>
            <?php endif; ?>
        </div>

        <div class="table-box">
            <table id="customerTable">
                <thead>
                    <tr>
                        <th>User ID (Edit)</th>
                        <th>Name</th>
                        <th>Phone</th>
                        <th>Password</th>
                        <th>Area</th>
                        <th>Address</th>
                        <th>Package</th>
                        <th>Bill</th>
                        <th>Expiry</th>
                        <th>Status</th>
                        <?php if($user_role === 'Super Admin'): ?><th>Actions</th><?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    while($row = mysqli_fetch_assoc($customers)): 
                        $row_bg = ($row['status'] == 'active') ? 'rgba(16, 185, 129, 0.06)' : 'rgba(239, 68, 68, 0.06)';
                    ?>
                    <tr style="background-color: <?php echo $row_bg; ?>;">
                        <td>
                            <?php if ($user_role === 'Super Admin'): ?>
                                <a href="?edit_id=<?php echo $row['customer_id']; ?>" style="text-decoration: none; color: var(--primary); font-weight: 700; border-bottom: 1px dashed var(--primary);">
                                    <?php echo $row['customer_id']; ?> <i class="fa-regular fa-pen-to-square" style="font-size:11px;"></i>
                                </a>
                            <?php else: ?>
                                <strong style="color: var(--dark);"><?php echo $row['customer_id']; ?></strong>
                            <?php endif; ?>
                        </td>
                        <td><strong><?php echo $row['name']; ?></strong></td>
                        <td><?php echo $row['phone']; ?></td> 
                        <td><?php echo $row['password']; ?></td> 
                        <td><?php echo $row['area']; ?></td> 
                        <td><?php echo $row['address']; ?></td> 
                        <td><?php echo $row['package']; ?></td> 
                        <td><strong><?php echo number_format($row['bill_amount'], 0); ?></strong> TK</td>
                        <td><?php echo date("d-M-Y", strtotime($row['expiry_date'])); ?></td>
                        <td><span class="badge <?php echo ($row['status'] == 'active') ? 'badge-active' : 'badge-expired'; ?>"><?php echo $row['status']; ?></span></td>
                        
                        <?php if($user_role === 'Super Admin'): ?>
                        <td>
                            <?php if($row['status'] == 'active'): ?>
                                <a onclick="confirmAction('?action=deactive&id=<?php echo $row['customer_id']; ?>', 'Disable this user?', 'warning')" class="btn-action btn-deactive"><i class="fa-solid fa-ban"></i> Disable</a>
                            <?php else: ?>
                                <a onclick="confirmAction('?action=active&id=<?php echo $row['customer_id']; ?>', 'Enable this user?', 'question')" class="btn-action btn-active"><i class="fa-solid fa-circle-check"></i> Enable</a>
                            <?php endif; ?>
                            <a onclick="confirmAction('?delete=<?php echo $row['customer_id']; ?>', 'Are you sure to delete?', 'error')" class="btn-action btn-del"><i class="fa-solid fa-trash"></i> Del</a>
                        </td>
                        <?php endif; ?>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

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

function searchTable() {
    let searchInput = document.getElementById("searchInput").value.toUpperCase();
    let areaFilter = document.getElementById("areaFilter").value.toUpperCase();
    let table = document.getElementById("customerTable");
    let tr = table.getElementsByTagName("tr");

    for (let i = 1; i < tr.length; i++) {
        let rowText = tr[i].innerText.toUpperCase();
        let areaCell = tr[i].getElementsByTagName("td")[3];
        let areaText = areaCell ? areaCell.innerText.toUpperCase() : "";

        let matchesSearch = rowText.indexOf(searchInput) > -1;
        let matchesArea = areaFilter === "" || areaText === areaFilter;

        tr[i].style.display = (matchesSearch && matchesArea) ? "" : "none";
    }
}

function confirmAction(url, title, icon = 'question') {
    Swal.fire({
        title: title, icon: icon, showCancelButton: true, confirmButtonColor: '#4f46e5', cancelButtonColor: '#ef4444', confirmButtonText: 'Yes, Confirm', cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) { window.location.href = url; }
    })
}

<?php if(isset($_SESSION['msg'])): ?>
    Swal.fire({ icon: 'success', title: 'Done!', text: '<?php echo $_SESSION['msg']; ?>', timer: 1500, showConfirmButton: false });
<?php unset($_SESSION['msg']); endif; ?>

<?php if(isset($_SESSION['msg_error'])): ?>
    Swal.fire({ icon: 'error', title: 'Error!', text: '<?php echo $_SESSION['msg_error']; ?>' });
<?php unset($_SESSION['msg_error']); endif; ?>
</script>
</body>
</html>
