<?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/MikroTik.php';

requireRole('super_admin');
$pageTitle = 'Edit Pelanggan';

$db = db();
$branches = Branch::all();
$packages = $db->query("SELECT * FROM packages WHERE status='active' ORDER BY name")->fetchAll();

$customerId = (int)($_GET['id'] ?? 0);
if ($customerId <= 0) {
    redirect('/admin/customers.php', 'ID customer tidak valid', 'error');
}

$customer = Customer::find($customerId);
if (!$customer) {
    redirect('/admin/customers.php', 'Customer tidak ditemukan', 'error');
}

// Get existing PPPoE secrets from MikroTik
$existingSecrets = [];
$mtConnected = false;
try {
    $mt = new MikroTik();
    $secrets = $mt->getAllSecrets();
    $mtConnected = empty($mt->lastError);
    
    foreach ($secrets as $s) {
        if ($s['name'] !== $customer['pppoe_username']) {
            $existingSecrets[] = [
                'name' => $s['name'],
                'disabled' => isset($s['disabled']) && $s['disabled'] === 'true'
            ];
        }
    }
} catch (\Throwable $e) {
    $mtConnected = false;
}

// ============================================================================
// ⭐ PERBAIKAN LOGIKA: HITUNG JATUH TEMPO & MASA AKTIF
// ============================================================================
$installationDate = $customer['installation_date'] ?? $customer['created_at'] ?? date('Y-m-d');
$installationDate = date('Y-m-d', strtotime($installationDate));

$currentDueDay = (int)($customer['due_day'] ?? date('j', strtotime($installationDate)));

// ⭐ Hitung jatuh tempo: tanggal instalasi + 1 bulan, lalu set tanggal sesuai due_day
$instDateObj = new DateTime($installationDate);
$dueDateObj = clone $instDateObj;
$dueDateObj->modify('+1 month');
// Set tanggal sesuai due_day (handle bulan dengan jumlah hari berbeda)
$maxDayInMonth = (int)$dueDateObj->format('t');
$dueDateObj->setDate((int)$dueDateObj->format('Y'), (int)$dueDateObj->format('m'), min($currentDueDay, $maxDayInMonth));
$dueDate = $dueDateObj->format('Y-m-d');

// ⭐ PERBAIKAN: Masa aktif = jatuh tempo + 1 bulan (BUKAN dari tanggal instalasi)
$activeUntilObj = clone $dueDateObj;
$activeUntilObj->modify('+1 month');
$activeUntilObj->setTime(23, 59, 59);
$activeUntil = $customer['active_until'] ?? $activeUntilObj->format('Y-m-d H:i:s');
$activeUntilDate = date('Y-m-d', strtotime($activeUntil));

// Format tanggal dalam Bahasa Indonesia
$hariIndonesia = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
$bulanIndonesia = [
    1 => 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
    'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
];

// ⭐ FUNGSI FORMAT TANGGAL: "Hari, Tanggal Bulan Tahun"
function formatTanggal($dateStr, $hariIndonesia, $bulanIndonesia) {
    $timestamp = strtotime($dateStr);
    $hari = $hariIndonesia[date('w', $timestamp)];
    $tanggal = date('j', $timestamp);
    $bulan = $bulanIndonesia[(int)date('n', $timestamp)];
    $tahun = date('Y', $timestamp);
    return "$hari, $tanggal $bulan $tahun";
}

// ⭐ Format semua tanggal dengan format yang sama
$installationDateFormatted = formatTanggal($installationDate, $hariIndonesia, $bulanIndonesia);
$dueDateFormatted = formatTanggal($dueDate, $hariIndonesia, $bulanIndonesia);
$activeUntilFormatted = formatTanggal($activeUntilDate, $hariIndonesia, $bulanIndonesia);

// Hitung countdown jatuh tempo (dari hari ini ke jatuh tempo)
$today = strtotime('today');
$dueDayTs = strtotime($dueDate);
$daysDiff = floor(($dueDayTs - $today) / 86400);

if ($daysDiff > 0) {
    $dueCountdown = "$daysDiff hari lagi";
    $dueStatusClass = 'warning';
    $dueStatusIcon = '⏳';
} elseif ($daysDiff == 0) {
    $dueCountdown = 'HARI INI!';
    $dueStatusClass = 'danger';
    $dueStatusIcon = '🔥';
} else {
    $daysOverdue = abs($daysDiff);
    $dueCountdown = "Terlambat $daysOverdue hari";
    $dueStatusClass = 'danger';
    $dueStatusIcon = '⚠️';
}

// ⭐ PERBAIKAN: Hitung periode masa aktif (dari jatuh tempo ke active_until)
$activeUntilTs = strtotime($activeUntil);
$activePeriodDays = floor(($activeUntilTs - $dueDayTs) / 86400);

// Hitung sisa masa aktif dari HARI INI
$now = time();
$daysLeftActive = floor(($activeUntilTs - $now) / 86400);

