<?php
// ==================== FUNGSI BANTU ====================
function generateFileName($originalName) {
    $extension = pathinfo($originalName, PATHINFO_EXTENSION);
    $date = date('YmdHis');
    $random = rand(10000, 99999);
    return $date . $random . '.' . $extension;
}

function deleteOldFile($filename) {
    if (!empty($filename) && file_exists($filename)) {
        unlink($filename);
    }
}

// ==================== PROSES simpan ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_settings'])) {
    $upload_dir = '../../assets/images/uploads/';
    
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    // Data form
    $fields = [
        'title', 'nama', 'subtitle', 'tagline', 'subtagline', 'deskripsi',
        'deskripsi_footer', 'alamat', 'telpon', 'email', 'about_us', 'no_rekening',
        'mata_uang', 'zona_waktu', 'terms_service', 'privacy_policy',
        'benefit_keanggotaan', 'buka_keanggotaan', 'payment_gateway',
        'mode_pemeliharaan', 'informasi'
    ];
    
    $data = [];
    foreach ($fields as $field) {
        $data[$field] = mysql_real_escape_string($_POST[$field]);
    }
    
    $data['biaya_keanggotaan'] = (int)$_POST['biaya_keanggotaan'];
    $data['biaya_perpanjangan'] = (int)$_POST['biaya_perpanjangan'];
    
    // File uploads
    $file_fields = [
        'logo' => ['input' => 'logo_file', 'old' => 'logo_old'],
        'gambar' => ['input' => 'gambar_file', 'old' => 'gambar_old'],
        'gambar_keanggotaan' => ['input' => 'gambar_keanggotaan_file', 'old' => 'gambar_keanggotaan_old']
    ];
    
    foreach ($file_fields as $key => $file) {
        $$key = mysql_real_escape_string($_POST[$file['old']]);
        
        if (!empty($_FILES[$file['input']]['name'])) {
            $old_file = $_POST[$file['old']];
            if (!empty($old_file) && $old_file != 'default.png') {
                deleteOldFile($upload_dir . basename($old_file));
            }
            
            $filename = generateFileName($_FILES[$file['input']]['name']);
            $tmp_name = $_FILES[$file['input']]['tmp_name'];
            $path = $upload_dir . $filename;
            
            if (move_uploaded_file($tmp_name, $path)) {
                $$key = $filename;
            } else {
                $_SESSION['error_message'] = "Gagal upload $key!";
            }
        }
    }
    
    // Validasi
    if (empty($data['title']) || empty($data['nama'])) {
        $_SESSION['error_message'] = "Judul Website dan Nama Organisasi wajib diisi!";
        header("Location: ?menu=settings");
        exit();
    }
    
    if ($data['biaya_keanggotaan'] < 0 || $data['biaya_perpanjangan'] < 0) {
        $_SESSION['error_message'] = "Biaya keanggotaan tidak boleh negatif!";
        header("Location: ?menu=settings");
        exit();
    }
    
    // Update database
    $update_query = "UPDATE konfigurasi SET 
        title = '{$data['title']}',
        nama = '{$data['nama']}',
        subtitle = '{$data['subtitle']}',
        logo = '$logo',
        gambar = '$gambar',
        tagline = '{$data['tagline']}',
        subtagline = '{$data['subtagline']}',
        deskripsi = '{$data['deskripsi']}',
        deskripsi_footer = '{$data['deskripsi_footer']}',
        alamat = '{$data['alamat']}',
        telpon = '{$data['telpon']}',
        email = '{$data['email']}',
        about_us = '{$data['about_us']}',
        no_rekening = '{$data['no_rekening']}',
        mata_uang = '{$data['mata_uang']}',
        zona_waktu = '{$data['zona_waktu']}',
        terms_service = '{$data['terms_service']}',
        privacy_policy = '{$data['privacy_policy']}',
        biaya_keanggotaan = '{$data['biaya_keanggotaan']}',
        biaya_perpanjangan = '{$data['biaya_perpanjangan']}',
        gambar_keanggotaan = '$gambar_keanggotaan',
        benefit_keanggotaan = '{$data['benefit_keanggotaan']}',
        buka_keanggotaan = '{$data['buka_keanggotaan']}',
        payment_gateway = '{$data['payment_gateway']}',
        mode_pemeliharaan = '{$data['mode_pemeliharaan']}',
        informasi = '{$data['informasi']}',
        updated = NOW()
        WHERE idweb = '$idweb'";
    
    $result = mysql_query($update_query);
    
    if ($result) {
        $_SESSION['success_message'] = "Pengaturan berhasil disimpan!";
        $query1 = mysql_query("SELECT * FROM konfigurasi WHERE idweb = '$idweb' LIMIT 1");
        $set    = mysql_fetch_array($query1);
    } else {
        $_SESSION['error_message'] = "Gagal menyimpan pengaturan: " . mysql_error();
    }
    
    echo "<script>window.location.href = '?menu=settings';</script>";
    exit();
}
?>

