<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/Customer.php';
require_once __DIR__ . '/../classes/Branch.php';
require_once __DIR__ . '/../classes/Bill.php';
require_once __DIR__ . '/../classes/MikroTik.php';

requireRole('super_admin', 'branch_admin');
$pageTitle = 'Data Pelanggan';

$db = db();

// ============================================================================
// 1. DETEKSI ROLE & BRANCH USER YANG SEDANG LOGIN
// ============================================================================
$currentUserId = currentUserId();
$currentUser = null;
$userRole = 'super_admin';
$userBranchId = null;
$userBranchName = 'Pusat';

try {
    $stmt = $db->prepare("SELECT id, username, name, role, branch_id FROM users WHERE id = ?");
    $stmt->execute([$currentUserId]);
    $currentUser = $stmt->fetch();
    
    if ($currentUser) {
        $userRole = $currentUser['role'] ?? 'super_admin';
        $userBranchId = !empty($currentUser['branch_id']) ? (int)$currentUser['branch_id'] : null;
    }
} catch (\Throwable $e) {
    $userRole = 'super_admin';
}

$isSuperAdmin = ($userRole === 'super_admin');
$isBranchAdmin = ($userRole === 'branch_admin');

$allBranches = Branch::all();
foreach ($allBranches as $b) {
    if ((int)$b['id'] === $userBranchId) {
        $userBranchName = $b['name'];
        break;
    }
}

// ============================================================================
// 2. AUTO-CHECK OVERDUE
// ============================================================================
try {
    if ($isSuperAdmin) {
        $overdueResult = Bill::processOverdue();
    } else {
        $overdueResult = Bill::processOverdue($userBranchId);
    }
    
    if ($overdueResult['marked'] > 0) {
        logActivity(currentUserId(), 'auto_suspend_overdue', 
            "Auto-suspend {$overdueResult['suspended']} customer overdue.");
        
        if (!isset($_SESSION['flash_message'])) {
            $_SESSION['flash_message'] = [
                'type' => 'warning',
                'message' => "⚠️ Auto-suspend: {$overdueResult['suspended']} customer di-suspend karena tagihan overdue."
            ];
        }
    }
} catch (\Throwable $e) {}

// ============================================================================
// 3. HANDLE ACTIONS (GET)
// ============================================================================
if (isset($_GET['action']) && isset($_GET['id']) && verifyCsrf($_GET['token'] ?? '')) {
    $action = $_GET['action'];
    $customerId = (int) $_GET['id'];
    $customer = Customer::find($customerId);
    
    if (!$customer) {
        redirect('/admin/customers.php', '❌ Customer tidak ditemukan', 'error');
    }
    
    if ($isBranchAdmin && (int)$customer['branch_id'] !== $userBranchId) {
        redirect('/admin/customers.php', '❌ Anda tidak memiliki akses ke pelanggan cabang lain!', 'error');
    }
    
    switch ($action) {
        case 'generate_bill':
            $result = Bill::generate($customerId);
            if ($result['success']) {
                logActivity(currentUserId(), 'generate_bill', 
                    "Generate tagihan #{$result['bill_number']} untuk {$customer['name']}");
                redirect('/admin/customers.php', 
                    "✅ Tagihan berhasil digenerate: {$result['bill_number']} - Rp " . number_format($result['amount']));
            } else {
                redirect('/admin/customers.php', '❌ ' . $result['error'], 'error');
            }
            break;
            
        case 'suspend':
            try {
                $mt = new MikroTik();
                $result = $mt->suspendCustomer($customer['pppoe_username']);
                if ($result['success']) {
                    Customer::update($customerId, ['status' => 'suspended']);
                    logActivity(currentUserId(), 'suspend_customer', "Suspend pelanggan: {$customer['name']}");
                    redirect('/admin/customers.php', '✅ Pelanggan berhasil di-suspend');
                } else {
                    redirect('/admin/customers.php', '❌ Gagal suspend: ' . $result['error'], 'error');
                }
            } catch (\Throwable $e) {
                redirect('/admin/customers.php', '❌ Error: ' . $e->getMessage(), 'error');
            }
            break;
            
        case 'restore':
            try {
                $mt = new MikroTik();
                $result = $mt->restoreCustomer($customer['pppoe_username']);
                if ($result['success']) {
                    Customer::update($customerId, ['status' => 'active']);
                    logActivity(currentUserId(), 'restore_customer', "Restore pelanggan: {$customer['name']}");
                    redirect('/admin/customers.php', '✅ Pelanggan berhasil di-restore');
                } else {
                    redirect('/admin/customers.php', '❌ Gagal restore: ' . $result['error'], 'error');
                }
            } catch (\Throwable $e) {
                redirect('/admin/customers.php', '❌ Error: ' . $e->getMessage(), 'error');
            }
            break;
            
        case 'delete':
            try {
                $mt = new MikroTik();
                $mt->removeSecret($customer['pppoe_username']);
            } catch (\Throwable $e) {}
            Customer::delete($customerId);
            logActivity(currentUserId(), 'delete_customer', "Hapus pelanggan #$customerId - {$customer['name']}");
            redirect('/admin/customers.php', '✅ Pelanggan berhasil dihapus');
            break;
    }
}