if ($daysLeftActive > 7) {
    $activeStatus = "Aktif $daysLeftActive hari lagi";
    $activeClass = 'success';
} elseif ($daysLeftActive > 0) {
    $activeStatus = "Segera habis ($daysLeftActive hari)";
    $activeClass = 'warning';
} elseif ($daysLeftActive == 0) {
    $activeStatus = "Habis HARI INI";
    $activeClass = 'danger';
} else {
    $activeStatus = "Expired " . abs($daysLeftActive) . " hari lalu";
    $activeClass = 'danger';
}

$error = '';

// Handle update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCsrf($_POST['csrf_token'] ?? '')) {
    $oldUsername = $customer['pppoe_username'];
    $newUsername = $_POST['pppoe_username'];
    $newPassword = $_POST['pppoe_password'];
    $useExisting = isset($_POST['use_existing_secret']) && $_POST['use_existing_secret'] === '1';
    
    if (empty($newUsername) || empty($newPassword)) {
        $error = 'Username dan password PPPoE wajib diisi';
    } else {
        $updateData = [
            'branch_id' => $_POST['branch_id'],
            'name' => $_POST['name'],
            'pppoe_username' => $newUsername,
            'pppoe_password' => $newPassword,
            'package_id' => $_POST['package_id'],
            'phone' => $_POST['phone'],
            'email' => $_POST['email'] ?? null,
            'address' => $_POST['address'] ?? null,
            'ip_address' => $_POST['ip_address'] ?? null,
            'due_day' => (int)($_POST['due_day'] ?? 3),
        ];
        
        $result = Customer::update($customerId, $updateData);
        
        if ($result['success']) {
            $syncResult = ['success' => true, 'message' => ''];
            
            if ($oldUsername !== $newUsername || $customer['pppoe_password'] !== $newPassword) {
                try {
                    $mt = new MikroTik();
                    
                    if ($useExisting) {
                        $enableResult = $mt->restoreCustomer($newUsername);
                        if (!$enableResult['success']) {
                            $syncResult = ['success' => false, 'message' => 'Gagal enable secret: ' . $enableResult['error']];
                        }
                    } else {
                        if ($oldUsername !== $newUsername) {
                            $mt->removeSecret($oldUsername);
                        }
                        
                        $addResult = $mt->addSecret(
                            $newUsername,
                            $newPassword,
                            $customer['package_name'] ?? 'default',
                            'pppoe',
                            $customer['name']
                        );
                        
                        if (!$addResult['success']) {
                            $syncResult = ['success' => false, 'message' => 'Gagal sync ke MikroTik: ' . $addResult['error']];
                        }
                    }
                } catch (\Throwable $e) {
                    $syncResult = ['success' => false, 'message' => 'Error sync: ' . $e->getMessage()];
                }
            }
            
            logActivity(currentUserId(), 'edit_customer', "Edit pelanggan: " . $_POST['name'], 'customer', $customerId);
            
            if ($syncResult['success']) {
                redirect('/admin/customers.php', '✅ Pelanggan berhasil diupdate dan sinkron ke MikroTik');
            } else {
                redirect('/admin/customers.php', '⚠️ Pelanggan diupdate tapi GAGAL sync: ' . $syncResult['message'], 'warning');
            }
        } else {
            $error = $result['error'];
        }
    }
}

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

<style>
/* === NAVBAR MODERN === */
.navbar-modern { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); padding: 15px 20px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 2px 10px rgba(0,0,0,0.1); position: sticky; top: 0; z-index: 1000; }
.navbar-left { display: flex; align-items: center; gap: 15px; }
.burger-btn { background: rgba(255,255,255,0.15); border: none; color: white; width: 40px; height: 40px; border-radius: 10px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1.3rem; transition: all 0.3s ease; }
.burger-btn:hover { background: rgba(255,255,255,0.25); transform: scale(1.05); }
.navbar-title { color: white; font-size: 1.2rem; font-weight: 700; margin: 0; }
.navbar-subtitle { color: rgba(255,255,255,0.85); font-size: 0.78rem; margin: 0; }
.navbar-right { display: flex; align-items: center; gap: 10px; }
.navbar-badge { background: rgba(255,255,255,0.2); color: white; padding: 6px 12px; border-radius: 20px; font-size: 0.82rem; font-weight: 500; display: inline-flex; align-items: center; gap: 6px; }