<style>
    /* Style konsisten dengan halaman lain */
    .setting-card {
        transition: all 0.3s ease;
        border: 1px solid var(--gray-200);
        border-radius: var(--border-radius);
        background: white;
    }
    
    .setting-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    
    .nav-tabs-custom {
        border-bottom: 1px solid #e2e8f0;
    }
    
    .nav-tabs-custom .nav-link {
        border: 1px solid transparent;
        border-top-left-radius: 8px;
        border-top-right-radius: 8px;
        padding: 0.75rem 1.25rem;
        color: #64748b;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .nav-tabs-custom .nav-link:hover {
        border-color: #e2e8f0;
        color: #4361ee;
    }
    
    .nav-tabs-custom .nav-link.active {
        background-color: white;
        border-color: #e2e8f0 #e2e8f0 #fff;
        color: #4361ee;
        font-weight: 600;
    }
    
    .tab-content-custom {
        background: white;
        border: 1px solid #e2e8f0;
        border-top: none;
        border-radius: 0 0 8px 8px;
        padding: 1.5rem;
    }
    
    .stat-card {
        background: white;
        border: 1px solid var(--gray-200);
        border-radius: var(--border-radius);
        transition: all 0.3s ease;
    }
    
    .stat-card:hover {
        box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    }
    
    .stat-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .setting-section {
        padding: 1.25rem;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        background: white;
        margin-bottom: 1.5rem;
    }
    
    .setting-section h5 {
        color: #1e293b;
        font-weight: 600;
        padding-bottom: 0.75rem;
        margin-bottom: 1rem;
        border-bottom: 2px solid #f1f5f9;
    }
    
    .form-label {
        font-weight: 500;
        color: #334155;
        margin-bottom: 0.5rem;
    }
    
    .form-control, .form-select {
        border: 1px solid #e2e8f0;
        border-radius: 6px;
        padding: 0.5rem 0.75rem;
        color: #334155;
    }
    
    .form-control:focus, .form-select:focus {
        border-color: #4361ee;
        box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
    }
    
    .img-preview {
        max-height: 100px;
        border-radius: 6px;
        border: 1px solid #e2e8f0;
        padding: 4px;
        background: white;
    }
    
    .info-badge {
        padding: 6px 12px;
        border-radius: 6px;
        font-size: 0.75rem;
        font-weight: 500;
        background-color: #f1f5f9;
        color: #64748b;
        border: 1px solid #e2e8f0;
    }
    
    /* Responsive adjustments */
    @media (max-width: 768px) {
        .nav-tabs-custom .nav-link {
            padding: 0.5rem 1rem;
            font-size: 0.9rem;
        }
        
        .setting-section {
            padding: 1rem;
        }
        
        .tab-content-custom {
            padding: 1rem;
        }
    }
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4 class="fw-bold mb-1">Pengaturan Sistem</h4>
        <p class="text-muted mb-0">Konfigurasi platform <?php echo htmlspecialchars($set['title']); ?></p>
    </div>
    <div>
        <button type="submit" form="settingsForm" name="save_settings" class="btn btn-primary">
            <i data-lucide="save" width="16"></i>
            simpan
        </button>
    </div>