// ============================================================================
// 3.5. HANDLE MANUAL PAYMENT (POST FROM MODAL)
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_pay']) && verifyCsrf($_POST['csrf_token'] ?? '')) {
    $billId = (int) $_POST['bill_id'];
    $customerId = (int) ($_POST['customer_id'] ?? 0);
    $paymentMethod = $_POST['payment_method'] ?? 'Tunai';
    $category = $_POST['category'] ?? 'Pelunasan Tagihan';
    
    // CATATAN: Pastikan method Bill::pay() di classes/Bill.php sudah diupdate 
    // untuk menerima parameter $paymentMethod dan $category.
    $result = Bill::pay($billId, $paymentMethod, $category);
    
    if ($result['success']) {
        if ($customerId === 0 && isset($result['customer_id'])) {
            $customerId = (int) $result['customer_id'];
        }
        
        $customer = Customer::find($customerId);
        
        // 1. Customer di-restore (jika suspended)
        if ($customer && $customer['status'] === 'suspended') {
            try {
                $mt = new MikroTik();
                $mt->restoreCustomer($customer['pppoe_username']);
                Customer::update($customerId, ['status' => 'active']);
            } catch (\Throwable $e) {}
        }
        
        // 2. Auto-generate tagihan bulan depan (+1 bulan)
        // CATATAN: Pastikan ada method Bill::generateNextMonth($customerId) di classes/Bill.php
        if (method_exists('Bill', 'generateNextMonth')) {
            Bill::generateNextMonth($customerId);
        } else {
            Bill::generate($customerId); // Fallback
        }
        
        logActivity(currentUserId(), 'pay_bill', "Bayar manual tagihan #$billId via $paymentMethod ($category)");
        redirect('/admin/customers.php', '✅ Pembayaran berhasil dicatat & tagihan bulan depan digenerate');
    } else {
        redirect('/admin/customers.php', '❌ ' . $result['error'], 'error');
    }
}

// ============================================================================
// 4. HANDLE BULK ACTIONS
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action']) && verifyCsrf($_POST['csrf_token'] ?? '')) {
    $action = $_POST['bulk_action'];
    $selectedIds = $_POST['selected_customers'] ?? [];
    
    if (!empty($selectedIds)) {
        $successCount = 0;
        $failCount = 0;
        
        foreach ($selectedIds as $id) {
            $customer = Customer::find((int)$id);
            if (!$customer) continue;
            
            if ($isBranchAdmin && (int)$customer['branch_id'] !== $userBranchId) {
                $failCount++;
                continue;
            }
            
            try {
                switch ($action) {
                    case 'generate_bill':
                        $result = Bill::generate($id);
                        if ($result['success']) $successCount++;
                        else $failCount++;
                        break;
                        
                    case 'suspend':
                        $mt = new MikroTik();
                        $result = $mt->suspendCustomer($customer['pppoe_username']);
                        if ($result['success']) {
                            Customer::update($id, ['status' => 'suspended']);
                            $successCount++;
                        } else $failCount++;
                        break;
                        
                    case 'restore':
                        $mt = new MikroTik();
                        $result = $mt->restoreCustomer($customer['pppoe_username']);
                        if ($result['success']) {
                            Customer::update($id, ['status' => 'active']);
                            $successCount++;
                        } else $failCount++;
                        break;
                }
            } catch (\Throwable $e) {
                $failCount++;
            }
        }
        
        $msg = "Bulk action selesai. Berhasil: $successCount";
        if ($failCount > 0) $msg .= ", Gagal: $failCount";
        
        logActivity(currentUserId(), 'bulk_action', "Bulk $action pada " . count($selectedIds) . " pelanggan");
        redirect('/admin/customers.php', $msg);
    }
}