.main-content { padding: 16px; max-width: 1000px; margin: 0 auto; display: flex; flex-direction: column; gap: 20px; }
.page-title { font-size: 1.4rem; font-weight: 700; color: #003D7A; margin: 0 0 12px; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.page-title i { color: #0066CC; }
.customer-badge { background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%); color: #f57c00; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 600; display: inline-flex; align-items: center; gap: 5px; }
.branch-badge { background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%); color: #003D7A; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 600; display: inline-flex; align-items: center; gap: 5px; }
.super-badge { background: linear-gradient(135deg, #7c3aed 0%, #a78bfa 100%); color: white; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 600; display: inline-flex; align-items: center; gap: 5px; }

.alert-modern { padding: 12px 16px; border-radius: 10px; margin-bottom: 12px; display: flex; align-items: flex-start; gap: 10px; font-size: 0.88rem; 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.1rem; margin-top: 2px; flex-shrink: 0; }

.form-card { background: white; border-radius: 14px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); overflow: hidden; }
.form-card-header { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; padding: 14px 20px; display: flex; align-items: center; justify-content: space-between; gap: 10px; font-weight: 600; font-size: 0.95rem; }
.form-card-header .header-left { display: flex; align-items: center; gap: 10px; }
.form-card-header .customer-number { background: rgba(255,255,255,0.2); padding: 3px 10px; border-radius: 12px; font-size: 0.75rem; font-weight: 600; font-family: 'Courier New', monospace; }
.form-card-body { padding: 16px 20px; }

.form-section { margin-bottom: 16px; padding-bottom: 16px; border-bottom: 1px dashed #e8f4f8; }
.form-section:last-child { border-bottom: none; margin-bottom: 0; padding-bottom: 0; }
.section-title { display: flex; align-items: center; gap: 8px; font-size: 0.92rem; font-weight: 700; color: #003D7A; margin: 0 0 12px; }
.section-title i { color: #0066CC; font-size: 1rem; }
.section-title .section-badge { margin-left: auto; font-size: 0.7rem; padding: 2px 8px; background: #e3f2fd; color: #1565c0; border-radius: 10px; font-weight: 600; }

.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px; }
.form-grid.single { grid-template-columns: 1fr; }
.form-grid.triple { grid-template-columns: repeat(3, 1fr); }
.form-group { margin: 0; }
.form-label-modern { display: flex; align-items: center; gap: 6px; font-weight: 600; color: #003D7A; margin-bottom: 6px; font-size: 0.82rem; }
.form-label-modern i { color: #0066CC; font-size: 0.9rem; }
.form-label-modern .required { color: #DC3545; margin-left: 2px; }
.form-control-modern, .form-select-modern { width: 100%; padding: 9px 12px; border: 2px solid #e8f4f8; border-radius: 10px; font-size: 0.88rem; transition: all 0.3s ease; background: #f8fafc; font-family: inherit; box-sizing: border-box; }
.form-control-modern:focus, .form-select-modern:focus { outline: none; border-color: #0066CC; background: white; box-shadow: 0 0 0 3px rgba(0, 102, 204, 0.1); }
.form-control-modern[readonly] { background: #f0f0f0; color: #666; cursor: not-allowed; }
textarea.form-control-modern { resize: vertical; min-height: 50px; }
.form-hint { display: flex; align-items: center; gap: 3px; margin-top: 4px; font-size: 0.72rem; color: #999; }

/* === ⭐ SCHEDULE INFO BOX === */
.schedule-info-box {
    background: linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%);
    border: 2px solid #ce93d8;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 16px;
}

.schedule-info-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 0.88rem;
    font-weight: 700;
    color: #6a1b9a;
    margin-bottom: 12px;
}

.schedule-info-title i { font-size: 1.1rem; }

.schedule-info-title .lock-badge {
    margin-left: auto;
    background: #6a1b9a;
    color: white;
    padding: 3px 10px;
    border-radius: 12px;
    font-size: 0.68rem;
    font-weight: 700;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.schedule-info-title .edit-badge {
    margin-left: auto;
    background: #ff9800;
    color: white;
    padding: 3px 10px;
    border-radius: 12px;
    font-size: 0.68rem;
    font-weight: 700;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.7; }
}

.schedule-grid {
    display: grid;
    grid-template-columns: 1fr auto 1fr auto 1fr;
    gap: 10px;
    align-items: center;
}

.schedule-item {
    text-align: center;
    padding: 12px 10px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    border: 2px solid transparent;
    transition: all 0.3s ease;
}

.schedule-item.installation { border-color: #42a5f5; }
.schedule-item.due-date { border-color: #ffa726; }
.schedule-item.active-until { border-color: #66bb6a; }
.schedule-item.preview { border-style: dashed; background: #fffde7; }

.schedule-item-icon { font-size: 1.5rem; margin-bottom: 6px; }
.schedule-item-label { font-size: 0.68rem; color: #666; text-transform: uppercase; font-weight: 700; letter-spacing: 0.3px; margin-bottom: 6px; }

/* ⭐ PERBAIKAN: Format tanggal lebih besar dan jelas */
.schedule-item-date { 
    font-size: 0.82rem; 
    font-weight: 700; 
    color: #003D7A; 
    margin-bottom: 4px; 
    line-height: 1.4;
    word-wrap: break-word;
}

.schedule-item.installation .schedule-item-date { color: #1565c0; }
.schedule-item.due-date .schedule-item-date { color: #ef6c00; }
.schedule-item.active-until .schedule-item-date { color: #2e7d32; }
.schedule-item.preview .schedule-item-date { color: #f57c00; font-style: italic; }

.schedule-item-status { display: inline-block; padding: 3px 10px; border-radius: 12px; font-size: 0.7rem; font-weight: 700; margin-top: 4px; }
.schedule-item-status.warning { background: #fff3cd; color: #856404; }
.schedule-item-status.danger { background: #f8d7da; color: #842029; }
.schedule-item-status.success { background: #d1e7dd; color: #0f5132; }
.schedule-item-status.preview { background: #fff3cd; color: #f57c00; }

.schedule-arrow { font-size: 1.5rem; color: #9c27b0; text-align: center; font-weight: 700; }

.schedule-note {
    margin-top: 12px;
    padding: 10px 12px;
    background: rgba(255,255,255,0.6);
    border-radius: 8px;
    font-size: 0.78rem;
    color: #6a1b9a;
    display: flex;
    align-items: flex-start;
    gap: 8px;
}

.schedule-note i { margin-top: 2px; flex-shrink: 0; }

.schedule-note.preview-note {
    background: #fff8e1;
    color: #f57c00;
    border-left: 3px solid #ff9800;
}

/* ⭐ PERBAIKAN: Info periode masa aktif */
.period-info {
    margin-top: 12px;
    padding: 10px 14px;
    background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
    border-radius: 8px;
    border-left: 4px solid #4caf50;
    font-size: 0.82rem;
    color: #2e7d32;
    display: flex;
    align-items: center;
    gap: 10px;
}

.period-info i { font-size: 1.2rem; flex-shrink: 0; }
.period-info strong { color: #1b5e20; }

.info-box { background: #e3f2fd; border-left: 3px solid #0066CC; padding: 10px 12px; border-radius: 8px; font-size: 0.8rem; color: #1565c0; margin-top: 8px; display: flex; align-items: flex-start; gap: 8px; }
.info-box i { margin-top: 2px; flex-shrink: 0; }
.info-box code { background: rgba(255,255,255,0.6); padding: 1px 6px; border-radius: 4px; font-family: 'Courier New', monospace; font-weight: 700; color: #003D7A; }

.warning-box { background: #fff8e1; border-left: 3px solid #FF9900; padding: 10px 12px; border-radius: 8px; font-size: 0.8rem; color: #f57c00; margin-top: 8px; display: flex; align-items: flex-start; gap: 8px; }
.warning-box i { margin-top: 2px; flex-shrink: 0; }

.current-value { background: #fff8e1; border-left: 3px solid #FF9900; padding: 6px 10px; border-radius: 6px; font-size: 0.78rem; color: #f57c00; margin-top: 6px; display: flex; align-items: center; gap: 6px; }
.current-value strong { color: #003D7A; font-family: 'Courier New', monospace; }

.secret-toggle { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 12px; }
.secret-option { position: relative; }
.secret-option input[type="radio"] { position: absolute; opacity: 0; pointer-events: none; }
.secret-option label { display: block; padding: 10px 12px; border: 2px solid #e8f4f8; border-radius: 10px; cursor: pointer; transition: all 0.3s ease; background: #f8fafc; font-size: 0.82rem; font-weight: 600; color: #003D7A; }
.secret-option label:hover { border-color: #0066CC; background: #eef5fc; }
.secret-option input[type="radio"]:checked + label { border-color: #0066CC; background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%); color: #003D7A; box-shadow: 0 2px 8px rgba(0, 102, 204, 0.15); }
.secret-option-title { display: flex; align-items: center; gap: 6px; margin-bottom: 2px; }
.secret-option-title i { color: #0066CC; font-size: 1rem; }
.secret-option-desc { font-size: 0.72rem; color: #666; font-weight: 400; margin-top: 2px; }

.btn-modern { padding: 10px 20px; border: none; border-radius: 10px; font-size: 0.9rem; font-weight: 600; cursor: pointer; transition: all 0.3s ease; display: inline-flex; align-items: center; justify-content: center; gap: 6px; text-decoration: none; }
.btn-modern.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3); }
.btn-modern.primary:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(0, 102, 204, 0.4); }
.btn-modern.secondary { background: white; color: #666; border: 2px solid #e8f4f8; }
.btn-modern.secondary:hover { background: #f8fafc; border-color: #0066CC; color: #0066CC; }
.btn-group-modern { display: flex; gap: 10px; margin-top: 16px; padding-top: 16px; border-top: 1px dashed #e8f4f8; }

@media (max-width: 768px) {
    .navbar-modern { padding: 12px 15px; }
    .navbar-title { font-size: 1rem; }
    .navbar-subtitle, .navbar-badge { display: none; }
    .main-content { padding: 12px; }
    .page-title { font-size: 1.2rem; }
    .form-card-body { padding: 14px 16px; }
    .form-grid, .form-grid.triple { grid-template-columns: 1fr; gap: 10px; }
    .secret-toggle { grid-template-columns: 1fr; }
    .btn-group-modern { flex-direction: column; }
    .btn-modern { width: 100%; padding: 11px; }
    .form-control-modern, .form-select-modern { padding: 10px 12px; font-size: 0.9rem; }
    .schedule-grid { grid-template-columns: 1fr; gap: 8px; }
    .schedule-arrow { transform: rotate(90deg); font-size: 1.2rem; }
    .schedule-item { padding: 10px 8px; }
    .schedule-item-date { font-size: 0.78rem; }
}

@media (max-width: 480px) {
    .navbar-modern { padding: 10px 12px; }
    .burger-btn { width: 36px; height: 36px; font-size: 1.1rem; }
    .navbar-title { font-size: 0.95rem; }
    .main-content { padding: 10px; }
    .page-title { font-size: 1.1rem; }
    .form-card-header { padding: 12px 16px; font-size: 0.9rem; }
    .form-card-body { padding: 12px 14px; }
    .form-section { margin-bottom: 12px; padding-bottom: 12px; }
    .section-title { font-size: 0.88rem; }
    .secret-option label { padding: 8px 10px; font-size: 0.8rem; }
    .form-label-modern { font-size: 0.8rem; }
    .schedule-info-box { padding: 12px; }
    .schedule-info-title { font-size: 0.82rem; }
    .schedule-item-icon { font-size: 1.2rem; }
}
</style>

<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">Edit Pelanggan</h1>
            <p class="navbar-subtitle">Update data & sinkron MikroTik</p>
        </div>
    </div>
    <div class="navbar-right">
        <span class="navbar-badge">
            <i class="bi bi-shield-lock-fill"></i> Super Admin Mode
        </span>
    </div>
</div>

<div class="main-content">
    <h2 class="page-title">
        <i class="bi bi-person-lines-fill"></i>
        <span>Edit Pelanggan</span>
        <span class="branch-badge">
            <i class="bi bi-building"></i>
            <?php
                $branchName = '-';
                foreach ($branches as $b) {
                    if ($b['id'] == $customer['branch_id']) {
                        $branchName = $b['name'];
                        break;
                    }
                }
                echo htmlspecialchars($branchName);
            ?>
        </span>
        <span class="customer-badge">
            <i class="bi bi-person-circle"></i>
            <?= htmlspecialchars($customer['name']) ?>
        </span>
        <span class="super-badge">
            <i class="bi bi-shield-fill-check"></i>
            Super Admin
        </span>
    </h2>

    <?php if ($error): ?>
        <div class="alert-modern danger">
            <i class="bi bi-exclamation-circle-fill"></i>
            <div><?= htmlspecialchars($error) ?></div>
        </div>
    <?php endif; ?>

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

    <!-- ⭐ SCHEDULE INFO BOX -->
    <div class="schedule-info-box">
        <div class="schedule-info-title">
            <i class="bi bi-calendar3"></i>
            <span>Informasi Jadwal Pembayaran</span>
            <span class="edit-badge" id="scheduleEditBadge" style="display: none;">
                <i class="bi bi-pencil-fill"></i> Mode Edit Jatuh Tempo
            </span>
            <span class="lock-badge">
                <i class="bi bi-unlock-fill"></i> Super Admin
            </span>
        </div>
        
        <div class="schedule-grid">
            <!-- Tanggal Instalasi -->
            <div class="schedule-item installation">
                <div class="schedule-item-icon">📅</div>
                <div class="schedule-item-label">Tanggal Instalasi</div>
                <div class="schedule-item-date"><?= $installationDateFormatted ?></div>
                <div class="schedule-item-status success">
                    <i class="bi bi-check-circle-fill"></i> Tetap
                </div>
            </div>
            
            <div class="schedule-arrow">→</div>
            
            <!-- Jatuh Tempo -->
            <div class="schedule-item due-date" id="currentDueDateBox">
                <div class="schedule-item-icon">⏰</div>
                <div class="schedule-item-label">Jatuh Tempo</div>
                <div class="schedule-item-date"><?= $dueDateFormatted ?></div>
                <div class="schedule-item-status <?= $dueStatusClass ?>">
                    <?= $dueStatusIcon ?> <?= $dueCountdown ?>
                </div>
            </div>
            
            <div class="schedule-arrow">→</div>
            
            <!-- Masa Aktif -->
            <div class="schedule-item active-until">
                <div class="schedule-item-icon">✅</div>
                <div class="schedule-item-label">Masa Aktif Sampai</div>
                <div class="schedule-item-date"><?= $activeUntilFormatted ?></div>
                <div class="schedule-item-status <?= $activeClass ?>">
                    <?= $activeStatus ?>
                </div>
            </div>
        </div>
        
        <!-- ⭐ PERBAIKAN: Info periode masa aktif yang jelas -->
        <div class="period-info">
            <i class="bi bi-info-circle-fill"></i>
            <div>
                <strong>Periode Layanan:</strong> <?= $activePeriodDays ?> hari 
                (dari <?= $dueDateFormatted ?> sampai <?= $activeUntilFormatted ?>)
            </div>
        </div>
        
        <!-- ⭐ PREVIEW JADWAL BARU -->
        <div id="newSchedulePreview" style="display: none; margin-top: 12px;">
            <div class="schedule-grid">
                <div class="schedule-item installation" style="opacity: 0.5;">
                    <div class="schedule-item-icon">📅</div>
                    <div class="schedule-item-label">Tanggal Instalasi</div>
                    <div class="schedule-item-date"><?= $installationDateFormatted ?></div>
                    <div class="schedule-item-status success">
                        <i class="bi bi-check-circle-fill"></i> Tetap
                    </div>
                </div>
                
                <div class="schedule-arrow">→</div>
                
                <div class="schedule-item due-date preview">
                    <div class="schedule-item-icon">🆕</div>
                    <div class="schedule-item-label">Jatuh Tempo BARU</div>
                    <div class="schedule-item-date" id="newDueDatePreview">-</div>
                    <div class="schedule-item-status preview" id="newDueCountdown">-</div>
                </div>
                
                <div class="schedule-arrow">→</div>
                
                <div class="schedule-item active-until preview">
                    <div class="schedule-item-icon">🆕</div>
                    <div class="schedule-item-label">Masa Aktif BARU</div>
                    <div class="schedule-item-date" id="newActiveUntilPreview">-</div>
                    <div class="schedule-item-status preview" id="newActiveStatus">-</div>
                </div>
            </div>
            
            <div class="schedule-note preview-note">
                <i class="bi bi-info-circle-fill"></i>
                <div>
                    <strong>Preview:</strong> Jika jatuh tempo diubah ke <strong id="newDueDayDisplay">-</strong>, 
                    jadwal akan berubah seperti di atas. Periode layanan tetap <strong>30 hari</strong>.
                </div>
            </div>
        </div>
        
        <div class="schedule-note">
            <i class="bi bi-lightbulb-fill"></i>
            <div>
                <strong>Info:</strong> Sebagai Super Admin, Anda dapat mengubah tanggal jatuh tempo pelanggan. 
                Geser dropdown "Jatuh Tempo" di form bawah untuk melihat preview perubahan.
            </div>
        </div>
    </div>

    <!-- FORM CARD -->
    <div class="form-card">
        <div class="form-card-header">
            <div class="header-left">
                <i class="bi bi-pencil-square"></i>
                <span>Form Edit Pelanggan</span>
            </div>
            <span class="customer-number">
                <i class="bi bi-hash"></i> #<?= htmlspecialchars($customer['customer_number']) ?>
            </span>
        </div>
        <div class="form-card-body">
            <form method="POST" id="customerForm">
                <?= csrfField() ?>
                
                <!-- SECTION 1: DATA PELANGGAN -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="bi bi-person-fill"></i>
                        <span>Data Pelanggan</span>
                    </h3>
                    
                    <div class="form-grid">
                        <div class="form-group">
                            <label class="form-label-modern">
                                <i class="bi bi-building"></i>
                                Cabang <span class="required">*</span>
                            </label>
                            <select name="branch_id" class="form-select-modern" required>
                                <option value="">-- Pilih Cabang --</option>
                                <?php foreach ($branches as $b): ?>
                                    <option value="<?= $b['id'] ?>" <?= $customer['branch_id'] == $b['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($b['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label-modern">
                                <i class="bi bi-person"></i>
                                Nama Lengkap <span class="required">*</span>
                            </label>
                            <input type="text" name="name" class="form-control-modern" 
                                   value="<?= htmlspecialchars($customer['name']) ?>" required>
                        </div>
                    </div>
                    
<div class="form-grid triple">
    <div class="form-group">
        <label class="form-label-modern">
            <i class="bi bi-telephone"></i>
            No. HP <span class="required">*</span>
        </label>
        <input type="text" name="phone" class="form-control-modern" 
               value="<?= htmlspecialchars($customer['phone']) ?>" required>
    </div>
    <div class="form-group">
        <label class="form-label-modern">
            <i class="bi bi-envelope"></i>
            Email
        </label>
        <input type="email" name="email" class="form-control-modern" 
               value="<?= htmlspecialchars($customer['email'] ?? '') ?>">
    </div>
    <div class="form-group">
        <label class="form-label-modern">
            <i class="bi bi-calendar-event"></i>
            ⭐ Jatuh Tempo (Bisa Diubah) <span class="required">*</span>
        </label>
        <select name="due_day" id="due_day_select" class="form-select-modern" required onchange="updateSchedulePreview()">
            <?php 
            // ⭐ Hitung tanggal jatuh tempo untuk setiap pilihan (instalasi + 1 bulan)
            $instDateObj = new DateTime($installationDate);
            for ($i = 1; $i <= 28; $i++): 
                $previewDueDate = clone $instDateObj;
                $previewDueDate->modify('+1 month');
                $maxDayInMonth = (int)$previewDueDate->format('t');
                $previewDueDate->setDate(
                    (int)$previewDueDate->format('Y'), 
                    (int)$previewDueDate->format('m'), 
                    min($i, $maxDayInMonth)
                );
                $previewDateFormatted = formatTanggal($previewDueDate->format('Y-m-d'), $hariIndonesia, $bulanIndonesia);
                $isSelected = ($customer['due_day'] == $i);
            ?>
                <option value="<?= $i ?>" <?= $isSelected ? 'selected' : '' ?> 
                        data-preview="<?= $previewDateFormatted ?>">
                    <?= $previewDateFormatted ?>
                    <?= $isSelected ? ' ← Saat ini' : '' ?>
                </option>
            <?php endfor; ?>
        </select>
        <small class="form-hint">
            <i class="bi bi-info-circle"></i>
            Saat ini: <strong><?= formatTanggal($dueDate, $hariIndonesia, $bulanIndonesia) ?></strong> 
            (Tanggal <?= $currentDueDay ?> setiap bulan)
        </small>
    </div>
</div>
                    
                    <div class="form-grid single">
                        <div class="form-group">
                            <label class="form-label-modern">
                                <i class="bi bi-geo-alt"></i>
                                Alamat
                            </label>
                            <textarea name="address" class="form-control-modern" rows="2"><?= htmlspecialchars($customer['address'] ?? '') ?></textarea>
                        </div>
                    </div>
                </div>

                <!-- SECTION 2: PPPoE CONFIGURATION -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="bi bi-router-fill"></i>
                        <span>Konfigurasi PPPoE</span>
                        <span class="section-badge"><?= $mtConnected ? '🟢 MikroTik OK' : '🔴 Offline' ?></span>
                    </h3>
                    
                    <div class="warning-box" style="margin-top: 0; margin-bottom: 12px;">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <span>Mengubah username/password PPPoE akan mempengaruhi koneksi internet customer.</span>
                    </div>
                    
                    <div class="secret-toggle">
                        <div class="secret-option">
                            <input type="radio" name="secret_option" id="secret_edit" value="edit" checked onchange="toggleSecretOption()">
                            <label for="secret_edit">
                                <div class="secret-option-title">
                                    <i class="bi bi-pencil-fill"></i>
                                    <span>Edit Secret</span>
                                </div>
                                <div class="secret-option-desc">Ubah username/password PPPoE</div>
                            </label>
                        </div>
                        <div class="secret-option">
                            <input type="radio" name="secret_option" id="secret_existing" value="existing" onchange="toggleSecretOption()">
                            <label for="secret_existing">
                                <div class="secret-option-title">
                                    <i class="bi bi-link-45deg"></i>
                                    <span>Pakai Secret Lain</span>
                                </div>
                                <div class="secret-option-desc">Switch ke secret yang sudah ada</div>
                            </label>
                        </div>
                    </div>
                    
                    <div id="edit_secret_fields">
                        <div class="form-grid">
                            <div class="form-group">
                                <label class="form-label-modern">
                                    <i class="bi bi-person-badge"></i>
                                    Username PPPoE <span class="required">*</span>
                                </label>
                                <input type="text" name="pppoe_username" id="pppoe_username_edit" class="form-control-modern" 
                                       value="<?= htmlspecialchars($customer['pppoe_username']) ?>" required>
                                <div class="current-value">
                                    <i class="bi bi-info-circle"></i>
                                    Saat ini: <strong><?= htmlspecialchars($customer['pppoe_username']) ?></strong>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="form-label-modern">
                                    <i class="bi bi-key-fill"></i>
                                    Password PPPoE <span class="required">*</span>
                                </label>
                                <input type="text" name="pppoe_password" id="pppoe_password_edit" class="form-control-modern" 
                                       value="<?= htmlspecialchars($customer['pppoe_password']) ?>" required>
                                <div class="current-value">
                                    <i class="bi bi-info-circle"></i>
                                    Saat ini: <strong><?= htmlspecialchars($customer['pppoe_password']) ?></strong>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div id="existing_secret_fields" style="display: none;">
                        <div class="form-grid">
                            <div class="form-group">
                                <label class="form-label-modern">
                                    <i class="bi bi-list-check"></i>
                                    Pilih Secret <span class="required">*</span>
                                </label>
                                <select name="pppoe_username_existing" id="pppoe_username_existing" class="form-select-modern">
                                    <option value="">-- Pilih Secret --</option>
                                    <?php foreach ($existingSecrets as $s): ?>
                                        <option value="<?= htmlspecialchars($s['name']) ?>" <?= $s['disabled'] ? 'disabled' : '' ?>>
                                            <?= htmlspecialchars($s['name']) ?> <?= $s['disabled'] ? '(Disabled)' : '' ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <small class="form-hint">
                                    <i class="bi bi-info-circle"></i>
                                    <?= count($existingSecrets) ?> secrets tersedia
                                </small>
                            </div>
                            <div class="form-group">
                                <label class="form-label-modern">
                                    <i class="bi bi-key-fill"></i>
                                    Password <span class="required">*</span>
                                </label>
                                <input type="text" name="pppoe_password_existing" id="pppoe_password_existing" class="form-control-modern" 
                                       placeholder="Samakan dengan di MikroTik">
                            </div>
                        </div>
                        <div class="warning-box">
                            <i class="bi bi-exclamation-triangle-fill"></i>
                            <span>Secret lama (<strong><?= htmlspecialchars($customer['pppoe_username']) ?></strong>) akan tetap ada di MikroTik tapi tidak dipakai lagi.</span>
                        </div>
                    </div>
                    
                    <input type="hidden" name="pppoe_username" id="final_username" value="<?= htmlspecialchars($customer['pppoe_username']) ?>">
                    <input type="hidden" name="pppoe_password" id="final_password" value="<?= htmlspecialchars($customer['pppoe_password']) ?>">
                    <input type="hidden" name="use_existing_secret" id="use_existing_flag" value="0">
                </div>

                <!-- SECTION 3: PAKET INTERNET -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="bi bi-box-fill"></i>
                        <span>Paket Internet</span>
                    </h3>
                    
                    <div class="form-grid">
                        <div class="form-group">
                            <label class="form-label-modern">
                                <i class="bi bi-speedometer2"></i>
                                Paket <span class="required">*</span>
                            </label>
                            <select name="package_id" class="form-select-modern" required>
                                <?php foreach ($packages as $p): ?>
                                    <option value="<?= $p['id'] ?>" <?= $customer['package_id'] == $p['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($p['name']) ?> - Rp <?= number_format($p['price']) ?>
                                        <?= $p['speed'] ? '(' . htmlspecialchars($p['speed']) . ')' : '' ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label-modern">
                                <i class="bi bi-hdd-network"></i>
                                IP Address (Opsional)
                            </label>
                            <input type="text" name="ip_address" class="form-control-modern" 
                                   value="<?= htmlspecialchars($customer['ip_address'] ?? '') ?>" 
                                   placeholder="192.168.1.100">
                            <small class="form-hint">
                                <i class="bi bi-info-circle"></i>
                                Kosongkan jika menggunakan IP dinamis
                            </small>
                        </div>
                    </div>
                </div>

                <div class="btn-group-modern">
                    <button type="submit" class="btn-modern primary" onclick="prepareForm()">
                        <i class="bi bi-save-fill"></i>
                        <span>Update & Sinkronkan</span>
                    </button>
                    <a href="/admin/customers.php" class="btn-modern secondary">
                        <i class="bi bi-x-circle"></i>
                        <span>Batal</span>
                    </a>
                </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 toggleSecretOption() {
    const isEdit = document.getElementById('secret_edit').checked;
    document.getElementById('edit_secret_fields').style.display = isEdit ? 'block' : 'none';
    document.getElementById('existing_secret_fields').style.display = isEdit ? 'none' : 'block';
    
    document.getElementById('pppoe_username_edit').required = isEdit;
    document.getElementById('pppoe_password_edit').required = isEdit;
    document.getElementById('pppoe_username_existing').required = !isEdit;
    document.getElementById('pppoe_password_existing').required = !isEdit;
}

function prepareForm() {
    const isEdit = document.getElementById('secret_edit').checked;
    
    if (isEdit) {
        document.getElementById('final_username').value = document.getElementById('pppoe_username_edit').value;
        document.getElementById('final_password').value = document.getElementById('pppoe_password_edit').value;
        document.getElementById('use_existing_flag').value = '0';
    } else {
        document.getElementById('final_username').value = document.getElementById('pppoe_username_existing').value;
        document.getElementById('final_password').value = document.getElementById('pppoe_password_existing').value;
        document.getElementById('use_existing_flag').value = '1';
    }
}

// ⭐ FORMAT TANGGAL BAHASA INDONESIA
const hariIndonesia = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
const bulanIndonesia = ['', 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];

// ⭐ FUNGSI FORMAT: "Hari, Tanggal Bulan Tahun"
function formatTanggal(date) {
    const hari = hariIndonesia[date.getDay()];
    const tanggal = date.getDate();
    const bulan = bulanIndonesia[date.getMonth() + 1];
    const tahun = date.getFullYear();
    return `${hari}, ${tanggal} ${bulan} ${tahun}`;
}

// ⭐ LIVE PREVIEW JADWAL BARU
function updateSchedulePreview() {
    const newDueDay = parseInt(document.getElementById('due_day_select').value);
    const currentDueDay = <?= $currentDueDay ?>;
    const installationDate = '<?= $installationDate ?>';
    
    const previewBox = document.getElementById('newSchedulePreview');
    const editBadge = document.getElementById('scheduleEditBadge');
    
    if (newDueDay === currentDueDay) {
        previewBox.style.display = 'none';
        editBadge.style.display = 'none';
        return;
    }
    
    // Hitung tanggal jatuh tempo baru
    const instDate = new Date(installationDate);
    const newDueDate = new Date(instDate);
    newDueDate.setMonth(newDueDate.getMonth() + 1);
    
    // Handle bulan dengan jumlah hari berbeda
    const maxDay = new Date(newDueDate.getFullYear(), newDueDate.getMonth() + 1, 0).getDate();
    newDueDate.setDate(Math.min(newDueDay, maxDay));
    
    // ⭐ PERBAIKAN: Masa aktif = jatuh tempo + 1 bulan
    const newActiveUntil = new Date(newDueDate);
    newActiveUntil.setMonth(newActiveUntil.getMonth() + 1);
    newActiveUntil.setHours(23, 59, 59);
    
    // Hitung countdown
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const diffTime = newDueDate - today;
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    
    let countdownText = '';
    if (diffDays > 0) {
        countdownText = `⏳ ${diffDays} hari lagi`;
    } else if (diffDays === 0) {
        countdownText = '🔥 HARI INI!';
    } else {
        countdownText = `⚠️ Terlambat ${Math.abs(diffDays)} hari`;
    }
    
    // Hitung periode masa aktif
    const activePeriodDays = Math.floor((newActiveUntil - newDueDate) / (1000 * 60 * 60 * 24));
    
    // Update preview dengan format "Hari, Tanggal Bulan Tahun"
    document.getElementById('newDueDatePreview').textContent = formatTanggal(newDueDate);
    document.getElementById('newDueCountdown').textContent = countdownText;
    
    document.getElementById('newActiveUntilPreview').textContent = formatTanggal(newActiveUntil);
    document.getElementById('newActiveStatus').textContent = `Periode: ${activePeriodDays} hari`;
    
    document.getElementById('newDueDayDisplay').textContent = `Tanggal ${newDueDay}`;
    
    previewBox.style.display = 'block';
    editBadge.style.display = 'inline-flex';
}

toggleSecretOption();
updateSchedulePreview();
</script>

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