</div>

<!-- ==================== NOTIFIKASI ==================== -->
<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
    <i data-lucide="check-circle" class="me-2"></i>
    <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <i data-lucide="alert-circle" class="me-2"></i>
    <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>


<form method="POST" action="" enctype="multipart/form-data" id="settingsForm">
    <!-- Tab Navigation -->
    <ul class="nav nav-tabs nav-tabs-custom" id="settingsTab" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#umum" type="button">
                <i data-lucide="settings" width="16"></i> Umum
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#konten" type="button">
                <i data-lucide="file-text" width="16"></i> Konten
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#kontak" type="button">
                <i data-lucide="phone" width="16"></i> Kontak
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#keanggotaan" type="button">
                <i data-lucide="users" width="16"></i> Keanggotaan
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#sistem" type="button">
                <i data-lucide="server" width="16"></i> Sistem
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#media" type="button">
                <i data-lucide="image" width="16"></i> Media
            </button>
        </li>
    </ul>
    
    <!-- Tab Content -->
    <div class="tab-content tab-content-custom" id="settingsTabContent">
        <!-- Tab Umum -->
        <div class="tab-pane fade show active" id="umum">
            <div class="setting-section">
                <h5 class="fw-bold mb-4">Informasi Dasar</h5>
                <div class="row g-3">
                    <!--<div class="col-md-6">-->
                    <!--    <label class="form-label fw-medium">ID Website</label>-->
                    <!--    <div class="d-flex align-items-center gap-2">-->
                    <!--        <input type="text" class="form-control" value="<?php echo htmlspecialchars($set['idweb']); ?>" readonly>-->
                    <!--        <span class="info-badge">Unik</span>-->
                    <!--    </div>-->
                    <!--</div>-->
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Judul Website *</label>
                        <input type="text" class="form-control" name="title" value="<?php echo htmlspecialchars($set['title']); ?>" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Nama Organisasi *</label>
                        <input type="text" class="form-control" name="nama" value="<?php echo htmlspecialchars($set['nama']); ?>" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Subjudul</label>
                        <input type="text" class="form-control" name="subtitle" value="<?php echo htmlspecialchars($set['subtitle']); ?>">
                    </div>
                </div>
            </div>
            
            <div class="setting-section">
                <h5 class="fw-bold mb-4">Tagline & Deskripsi</h5>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Tagline</label>
                        <input type="text" class="form-control" name="tagline" value="<?php echo htmlspecialchars($set['tagline']); ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Sub Tagline</label>
                        <textarea class="form-control" name="subtagline" rows="2"><?php echo htmlspecialchars($set['subtagline']); ?></textarea>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-medium">Deskripsi Utama</label>
                        <textarea class="form-control" name="deskripsi" rows="3"><?php echo htmlspecialchars($set['deskripsi']); ?></textarea>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Tab Konten -->
        <div class="tab-pane fade" id="konten">
            <div class="setting-section">
                <h5 class="fw-bold mb-4">Konten Website</h5>
                <div class="row g-3">
                    <div class="col-12">
                        <label class="form-label fw-medium">Tentang Kami (About Us)</label>
                        <textarea class="form-control" name="about_us" rows="5"><?php echo htmlspecialchars($set['about_us']); ?></textarea>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-medium">Syarat Layanan (Terms of Service)</label>
                        <textarea class="form-control" name="terms_service" rows="3"><?php echo htmlspecialchars($set['terms_service']); ?></textarea>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-medium">Kebijakan Privasi (Privacy Policy)</label>
                        <textarea class="form-control" name="privacy_policy" rows="3"><?php echo htmlspecialchars($set['privacy_policy']); ?></textarea>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-medium">Deskripsi Footer</label>
                        <textarea class="form-control" name="deskripsi_footer" rows="2"><?php echo htmlspecialchars($set['deskripsi_footer']); ?></textarea>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-medium">Nomor Rekening</label>
                        <textarea class="form-control" name="no_rekening" rows="2"><?php echo htmlspecialchars($set['no_rekening']); ?></textarea>
                        <small class="text-muted">Pisahkan dengan baris baru</small>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Tab Kontak -->
        <div class="tab-pane fade" id="kontak">
            <div class="setting-section">
                <h5 class="fw-bold mb-4">Kontak & Alamat</h5>
                <div class="row g-3">
                    <div class="col-12">
                        <label class="form-label fw-medium">Alamat Lengkap</label>
                        <textarea class="form-control" name="alamat" rows="3"><?php echo htmlspecialchars($set['alamat']); ?></textarea>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Telepon</label>
                        <input type="text" class="form-control" name="telpon" value="<?php echo htmlspecialchars($set['telpon']); ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Email</label>
                        <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($set['email']); ?>">
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Tab Keanggotaan -->
        <div class="tab-pane fade" id="keanggotaan">
            <div class="setting-section">
                <h5 class="fw-bold mb-4">Pengaturan Keanggotaan</h5>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Biaya Keanggotaan (Rp)</label>
                        <input type="number" class="form-control" name="biaya_keanggotaan" value="<?php echo (int)$set['biaya_keanggotaan']; ?>" min="0">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Biaya Perpanjangan (Rp)</label>
                        <input type="number" class="form-control" name="biaya_perpanjangan" value="<?php echo (int)$set['biaya_perpanjangan']; ?>" min="0">
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-medium">Benefit Keanggotaan</label>
                        <textarea class="form-control" name="benefit_keanggotaan" rows="3"><?php echo htmlspecialchars($set['benefit_keanggotaan']); ?></textarea>
                        <small class="text-muted">Pisahkan dengan titik koma (;)</small>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Buka Pendaftaran Keanggotaan</label>
                        <select class="form-select" name="buka_keanggotaan">
                            <option value="Y" <?php echo $set['buka_keanggotaan'] == 'Y' ? 'selected' : ''; ?>>Ya, Terbuka</option>
                            <option value="T" <?php echo $set['buka_keanggotaan'] == 'T' ? 'selected' : ''; ?>>Tidak, Tertutup</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Tab Sistem -->
        <div class="tab-pane fade" id="sistem">
            <div class="setting-section">
                <h5 class="fw-bold mb-4">Pengaturan Sistem</h5>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Mata Uang</label>
                        <input type="text" class="form-control" name="mata_uang" value="<?php echo htmlspecialchars($set['mata_uang']); ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Zona Waktu</label>
                        <select class="form-select" name="zona_waktu">
                            <option value="Asia/Jakarta" <?php echo $set['zona_waktu'] == 'Asia/Jakarta' ? 'selected' : ''; ?>>Asia/Jakarta (WIB)</option>
                            <option value="Asia/Makassar" <?php echo $set['zona_waktu'] == 'Asia/Makassar' ? 'selected' : ''; ?>>Asia/Makassar (WITA)</option>
                            <option value="Asia/Jayapura" <?php echo $set['zona_waktu'] == 'Asia/Jayapura' ? 'selected' : ''; ?>>Asia/Jayapura (WIT)</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Payment Gateway</label>
                        <input type="text" class="form-control" name="payment_gateway" value="<?php echo htmlspecialchars($set['payment_gateway']); ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Mode Pemeliharaan</label>
                        <select class="form-select" name="mode_pemeliharaan">
                            <option value="T" <?php echo $set['mode_pemeliharaan'] == 'T' ? 'selected' : ''; ?>>Normal</option>
                            <option value="Y" <?php echo $set['mode_pemeliharaan'] == 'Y' ? 'selected' : ''; ?>>Maintenance</option>
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-medium">Informasi Sistem</label>
                        <textarea class="form-control" name="informasi" rows="3"><?php echo htmlspecialchars($set['informasi']); ?></textarea>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Tab Media -->
        <div class="tab-pane fade" id="media">
            <div class="setting-section">
                <h5 class="fw-bold mb-4">Media & Gambar</h5>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Logo Website</label>
                        <input type="file" class="form-control" name="logo_file" accept="image/*" onchange="previewImage(this, 'logoPreview')">
                        <input type="hidden" name="logo_old" value="<?php echo htmlspecialchars($set['logo']); ?>">
                        <div class="mt-2">
                            <?php if (!empty($set['logo'])): ?>
                            <div class="d-flex align-items-center gap-3">
                                <img src="<?= $http?>assets/images/uploads/<?php echo htmlspecialchars($set['logo']); ?>" 
                                     id="logoPreview" class="img-preview">
                                <span class="text-muted small">Logo saat ini</span>
                            </div>
                            <?php else: ?>
                            <img src="" id="logoPreview" class="img-preview d-none">
                            <?php endif; ?>
                        </div>
                        <small class="text-muted">Ukuran maksimal 2MB, format: JPG, PNG, GIF</small>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Gambar Utama</label>
                        <input type="file" class="form-control" name="gambar_file" accept="image/*" onchange="previewImage(this, 'gambarPreview')">
                        <input type="hidden" name="gambar_old" value="<?php echo htmlspecialchars($set['gambar']); ?>">
                        <div class="mt-2">
                            <?php if (!empty($set['gambar'])): ?>
                            <div class="d-flex align-items-center gap-3">
                                <img src="<?= $http?>assets/images/uploads/<?php echo htmlspecialchars($set['gambar']); ?>" 
                                     id="gambarPreview" class="img-preview">
                                <span class="text-muted small">Gambar saat ini</span>
                            </div>
                            <?php else: ?>
                            <img src="" id="gambarPreview" class="img-preview d-none">
                            <?php endif; ?>
                        </div>
                        <small class="text-muted">Ukuran maksimal 2MB, format: JPG, PNG, GIF</small>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-medium">Gambar Keanggotaan</label>
                        <input type="file" class="form-control" name="gambar_keanggotaan_file" accept="image/*" onchange="previewImage(this, 'keanggotaanPreview')">
                        <input type="hidden" name="gambar_keanggotaan_old" value="<?php echo htmlspecialchars($set['gambar_keanggotaan']); ?>">
                        <div class="mt-2" id="keanggotaanPreviewContainer">
                            <?php if (!empty($set['gambar_keanggotaan'])): ?>
                            <div class="d-flex align-items-center gap-3">
                                <img src="<?= $http?>assets/images/uploads/<?php echo htmlspecialchars($set['gambar_keanggotaan']); ?>" 
                                     id="keanggotaanPreview" class="img-preview">
                                <span class="text-muted small">Gambar saat ini</span>
                            </div>
                            <?php else: ?>
                            <img src="" id="keanggotaanPreview" class="img-preview d-none">
                            <?php endif; ?>
                        </div>
                        <small class="text-muted">Ukuran maksimal 2MB, format: JPG, PNG, GIF</small>
                    </div>
                </div>
            </div>
            
   
        </div>
    </div>
    
             <!-- Informasi Update -->
            <div class="alert alert-info mt-4">
                <div class="d-flex align-items-center">
                    <i data-lucide="info" class="me-2 flex-shrink-0"></i>
                    <div>
                        <strong>Terakhir diupdate:</strong> 
                        <?php echo $set['updated'] == '0000-00-00 00:00:00' ? 'Belum pernah diupdate' : date('d M Y H:i:s', strtotime($set['updated'])); ?>
                        <br>
                        <small class="text-muted">Semua perubahan akan diterapkan secara langsung setelah disimpan</small>
                    </div>
                </div>
            </div>
    
    <div class="d-flex justify-content-between align-items-center mt-4 pt-3 border-top">
        <div class="text-muted small">
            <i data-lucide="alert-circle" width="14" class="me-1"></i>
            Field dengan tanda * wajib diisi
        </div>
        <div>
            <button type="submit" name="save_settings" class="btn btn-primary">
                <i data-lucide="save" width="16"></i>
                Simpan
            </button>
        </div>
    </div>