// ============================================================================
// 5. LOAD DATA PELANGGAN
// ============================================================================
try {
    if ($isBranchAdmin) {
        $stmt = $db->prepare("
            SELECT c.*, p.name as package_name, b.name as branch_name
            FROM customers c
            LEFT JOIN packages p ON c.package_id = p.id
            LEFT JOIN branches b ON c.branch_id = b.id
            WHERE c.branch_id = ?
            ORDER BY c.name ASC
        ");
        $stmt->execute([$userBranchId]);
        $customers = $stmt->fetchAll();
    } else {
        $customers = $db->query("
            SELECT c.*, p.name as package_name, b.name as branch_name
            FROM customers c
            LEFT JOIN packages p ON c.package_id = p.id
            LEFT JOIN branches b ON c.branch_id = b.id
            ORDER BY c.name ASC
        ")->fetchAll();
    }
} catch (\Throwable $e) {
    $customers = Customer::all();
}

if ($isBranchAdmin) {
    $branches = array_filter($allBranches, fn($b) => (int)$b['id'] === $userBranchId);
} else {
    $branches = $allBranches;
}

$activeConnections = [];
$mtConnected = false;
try {
    $mt = new MikroTik();
    $actives = $mt->getActiveConnections();
    $mtConnected = empty($mt->lastError);
    
    foreach ($actives as $active) {
        $activeConnections[$active['name']] = [
            'uptime' => $active['uptime'] ?? '-',
            'caller_id' => $active['caller-id'] ?? '-'
        ];
    }
} catch (\Throwable $e) {
    $mtConnected = false;
}

foreach ($customers as &$c) {
    $username = $c['pppoe_username'];
    
    if (isset($activeConnections[$username])) {
        $c['internet_status'] = 'connected';
        $c['uptime'] = $activeConnections[$username]['uptime'];
    } else {
        $c['internet_status'] = 'disconnected';
        $c['uptime'] = '-';
    }
    
    $unpaidBill = Bill::getLatestUnpaid($c['id']);
    $c['has_unpaid_bill'] = !empty($unpaidBill);
    $c['unpaid_bill'] = $unpaidBill;
}
unset($c);

// ============================================================================
// 6. FILTER
// ============================================================================
$filterStatus = $_GET['status'] ?? '';
$filterBranch = $_GET['branch'] ?? '';
$filterInternet = $_GET['internet'] ?? '';
$filterBill = $_GET['bill'] ?? '';
$search = $_GET['search'] ?? '';

if ($filterStatus || $filterBranch || $filterInternet || $filterBill || $search) {
    $filtered = [];
    foreach ($customers as $c) {
        if ($filterStatus && $c['status'] !== $filterStatus) continue;
        if ($filterBranch && !$isBranchAdmin && $c['branch_id'] != $filterBranch) continue;
        if ($filterInternet && $c['internet_status'] !== $filterInternet) continue;
        if ($filterBill === 'unpaid' && !$c['has_unpaid_bill']) continue;
        if ($filterBill === 'paid' && $c['has_unpaid_bill']) continue;
        if ($search && stripos($c['name'] . ' ' . $c['customer_number'] . ' ' . $c['phone'] . ' ' . $c['pppoe_username'], $search) === false) continue;
        $filtered[] = $c;
    }
    $customers = $filtered;
}

// ============================================================================
// 7. STATISTIK
// ============================================================================
$totalCustomers = count($customers);
$totalActive = count(array_filter($customers, fn($c) => $c['status'] === 'active'));
$totalSuspended = count(array_filter($customers, fn($c) => $c['status'] === 'suspended'));
$totalOnline = count(array_filter($customers, fn($c) => $c['internet_status'] === 'connected'));
$totalUnpaid = count(array_filter($customers, fn($c) => $c['has_unpaid_bill']));

require __DIR__ . '/../includes/header.php';
require __DIR__ . '/../includes/sidebar.php';
?>

<style>
/* === PAGE-SPECIFIC STYLES === */
.page-header { margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; }
.page-title { font-size: 1.8rem; font-weight: 700; color: #003D7A; margin: 0; display: flex; align-items: center; gap: 12px; }
.page-title i { font-size: 2rem; color: #0066CC; }
.btn-add { padding: 12px 24px; background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; border: none; border-radius: 12px; font-size: 0.95rem; font-weight: 600; cursor: pointer; transition: all 0.3s ease; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; box-shadow: 0 4px 15px rgba(0, 102, 204, 0.3); }
.btn-add:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0, 102, 204, 0.4); color: white; }
.summary-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 14px; margin-bottom: 20px; }
.summary-card { background: white; border-radius: 14px; padding: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.06); position: relative; overflow: hidden; transition: all 0.3s ease; border-left: 4px solid; }
.summary-card:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(0,0,0,0.1); }
.summary-card.primary { border-left-color: #0066CC; }
.summary-card.success { border-left-color: #00C853; }
.summary-card.warning { border-left-color: #FF9900; }
.summary-card.danger { border-left-color: #DC3545; }
.summary-card.info { border-left-color: #00B8D4; }
.summary-card-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
.summary-card-title { color: #666; font-size: 0.75rem; font-weight: 600; margin: 0; text-transform: uppercase; letter-spacing: 0.5px; }
.summary-card-icon { width: 36px; height: 36px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-size: 1rem; }
.summary-card.primary .summary-card-icon { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.summary-card.success .summary-card-icon { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.summary-card.warning .summary-card-icon { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.summary-card.danger .summary-card-icon { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.summary-card.info .summary-card-icon { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); }
.summary-card-value { font-size: 1.5rem; font-weight: 800; margin-bottom: 2px; letter-spacing: -0.5px; }
.summary-card.primary .summary-card-value { color: #0066CC; }
.summary-card.success .summary-card-value { color: #00C853; }
.summary-card.warning .summary-card-value { color: #FF9900; }
.summary-card.danger .summary-card-value { color: #DC3545; }
.summary-card.info .summary-card-value { color: #00B8D4; }
.summary-card-footer { font-size: 0.75rem; color: #999; }
.alert-modern { padding: 14px 18px; border-radius: 12px; margin-bottom: 16px; display: flex; align-items: flex-start; gap: 12px; font-size: 0.9rem; border: 2px solid; }
.alert-modern.success { background: #e8f5e9; border-color: #a5d6a7; color: #2e7d32; }
.alert-modern.danger { background: #ffebee; border-color: #ef9a9a; color: #c62828; }
.alert-modern.warning { background: #fff8e1; border-color: #ffe082; color: #f57c00; }
.alert-modern.info { background: #e3f2fd; border-color: #90caf9; color: #1565c0; }
.alert-modern i { font-size: 1.2rem; margin-top: 2px; flex-shrink: 0; }
.card-modern { background: white; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); overflow: hidden; margin-bottom: 20px; border: none; }
.card-header-modern { color: white; padding: 16px 20px; font-size: 1rem; font-weight: 600; display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.card-header-modern.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.card-header-modern .title-left { display: flex; align-items: center; gap: 10px; }
.card-body-modern { padding: 20px; }
.filter-form { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; align-items: end; }
.form-group-filter { margin-bottom: 0; }
.form-label-filter { display: block; font-weight: 600; color: #003D7A; margin-bottom: 6px; font-size: 0.8rem; }
.form-control-filter, .form-select-filter { width: 100%; padding: 10px 14px; border: 2px solid #e8f4f8; border-radius: 10px; font-size: 0.88rem; transition: all 0.3s ease; background: #f8fafc; font-family: inherit; }
.form-control-filter:focus, .form-select-filter:focus { outline: none; border-color: #0066CC; background: white; box-shadow: 0 0 0 4px rgba(0, 102, 204, 0.1); }
.btn-filter { padding: 10px 16px; border: none; border-radius: 10px; font-size: 0.88rem; font-weight: 600; cursor: pointer; transition: all 0.3s ease; display: inline-flex; align-items: center; justify-content: center; gap: 6px; text-decoration: none; white-space: nowrap; height: 42px; }
.btn-filter.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3); }
.btn-filter.outline { background: white; color: #666; border: 2px solid #e8f4f8; }
.table-wrapper { background: white; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); overflow: hidden; margin-bottom: 20px; }
.table-header { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; padding: 16px 20px; display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.table-header-title { display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 1rem; }
.table-header-count { background: rgba(255,255,255,0.2); padding: 4px 12px; border-radius: 20px; font-size: 0.82rem; font-weight: 600; }
.table-header-actions { display: flex; align-items: center; gap: 10px; }
.bulk-select-modern { padding: 8px 12px; border: 2px solid rgba(255,255,255,0.3); border-radius: 8px; background: rgba(255,255,255,0.1); color: white; font-size: 0.85rem; font-family: inherit; cursor: pointer; }
.bulk-select-modern option { background: white; color: #333; }
.table-scroll { overflow-x: auto; -webkit-overflow-scrolling: touch; }
.table-modern { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 0.88rem; min-width: 1100px; }
.table-modern thead { background: #f8fafc; position: sticky; top: 0; z-index: 10; }
.table-modern th { padding: 12px 14px; text-align: left; font-weight: 700; color: #003D7A; border-bottom: 2px solid #e8f4f8; font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.5px; white-space: nowrap; }
.table-modern td { padding: 12px 14px; border-bottom: 1px solid #f0f0f0; vertical-align: middle; }
.table-modern tbody tr { transition: all 0.2s ease; }
.table-modern tbody tr:hover { background: #f8fafc; }
.table-modern tbody tr:last-child td { border-bottom: none; }
.table-modern tbody tr.row-suspended { background: #fff8f8; }
.table-modern tbody tr.row-suspended:hover { background: #fff0f0; }
.table-modern tbody tr.row-unpaid { background: #fffdf5; }
.table-modern tbody tr.row-unpaid:hover { background: #fffae8; }
.checkbox-modern { width: 18px; height: 18px; cursor: pointer; accent-color: #0066CC; }
.customer-cell { display: flex; align-items: center; gap: 10px; }
.customer-avatar { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 700; color: white; font-size: 0.85rem; flex-shrink: 0; }
.customer-avatar.active { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.customer-avatar.suspended { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.customer-avatar.inactive { background: linear-gradient(135deg, #607D8B 0%, #90A4AE 100%); }
.customer-name { font-weight: 700; color: #003D7A; font-size: 0.88rem; margin: 0; line-height: 1.3; }
.badge-modern { display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; border-radius: 20px; font-size: 0.72rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; white-space: nowrap; }
.badge-modern.active { background: #d1e7dd; color: #0f5132; }
.badge-modern.suspended { background: #f8d7da; color: #842029; }
.badge-modern.inactive { background: #e9ecef; color: #41464b; }
.badge-modern.online { background: #d1e7dd; color: #0f5132; }
.badge-modern.offline { background: #e9ecef; color: #41464b; }
.badge-modern.unpaid { background: #fff3cd; color: #856404; }
.badge-modern.paid { background: #d1e7dd; color: #0f5132; }
.badge-modern.package { background: #cfe2ff; color: #084298; text-transform: none; }
.badge-modern.branch { background: #cff4fc; color: #055160; text-transform: none; }
.bill-info { font-size: 0.75rem; color: #856404; margin-top: 3px; line-height: 1.4; }
.action-buttons { display: flex; gap: 4px; flex-wrap: nowrap; }
.btn-action { width: 32px; height: 32px; border: none; border-radius: 8px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.3s ease; font-size: 0.88rem; text-decoration: none; flex-shrink: 0; }
.btn-action.pay { background: #d1e7dd; color: #0f5132; }
.btn-action.pay:hover { background: #00C853; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 200, 83, 0.3); }
.btn-action.generate { background: #cfe2ff; color: #084298; }
.btn-action.generate:hover { background: #0066CC; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3); }
.btn-action.link { background: #cff4fc; color: #055160; }
.btn-action.link:hover { background: #00B8D4; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 184, 212, 0.3); }
.btn-action.edit { background: #fff3cd; color: #856404; }
.btn-action.edit:hover { background: #FF9900; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(255, 153, 0, 0.3); }
.btn-action.wa { background: #d1e7dd; color: #0f5132; }
.btn-action.wa:hover { background: #25D366; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(37, 211, 102, 0.3); }
.btn-action.suspend { background: #f8d7da; color: #842029; }
.btn-action.suspend:hover { background: #DC3545; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3); }
.btn-action.restore { background: #cff4fc; color: #055160; }
.btn-action.restore:hover { background: #00B8D4; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 184, 212, 0.3); }
.btn-action.delete { background: #ffe5e5; color: #842029; }
.btn-action.delete:hover { background: #b02a37; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(176, 42, 55, 0.3); }
.empty-state { text-align: center; padding: 50px 20px; }
.empty-state-icon { width: 70px; height: 70px; margin: 0 auto 16px; background: #f8fafc; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 2rem; color: #ccc; }
.empty-state-title { color: #666; font-weight: 600; margin-bottom: 6px; font-size: 1rem; }
.empty-state-subtitle { color: #999; font-size: 0.85rem; margin: 0 0 16px; }

/* === MODAL PEMBAYARAN === */
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; z-index: 9999; animation: fadeIn 0.2s ease; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
.modal-content { background: white; border-radius: 16px; width: 90%; max-width: 450px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); overflow: hidden; animation: slideDown 0.3s ease; }
@keyframes slideDown { from { opacity: 0; transform: translateY(-30px); } to { opacity: 1; transform: translateY(0); } }
.modal-header { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; padding: 16px 20px; display: flex; justify-content: space-between; align-items: center; }
.modal-header h3 { margin: 0; font-size: 1.1rem; display: flex; align-items: center; gap: 8px; font-weight: 700; }
.modal-close { background: rgba(255,255,255,0.2); border: none; color: white; font-size: 1.2rem; cursor: pointer; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; transition: all 0.2s; }
.modal-close:hover { background: rgba(255,255,255,0.4); }
.modal-body { padding: 20px; }
.bill-summary { background: #f8fafc; padding: 12px; border-radius: 10px; margin-bottom: 16px; border-left: 4px solid #0066CC; }
.bill-summary p { margin: 4px 0; font-size: 0.85rem; color: #666; }
.bill-summary strong { color: #003D7A; }
.modal-body .form-group { margin-bottom: 15px; }
.modal-body label { display: flex; align-items: center; gap: 6px; font-weight: 600; color: #003D7A; margin-bottom: 6px; font-size: 0.85rem; }
.modal-footer { padding: 16px 20px; background: #f8fafc; display: flex; justify-content: flex-end; gap: 10px; border-top: 1px solid #e8f4f8; }

@media (max-width: 768px) {
    .page-header { flex-direction: column; align-items: stretch; }
    .page-title { font-size: 1.4rem; }
    .page-title i { font-size: 1.6rem; }
    .btn-add { width: 100%; justify-content: center; }
    .summary-row { grid-template-columns: repeat(2, 1fr); gap: 10px; }
    .filter-form { grid-template-columns: 1fr; }
    .btn-filter { width: 100%; }
}
</style>

<div class="main-content">
    <div class="navbar-modern">
        <div class="navbar-left">
            <button class="burger-btn" onclick="toggleSidebar()">
                <i class="bi bi-list"></i>
            </button>
            <div>
                <h1 class="navbar-title">Data Pelanggan</h1>
                <p class="navbar-subtitle">
                    <?php if ($isBranchAdmin): ?>
                        <i class="bi bi-building"></i> <?= htmlspecialchars($userBranchName) ?>
                    <?php else: ?>
                        <i class="bi bi-shield-check"></i> Pusat (Semua Cabang)
                    <?php endif; ?>
                </p>
            </div>
        </div>
        <div class="navbar-right">
            <?php if ($isBranchAdmin): ?>
                <span class="navbar-badge"><i class="bi bi-building"></i> <?= htmlspecialchars($userBranchName) ?></span>
            <?php else: ?>
                <span class="navbar-badge"><i class="bi bi-shield-check"></i> Super Admin</span>
            <?php endif; ?>
        </div>
    </div>

    <div class="content-wrapper">
        <div class="page-header">
            <h2 class="page-title"><i class="bi bi-people-fill"></i><span>Data Pelanggan</span></h2>
            <a href="/admin/customer_add.php" class="btn-add"><i class="bi bi-person-plus-fill"></i><span>Tambah Pelanggan</span></a>
        </div>

        <?= flashMessage() ?>

        <?php if (!$mtConnected): ?>
            <div class="alert-modern warning"><i class="bi bi-exclamation-triangle-fill"></i><div><strong>MikroTik tidak terhubung.</strong> Status internet tidak dapat ditampilkan.</div></div>
        <?php endif; ?>

        <div class="summary-row">
            <div class="summary-card primary"><div class="summary-card-header"><h6 class="summary-card-title">Total</h6><div class="summary-card-icon"><i class="bi bi-people-fill"></i></div></div><div class="summary-card-value"><?= number_format($totalCustomers) ?></div><div class="summary-card-footer">👥 Seluruh pelanggan</div></div>
            <div class="summary-card success"><div class="summary-card-header"><h6 class="summary-card-title">Aktif</h6><div class="summary-card-icon"><i class="bi bi-check-circle-fill"></i></div></div><div class="summary-card-value"><?= number_format($totalActive) ?></div><div class="summary-card-footer">✅ Pelanggan aktif</div></div>
            <div class="summary-card danger"><div class="summary-card-header"><h6 class="summary-card-title">Suspended</h6><div class="summary-card-icon"><i class="bi bi-pause-circle-fill"></i></div></div><div class="summary-card-value"><?= number_format($totalSuspended) ?></div><div class="summary-card-footer">⏸️ Di-suspend</div></div>
            <div class="summary-card info"><div class="summary-card-header"><h6 class="summary-card-title">Online</h6><div class="summary-card-icon"><i class="bi bi-wifi"></i></div></div><div class="summary-card-value"><?= number_format($totalOnline) ?></div><div class="summary-card-footer">🟢 Terhubung internet</div></div>
            <div class="summary-card warning"><div class="summary-card-header"><h6 class="summary-card-title">Belum Bayar</h6><div class="summary-card-icon"><i class="bi bi-exclamation-triangle-fill"></i></div></div><div class="summary-card-value"><?= number_format($totalUnpaid) ?></div><div class="summary-card-footer">💰 Menunggu pembayaran</div></div>
        </div>

        <div class="card-modern">
            <div class="card-header-modern primary"><div class="title-left"><i class="bi bi-funnel-fill"></i><span>Filter & Pencarian</span></div></div>
            <div class="card-body-modern">
                <form method="GET" class="filter-form">
                    <div class="form-group-filter"><label class="form-label-filter"><i class="bi bi-search"></i> Cari</label><input type="text" name="search" class="form-control-filter" value="<?= htmlspecialchars($search) ?>" placeholder="Nama, HP, username..."></div>
                    <div class="form-group-filter"><label class="form-label-filter"><i class="bi bi-circle"></i> Status</label><select name="status" class="form-select-filter"><option value="">Semua</option><option value="active" <?= $filterStatus === 'active' ? 'selected' : '' ?>>Aktif</option><option value="suspended" <?= $filterStatus === 'suspended' ? 'selected' : '' ?>>Suspended</option><option value="inactive" <?= $filterStatus === 'inactive' ? 'selected' : '' ?>>Nonaktif</option></select></div>
                    <div class="form-group-filter"><label class="form-label-filter"><i class="bi bi-wifi"></i> Internet</label><select name="internet" class="form-select-filter"><option value="">Semua</option><option value="connected" <?= $filterInternet === 'connected' ? 'selected' : '' ?>>Online</option><option value="disconnected" <?= $filterInternet === 'disconnected' ? 'selected' : '' ?>>Offline</option></select></div>
                    <div class="form-group-filter"><label class="form-label-filter"><i class="bi bi-receipt"></i> Tagihan</label><select name="bill" class="form-select-filter"><option value="">Semua</option><option value="unpaid" <?= $filterBill === 'unpaid' ? 'selected' : '' ?>>Belum Bayar</option><option value="paid" <?= $filterBill === 'paid' ? 'selected' : '' ?>>Sudah Bayar</option></select></div>
                    <?php if ($isSuperAdmin): ?>
                    <div class="form-group-filter"><label class="form-label-filter"><i class="bi bi-building"></i> Cabang</label><select name="branch" class="form-select-filter"><option value="">Semua Cabang</option><?php foreach ($branches as $b): ?><option value="<?= $b['id'] ?>" <?= $filterBranch == $b['id'] ? 'selected' : '' ?>><?= htmlspecialchars($b['name']) ?></option><?php endforeach; ?></select></div>
                    <?php else: ?><input type="hidden" name="branch" value="<?= $userBranchId ?>"><?php endif; ?>
                    <div style="display: flex; gap: 8px; grid-column: 1 / -1;"><button type="submit" class="btn-filter primary" style="flex: 1;"><i class="bi bi-funnel"></i><span>Filter</span></button><a href="/admin/customers.php" class="btn-filter outline" style="flex: 1;"><i class="bi bi-arrow-counterclockwise"></i><span>Reset</span></a></div>
                </form>
            </div>
        </div>

        <div class="table-wrapper">
            <div class="table-header">
                <div class="table-header-title"><i class="bi bi-people"></i><span>Daftar Pelanggan</span><span class="table-header-count"><?= count($customers) ?></span></div>
                <?php if (count($customers) > 0): ?>
                <div class="table-header-actions">
                    <form method="POST" id="bulkForm" style="margin: 0;"><?= csrfField() ?><select name="bulk_action" class="bulk-select-modern" onchange="confirmBulkAction(this)"><option value="">Bulk Action</option><option value="generate_bill">Generate Tagihan</option><option value="suspend">Suspend Selected</option><option value="restore">Restore Selected</option></select></form>
                </div>
                <?php endif; ?>
            </div>
            
            <?php if (empty($customers)): ?>
                <div class="empty-state"><div class="empty-state-icon"><i class="bi bi-inbox"></i></div><h5 class="empty-state-title">Tidak ada pelanggan</h5><p class="empty-state-subtitle">Belum ada data pelanggan yang sesuai filter</p><a href="/admin/customer_add.php" class="btn-add"><i class="bi bi-person-plus-fill"></i><span>Tambah Pelanggan</span></a></div>
            <?php else: ?>
                <form method="POST" id="bulkFormMain"><?= csrfField() ?><div class="table-scroll">
                    <table class="table-modern">
                        <thead><tr><th style="width: 40px;"><input type="checkbox" id="selectAll" class="checkbox-modern" onchange="toggleSelectAll()"></th><th>No. Pelanggan</th><th>Nama</th><?php if ($isSuperAdmin): ?><th>Cabang</th><?php endif; ?><th>Paket</th><th>Username PPPoE</th><th>No. HP</th><th>Status</th><th>Internet</th><th>Tagihan</th><th class="text-center">Aksi</th></tr></thead>
                        <tbody>
                        <?php foreach ($customers as $c): 
                            $rowClass = '';
                            if ($c['status'] === 'suspended') $rowClass = 'row-suspended';
                            elseif ($c['has_unpaid_bill']) $rowClass = 'row-unpaid';
                        ?>
                            <tr class="<?= $rowClass ?>">
                                <td><input type="checkbox" name="selected_customers[]" value="<?= $c['id'] ?>" class="customer-checkbox checkbox-modern"></td>
                                <td><strong style="color: #003D7A; font-size: 0.85rem;">#<?= htmlspecialchars($c['customer_number']) ?></strong></td>
                                <td><div class="customer-cell"><div class="customer-avatar <?= $c['status'] ?>"><?= strtoupper(substr($c['name'], 0, 1)) ?></div><div><div class="customer-name"><?= htmlspecialchars($c['name']) ?></div></div></div></td>
                                <?php if ($isSuperAdmin): ?><td><?php if (!empty($c['branch_name'])): ?><span class="badge-modern branch"><i class="bi bi-building"></i> <?= htmlspecialchars($c['branch_name']) ?></span><?php else: ?><span class="badge-modern branch"><i class="bi bi-globe"></i> Pusat</span><?php endif; ?></td><?php endif; ?>
                                <td><span class="badge-modern package"><i class="bi bi-box"></i> <?= htmlspecialchars($c['package_name']) ?></span></td>
                                <td><code style="font-size: 0.78rem; background: #f8fafc; padding: 2px 6px; border-radius: 4px;"><?= htmlspecialchars($c['pppoe_username']) ?></code></td>
                                <td><a href="https://wa.me/<?= preg_replace('/^0/', '62', $c['phone']) ?>" target="_blank" style="color: #25D366; text-decoration: none; font-weight: 600; font-size: 0.85rem;"><i class="bi bi-whatsapp"></i> <?= htmlspecialchars($c['phone']) ?></a></td>
                                <td><?php if ($c['status'] === 'active'): ?><span class="badge-modern active"><i class="bi bi-check-circle"></i> Aktif</span><?php elseif ($c['status'] === 'suspended'): ?><span class="badge-modern suspended"><i class="bi bi-pause-circle"></i> Suspended</span><?php else: ?><span class="badge-modern inactive"><i class="bi bi-dash-circle"></i> Nonaktif</span><?php endif; ?></td>
                                <td><?php if ($c['internet_status'] === 'connected'): ?><span class="badge-modern online" title="Uptime: <?= htmlspecialchars($c['uptime']) ?>"><i class="bi bi-wifi"></i> Online</span><?php else: ?><span class="badge-modern offline"><i class="bi bi-wifi-off"></i> Offline</span><?php endif; ?></td>
                                <td><?php if ($c['has_unpaid_bill']): ?><?php $bill = $c['unpaid_bill']; ?><span class="badge-modern unpaid"><i class="bi bi-receipt"></i> Belum Bayar</span><div class="bill-info">Rp <?= number_format($bill['amount']) ?><br><i class="bi bi-calendar"></i> <?= date('d/m/Y', strtotime($bill['due_date'])) ?></div><?php else: ?><span class="badge-modern paid"><i class="bi bi-check-circle"></i> Lunas</span><?php endif; ?></td>
                                <td>
                                    <div class="action-buttons" style="justify-content: center;">
                                        <?php if ($c['has_unpaid_bill']): ?>
                                            <button type="button" class="btn-action pay" 
                                               onclick="openPayModal(<?= $c['unpaid_bill']['id'] ?>, <?= $c['id'] ?>, '<?= htmlspecialchars($c['name'], ENT_QUOTES) ?>', '<?= htmlspecialchars($c['unpaid_bill']['bill_number'], ENT_QUOTES) ?>', 'Rp <?= number_format($c['unpaid_bill']['amount'], 0, ',', '.') ?>')" 
                                               title="Bayar Tagihan">
                                                <i class="bi bi-cash-coin"></i>
                                            </button>
                                            <a href="/public/pay.php?id=<?= urlencode($c['customer_number']) ?>" target="_blank" class="btn-action link" title="Link Pembayaran"><i class="bi bi-credit-card"></i></a>
                                        <?php else: ?>
                                            <a href="/admin/customers.php?action=generate_bill&id=<?= $c['id'] ?>&token=<?= csrfToken() ?>" class="btn-action generate" onclick="return confirm('Generate tagihan untuk <?= htmlspecialchars($c['name']) ?>?')" title="Generate Tagihan"><i class="bi bi-receipt-cutoff"></i></a>
                                        <?php endif; ?>
                                        <a href="/admin/customer_edit.php?id=<?= $c['id'] ?>" class="btn-action edit" title="Edit"><i class="bi bi-pencil-fill"></i></a>
                                        <a href="https://wa.me/<?= preg_replace('/^0/', '62', $c['phone']) ?>" target="_blank" class="btn-action wa" title="WhatsApp"><i class="bi bi-whatsapp"></i></a>
                                        <?php if ($c['status'] === 'active'): ?><a href="/admin/customers.php?action=suspend&id=<?= $c['id'] ?>&token=<?= csrfToken() ?>" class="btn-action suspend" onclick="return confirm('Suspend pelanggan ini?')" title="Suspend"><i class="bi bi-pause-fill"></i></a><?php elseif ($c['status'] === 'suspended'): ?><a href="/admin/customers.php?action=restore&id=<?= $c['id'] ?>&token=<?= csrfToken() ?>" class="btn-action restore" onclick="return confirm('Restore pelanggan ini?')" title="Restore"><i class="bi bi-play-fill"></i></a><?php endif; ?>
                                        <a href="/admin/customers.php?action=delete&id=<?= $c['id'] ?>&token=<?= csrfToken() ?>" class="btn-action delete" onclick="return confirm('Yakin hapus? Tindakan ini tidak bisa dibatalkan!')" title="Hapus"><i class="bi bi-trash-fill"></i></a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div></form>
            <?php endif; ?>
        </div>
    </div>

    <!-- Modal Pembayaran Manual -->
    <div id="payModal" class="modal-overlay" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="bi bi-cash-coin"></i> Konfirmasi Pembayaran Manual</h3>
                <button class="modal-close" onclick="closePayModal()">&times;</button>
            </div>
            <form method="POST">
                <?= csrfField() ?>
                <input type="hidden" name="bill_id" id="modal_bill_id">
                <input type="hidden" name="customer_id" id="modal_customer_id" value="0">
                
                <div class="modal-body">
                    <div class="bill-summary">
                        <p>Pelanggan: <strong id="modal_customer_name"></strong></p>
                        <p>No. Tagihan: <strong id="modal_bill_number"></strong></p>
                        <p>Jumlah: <strong id="modal_bill_amount" style="color: #00C853;"></strong></p>
                    </div>
                    
                    <div class="form-group">
                        <label><i class="bi bi-credit-card"></i> Metode Pembayaran</label>
                        <select name="payment_method" class="form-control-filter" required>
                            <option value="Tunai">Tunai</option>
                            <option value="Transfer Bank">Transfer Bank</option>
                            <option value="QRIS">QRIS</option>
                            <option value="Edc">EDC</option>
                            <option value="Lainnya">Lainnya</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label><i class="bi bi-tag"></i> Kategori</label>
                        <select name="category" class="form-control-filter" required>
                            <option value="Pelunasan Tagihan">Pelunasan Tagihan</option>
                            <option value="Pemasukan Lainnya">Pemasukan Lainnya</option>
                            <option value="Denda">Denda</option>
                            <option value="Biaya Instalasi">Biaya Instalasi</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-filter outline" onclick="closePayModal()">Batal</button>
                    <button type="submit" name="submit_pay" class="btn-filter primary"><i class="bi bi-check-circle"></i> Bayar Sekarang</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    if (sidebar && overlay) {
        sidebar.classList.toggle('active');
        overlay.classList.toggle('active');
        document.body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
    }
}

function toggleSelectAll() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.customer-checkbox');
    checkboxes.forEach(cb => cb.checked = selectAll.checked);
}

function confirmBulkAction(select) {
    if (select.value === '') return;
    const selected = document.querySelectorAll('.customer-checkbox:checked');
    if (selected.length === 0) { alert('Pilih minimal 1 pelanggan'); select.value = ''; return; }
    const actionText = { 'generate_bill': 'GENERATE TAGIHAN', 'suspend': 'SUSPEND', 'restore': 'RESTORE' };
    if (confirm(`${actionText[select.value]} untuk ${selected.length} pelanggan yang dipilih?`)) {
        const mainForm = document.getElementById('bulkFormMain');
        mainForm.querySelectorAll('input[name="selected_customers[]"]').forEach(el => el.remove());
        selected.forEach(cb => { const clone = cb.cloneNode(true); clone.style.display = 'none'; mainForm.appendChild(clone); });
        const input = document.createElement('input'); input.type = 'hidden'; input.name = 'bulk_action'; input.value = select.value; mainForm.appendChild(input);
        mainForm.submit();
    } else { select.value = ''; }
}

function openPayModal(billId, customerId, customerName, billNumber, billAmount) {
    document.getElementById('modal_bill_id').value = billId;
    document.getElementById('modal_customer_id').value = customerId || 0;
    document.getElementById('modal_customer_name').innerText = customerName;
    document.getElementById('modal_bill_number').innerText = billNumber;
    document.getElementById('modal_bill_amount').innerText = billAmount;
    document.getElementById('payModal').style.display = 'flex';
}

function closePayModal() {
    document.getElementById('payModal').style.display = 'none';
}

window.onclick = function(event) {
    const modal = document.getElementById('payModal');
    if (event.target === modal) closePayModal();
}
</script>

<?php require __DIR__ . '/../includes/footer.php'; ?>