<?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']; // লগইন করা ISP এর ইউনিক আইডি
$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'); 

// ২. ডাটাবেস থেকে এই সুনির্দিষ্ট ISP এর মাইক্রোটিক ও হোয়াটসঅ্যাপ সেটিংস তুলে আনা
$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'];
$secret = $isp_settings['whatsapp_secret'];
$sim    = $isp_settings['whatsapp_sim'];

$api = new RouterosAPI();

// --- ১. অ্যাক্টিভেশন, ট্রানজেকশন ও প্রোফাইল রিস্টোর লজিক ---
if (isset($_POST['activate_customer'])) {
    $cid = mysqli_real_escape_string($conn, $_POST['customer_id']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $trx_id = mysqli_real_escape_string($conn, $_POST['trx_id']);
    $today_time = date('Y-m-d H:i:s'); 

    // সুরক্ষার জন্য এখানেও isp_id চেক রাখা হয়েছে যাতে অন্য কারও কাস্টমার একটিভ না হয়
    $res = mysqli_query($conn, "SELECT name, phone, expiry_date, package FROM customers WHERE customer_id = '$cid' AND isp_id = '$current_isp_id' LIMIT 1");
    $user_info = mysqli_fetch_assoc($res);
    
    if ($user_info) {
        $cust_name = $user_info['name'];
        $cust_phone = $user_info['phone']; 
        $user_profile = (!empty($user_info['package'])) ? $user_info['package'] : "default";

        if ($api->connect($m_ip, $m_user, $m_pass, $m_port)) {
            
            $api->comm("/ppp/secret/set", array(
                "numbers" => $cid, 
                "disabled" => "no",
                "profile" => $user_profile
            ));
            
            $online = $api->comm("/ppp/active/print", array("?name" => $cid));
            if (!empty($online)) {
                $api->comm("/ppp/active/remove", array(".id" => $online[0][".id"]));
            }
            
            $api->disconnect();
            
            // ট্রানজেকশনে isp_id সেভ করা হচ্ছে
            mysqli_query($conn, "INSERT INTO transactions (isp_id, customer_id, amount, payment_method, trx_id, payment_date) 
                                VALUES ('$current_isp_id', '$cid', '$amount', '$method', '$trx_id', '$today_time')");

            // কাস্টমার আপডেটেও নিরাপত্তা নিশ্চিত করা হয়েছে
            mysqli_query($conn, "UPDATE customers SET 
                                status='active', 
                                expiry_date = DATE_ADD(expiry_date, INTERVAL 1 MONTH),
                                last_reminder_date = NULL 
                                WHERE customer_id = '$cid' AND isp_id = '$current_isp_id'");
            
            $updated_res = mysqli_query($conn, "SELECT expiry_date FROM customers WHERE customer_id = '$cid' AND isp_id = '$current_isp_id'");
            $updated_info = mysqli_fetch_assoc($updated_res);
            $new_expiry = date("d-M-Y", strtotime($updated_info['expiry_date']));

            // মেসেজ গেটওয়ে লজিক (ডাইনামিক সিক্রেট সহ)
            if(!empty($cust_phone)) {
                $clean_phone = preg_replace('/[^0-9]/', '', $cust_phone);
                if (strlen($clean_phone) == 11 && substr($clean_phone, 0, 2) == '01') {
                    $clean_phone = '88' . $clean_phone;
                }

                $msg = "Dear\n$cust_name\nYour internet bill of $amount taka has been paid\nYour next connection will expire on $new_expiry .\nThanks For Using Our Internet.";
                
                $sms_url = "https://wa.nux.my.id/api/sendSMS?to=" . urlencode($clean_phone) . 
                           "&msg=" . urlencode($msg) . 
                           "&sim=" . urlencode($sim) . 
                           "&secret=" . urlencode($secret);
                
                $response = @file_get_contents($sms_url);
                $status = ($response !== false) ? 'success' : 'failed';
                
                $safe_msg = mysqli_real_escape_string($conn, $msg);
                $safe_response = mysqli_real_escape_string($conn, $response);
                
                mysqli_query($conn, "INSERT INTO sms_logs (isp_id, customer_id, phone, message, status, response_text, cost, sent_at) 
                                    VALUES ('$current_isp_id', '$cid', '$clean_phone', '$safe_msg', '$status', '$safe_response', '0.00', '$today_time')");
            }
        }
    }
    header("Location: index.php"); exit();
}

// --- ২. ডি-অ্যাক্টিভেশন লজিক (ম্যানুয়াল充 ব্লক) ---
if (isset($_GET['action']) && $_GET['action'] == 'deactivate' && isset($_GET['cid'])) {
    $cid = mysqli_real_escape_string($conn, $_GET['cid']);
    if ($api->connect($m_ip, $m_user, $m_pass, $m_port)) {
        $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"])); }
        mysqli_query($conn, "UPDATE customers SET status='deactivated' WHERE customer_id = '$cid' AND isp_id = '$current_isp_id'");
        $api->disconnect();
    }
    header("Location: index.php"); exit();
}

// --- ৩. পরিসংখ্যান (আইএসপি ফিল্টার সহ) ---
$online_count = 0;
if ($api->connect($m_ip, $m_user, $m_pass, $m_port)) {
    $active_sessions = $api->comm("/ppp/active/print");
    $online_names = array_column($active_sessions, 'name');

    if (!empty($online_names)) {
        $ids = "'" . implode("', '", $online_names) . "'";
        $query = "SELECT COUNT(*) as t FROM customers WHERE customer_id IN ($ids) AND status='active' AND isp_id = '$current_isp_id'";
        $result = mysqli_query($conn, $query);
        $data = mysqli_fetch_assoc($result);
        $online_count = $data['t'];
    }
    $api->disconnect();
}

$bd_today = date('Y-m-d');
$bd_month = date('m');
$bd_year  = date('Y');

$total_clients_all = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as t FROM customers WHERE isp_id = '$current_isp_id'"))['t'] ?? 0;
$active_db = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as t FROM customers WHERE status='active' AND isp_id = '$current_isp_id'"))['t'];
$expired_db = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as t FROM customers WHERE status='deactivated' AND isp_id = '$current_isp_id'"))['t'];

// রোল ভিত্তিক কন্ডিশন (শুধুমাত্র নিজের আইএসপি-এর হিসাব দেখতে পাবে)
if ($user_role === 'Super Admin') {
    $total_bill = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(bill_amount) as t FROM customers WHERE isp_id = '$current_isp_id'"))['t'] ?? 0;
    $monthly_collect = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as t FROM transactions WHERE MONTH(payment_date) = '$bd_month' AND YEAR(payment_date) = '$bd_year' AND isp_id = '$current_isp_id'"))['t'] ?? 0;
} else {
    $total_bill = 0;
    $monthly_collect = 0;
}

$today_collect = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as t FROM transactions WHERE DATE(payment_date) = '$bd_today' AND isp_id = '$current_isp_id'"))['t'] ?? 0;

// সার্চ কুয়েরি মডিফিকেশন
$search = mysqli_real_escape_string($conn, $_GET['search'] ?? '');
$where = "WHERE isp_id = '$current_isp_id'";
if ($search) {
    $where .= " AND (customer_id LIKE '%$search%' OR name LIKE '%$search%')";
}
$customers = mysqli_query($conn, "SELECT * FROM customers $where 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>SaaS ISP - Dashboard</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 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; position: relative; }
        .sidebar-item a:hover, .sidebar-item.active a { color: #fff; background: var(--sidebar-hover); border-left: 4px solid var(--primary); }
        .side-badge { position: absolute; right: 20px; background: var(--success); color: white; font-size: 11px; padding: 2px 7px; border-radius: 10px; }
        .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; }
        .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; }
        .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%; outline: none; }
        .dashboard-body { padding: 40px; overflow-y: auto; flex: 1; }
        .stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 25px; }
        
        /* কার্ড বা বক্স এর CSS ডিজাইন আপডেট */
        .card { background: white; padding: 24px; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); text-decoration: none; color: inherit; transition: 0.2s; border: 1px solid #f3f4f6; display: block; cursor: pointer; }
        .card:hover { transform: translateY(-3px); box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        
        .card-title { font-size: 13px; color: #6b7280; text-transform: uppercase; font-weight: 600; }
        .card-value { font-size: 26px; font-weight: 700; margin-top: 10px; display: flex; align-items: center; justify-content: space-between; }
        .card-icon { padding: 10px; border-radius: 8px; font-size: 20px; }
        .action-bar { display: flex; justify-content: flex-end; margin-bottom: 20px; }
        .btn-add { background: var(--primary); color: white; padding: 10px 20px; 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: 900px; }
        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 { 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-act { background: #eef2ff; color: var(--primary); padding: 8px 14px; border-radius: 6px; font-size: 12px; font-weight: 600; cursor: pointer; border: 1px solid #e0e7ff; }
        .modal { display: none; position: fixed; z-index: 1005; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); backdrop-filter: blur(4px); }
        .modal-content { background: white; margin: 6% auto; padding: 30px; border-radius: 16px; width: 90%; max-width: 420px; }
        .form-group { margin-top: 16px; }
        .form-group label { display: block; margin-bottom: 6px; font-size: 12px; color: #4b5563; font-weight: 600; }
        .form-group input, .form-group select { width: 100%; padding: 11px; border: 1px solid #d1d5db; border-radius: 8px; }
        .btn-save { background: var(--success); color: white; width: 100%; padding: 12px; border-radius: 8px; font-weight: 600; margin-top: 24px; border: none; cursor: pointer; }
        .sidebar-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.4); z-index: 995; }
        .sidebar-overlay.active { display: block; }
        @media (max-width: 1024px) { .stats-grid { grid-template-columns: repeat(2, 1fr); } }
    </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-wifi"></i> Zara It Co.</a>
        <ul class="sidebar-menu">
            <li class="sidebar-item active"><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 <span class="side-badge"><?php echo $active_db; ?></span></a></li>
            <li class="sidebar-item"><a href="live_clients.php"><i class="fa-solid fa-circle-dot" style="color: #10b981;"></i> Total Live Online</a></li>
            <li class="sidebar-item"><a href="deactivated.php"><i class="fa-solid fa-user-slash"></i> Expired</a></li>
            <li class="sidebar-item"><a href="edit_profile.php"><i class="fa-solid fa-user-edit"></i> Site Manage</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 style="display: flex; align-items: center;">
            <div class="menu-toggle" onclick="toggleSidebar()"><i class="fa-solid fa-bars"></i></div>
            <form method="GET" class="search-box"><input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Search clients and press enter..."></form>
        </div>
        <div style="font-weight: 600; font-size: 14px; color: var(--primary);"><i class="fa-regular fa-clock"></i> Tenant Session Active</div>
    </header>

    <div class="dashboard-body">
        
        <div class="stats-grid">
            <a href="all.php" class="card">
                <div class="card-title">Total Clients</div>
                <div class="card-value"><?php echo $total_clients_all; ?> <i class="fa-solid fa-users card-icon" style="background:#e0e7ff; color:var(--primary);"></i></div>
            </a>
            <a href="active.php" class="card">
                <div class="card-title">Total Active</div>
                <div class="card-value"><?php echo $active_db; ?><i class="fa-solid fa-user-check card-icon" style="background:#d1fae5; color:var(--success);"></i></div>
            </a>
            <a href="live_clients.php" class="card">
                <div class="card-title">Live Online</div>
                <div class="card-value"><?php echo $online_count; ?><i class="fa-solid fa-globe card-icon" style="background:#dbeafe; color:#3b82f6;"></i></div>
            </a>
            <a href="deactivated.php" class="card">
                <div class="card-title">Expired</div>
                <div class="card-value"><?php echo $expired_db; ?><i class="fa-solid fa-user-slash card-icon" style="background:#fee2e2; color:var(--danger);"></i></div>
            </a>
        </div>

        <div class="stats-grid">
            <div class="card" style="cursor: default;">
                <div class="card-title">Total Bill</div>
                <div class="card-value"><?php echo number_format($total_bill, 0); ?> TK</div>
            </div>
            <div class="card" style="cursor: default;">
                <div class="card-title">Today Collect</div>
                <div class="card-value"><?php echo number_format($today_collect, 0); ?> TK</div>
            </div>
            <div class="card" style="cursor: default;">
                <div class="card-title">Monthly Collect</div>
                <div class="card-value"><?php echo number_format($monthly_collect, 0); ?> TK</div>
            </div>
            <div class="card" style="cursor: default;">
                <div class="card-title">WhatsApp Gateway</div>
                <div class="card-value" style="font-size: 16px; color: var(--success); font-weight: bold;"><i class="fa-solid fa-circle-check"></i> Connected</div>
            </div>
        </div>

        <div class="action-bar">
            <a href="add_customer.php" class="btn-add"><i class="fa-solid fa-plus"></i> Add New Customer</a>
        </div>

        <div class="table-box">
            <table>
                <thead>
                    <tr>
                        <th>Customer ID</th>
                        <th>Name</th>
                        <th>Phone</th>
                        <th>Address</th>
                        <th>Package</th>
                        <th>Bill Amount</th>
                        <th>Expiry Date</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?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 $row['phone']; ?></td> 
                        <td><?php echo $row['address']; ?></td> 
                        <td><?php echo $row['package']; ?></td> 
                        <td><strong><?php echo number_format($row['bill_amount'], 0); ?> TK</strong></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 strtoupper($row['status']); ?></span></td>
                        <td>
                            <button class="btn-act" onclick="openModal('<?php echo $row['customer_id']; ?>', '<?php echo $row['name']; ?>', '<?php echo $row['bill_amount']; ?>')"><i class="fa-solid fa-wallet"></i> Bill Collect</button>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<div id="payModal" class="modal">
    <div class="modal-content">
        <h2>বিল সংগ্রহ করুন</h2>
        <form method="POST" onsubmit="document.getElementById('loadingOverlay').style.display = 'flex';">
            <div class="form-group"><label>কাস্টমার আইডি</label><input type="text" name="customer_id" id="m_id" readonly></div>
            <div class="form-group"><label>কাস্টমারের নাম</label><input type="text" id="m_name" readonly></div>
            <div class="form-group"><label>বিল এর পরিমাণ (TK)</label><input type="number" name="amount" id="m_amount" required></div>
            <div class="form-group">
                <label>পেমেন্ট মাধ্যম</label>
                <select name="payment_method" required>
                    <option value="Cash">Cash (নগদ)</option>
                    <option value="bKash">bKash</option>
                    <option value="Nagad">Nagad</option>
                </select>
            </div>
            <div class="form-group"><label>ট্রানজেকশন আইডি (TrxID)</label><input type="text" name="trx_id" placeholder="ঐচ্ছিক"></div>
            <button type="submit" name="activate_customer" class="btn btn-save"><i class="fa-solid fa-check-double"></i> পেমেন্ট নিন ও একটিভ করুন</button>
            <button type="button" onclick="closeModal()" style="width:100%; background:none; border:none; color:#9ca3af; margin-top:15px; cursor:pointer;">বন্ধ করুন</button>
        </form>
    </div>
</div>

<div id="loadingOverlay" style="display:none; position:fixed; inset:0; z-index:9999; align-items:center; justify-content:center; background:rgba(255,255,255,0.8);">
    <div style="text-align:center;"><p style="font-weight:600; color:#4f46e5;">কাজ চলছে, অনুগ্রহ করে অপেক্ষা করুন...</p></div>
</div>

<script>
function toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('open');
    document.getElementById('sidebarOverlay').classList.toggle('active');
}
function openModal(id, name, bill) {
    document.getElementById('m_id').value = id;
    document.getElementById('m_name').value = name;
    document.getElementById('m_amount').value = bill;
    document.getElementById('payModal').style.display = 'block';
}
function closeModal() { document.getElementById('payModal').style.display = 'none'; }
</script>
</body>
</html>