</form>

<script>
// Preview gambar
function previewImage(input, previewId) {
    const preview = document.getElementById(previewId);
    const file = input.files[0];
    
    if (file) {
        // Validasi ukuran file (max 2MB)
        if (file.size > 2 * 1024 * 1024) {
            alert('Ukuran file maksimal 2MB');
            input.value = '';
            return;
        }
        
        // Validasi tipe file
        const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
        if (!validTypes.includes(file.type)) {
            alert('Format file harus JPG, PNG, atau GIF');
            input.value = '';
            return;
        }
        
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.classList.remove('d-none');
        }
        reader.readAsDataURL(file);
    }
}

// Validasi form sebelum submit
document.getElementById('settingsForm').addEventListener('submit', function(e) {
    const requiredFields = this.querySelectorAll('[required]');
    let isValid = true;
    
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            isValid = false;
            field.classList.add('is-invalid');
            
            // Scroll ke field yang error
            if (!field.closest('.tab-pane').classList.contains('active')) {
                const tabId = field.closest('.tab-pane').id;
                const tabButton = document.querySelector(`[data-bs-target="#${tabId}"]`);
                if (tabButton) {
                    new bootstrap.Tab(tabButton).show();
                }
            }
        } else {
            field.classList.remove('is-invalid');
        }
    });
    
    // Validasi biaya keanggotaan tidak negatif
    const biayaKeanggotaan = document.querySelector('input[name="biaya_keanggotaan"]');
    const biayaPerpanjangan = document.querySelector('input[name="biaya_perpanjangan"]');
    
    if (biayaKeanggotaan && parseInt(biayaKeanggotaan.value) < 0) {
        isValid = false;
        biayaKeanggotaan.classList.add('is-invalid');
        alert('Biaya keanggotaan tidak boleh negatif!');
    }
    
    if (biayaPerpanjangan && parseInt(biayaPerpanjangan.value) < 0) {
        isValid = false;
        biayaPerpanjangan.classList.add('is-invalid');
        alert('Biaya perpanjangan tidak boleh negatif!');
    }
    
    if (!isValid) {
        e.preventDefault();
        // Tampilkan pesan error di bagian atas
        const errorAlert = document.createElement('div');
        errorAlert.className = 'alert alert-danger alert-dismissible fade show';
        errorAlert.innerHTML = `
            <i data-lucide="alert-circle" class="me-2"></i>
            Harap lengkapi semua field yang wajib diisi dan periksa kembali data Anda!
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        const existingAlert = document.querySelector('.alert-danger');
        if (!existingAlert) {
            const form = document.querySelector('form');
            form.parentNode.insertBefore(errorAlert, form);
            
            // Update icons
            setTimeout(() => lucide.createIcons(), 100);
        }
        
        // Scroll ke atas
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
});

// Auto reload lucide icons
if (window.history.replaceState) {
    window.history.replaceState(null, null, window.location.href);
}

// Inisialisasi tooltips
document.addEventListener('DOMContentLoaded', function() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    const tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});

// Tampilkan ikon lucide setelah tab diubah
document.querySelectorAll('#settingsTab button').forEach(button => {
    button.addEventListener('shown.bs.tab', function () {
        setTimeout(() => lucide.createIcons(), 100);
    });
});
</script>