<?php
    $pageTitle = 'Kelola Layanan';
    if (!Auth::isLoggedIn() || $_SESSION['user_role'] !== 'admin') { redirect(base_url('login')); }

    $initialStatusFilter = $_GET['status'] ?? 'all';
    $initialCategoryFilter = $_GET['category_id'] ?? 'all';
    $initialProviderFilter = $_GET['provider_id'] ?? 'all';
    $initialSearchQuery = $_GET['search'] ?? '';
    $initialLimit = $_GET['limit'] ?? 15;

    $statusOptionsServices = [
        'all' => 'Semua Status',
        'active' => 'Aktif',
        'inactive' => 'Nonaktif',
    ];
     $searchColumnOptionsServices = [
        's.id' => 'ID Layanan (SMM)',
        's.provider_service_id' => 'ID Layanan (Provider)',
        's.name' => 'Nama Layanan',
        'c.name' => 'Nama Kategori',
        'p.name' => 'Nama Provider',
    ];
     $sortColumnOptionsServices = [
        's.name' => 'Nama Layanan',
        's.id' => 'ID Layanan (SMM)',
        'c.name' => 'Kategori',
        'p.name' => 'Provider',
        's.price_per_1000' => 'Harga/1k',
        's.min_order' => 'Min Pesan',
        's.max_order' => 'Maks Pesan',
        's.status' => 'Status',
        's.created_at' => 'Tgl Dibuat',
        's.updated_at' => 'Tgl Update',
    ];
    $sortTypeOptionsServices = ['ASC' => 'A-Z / Terendah', 'DESC' => 'Z-A / Tertinggi'];

    $categoriesForFilter = [];
    $providersForFilter = [];
    try {
        $stmtCat = $pdo->query("SELECT id, name FROM categories ORDER BY name ASC");
        $categoriesForFilter = $stmtCat->fetchAll(PDO::FETCH_ASSOC);
        $stmtProv = $pdo->query("SELECT id, name FROM providers ORDER BY name ASC");
        $providersForFilter = $stmtProv->fetchAll(PDO::FETCH_ASSOC);
    } catch (\PDOException $e) {
        error_log("Error fetching categories/providers for filter: " . $e->getMessage());
    }

    ?>
    <main class="flex-1 overflow-x-hidden overflow-y-auto p-6 md:p-8">
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
            <h2 class="text-2xl font-semibold text-gray-700 flex items-center">
                <i class="fas fa-list-alt mr-3 text-cyan-500"></i> Kelola Layanan
            </h2>
            <div class="flex items-center space-x-2">
                 <button type="button" id="admin-service-filter-modal-button"
                        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition">
                    <i class="fas fa-filter mr-1"></i> Filter
                </button>
                <button type="button" id="add-service-button"
                   class="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-lg shadow hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition">
                    <i class="fas fa-plus mr-1"></i> Tambah Layanan
                </button>
            </div>
        </div>

        <div id="admin-services-message" class="mb-4 text-sm"></div>

        <div class="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                            <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Layanan</th>
                            <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kategori</th>
                            <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Provider</th>
                            <th scope="col" class="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">ID Prov</th>
                            <th scope="col" class="px-3 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Harga/1k</th>
                            <th scope="col" class="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Min</th>
                            <th scope="col" class="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Maks</th>
                            <th scope="col" class="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                            <th scope="col" class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                        </tr>
                    </thead>
                    <tbody id="admin-services-table-body" class="bg-white divide-y divide-gray-200">
                        <tr>
                            <td colspan="10" class="px-6 py-10 text-center text-sm text-gray-500 italic">
                                <i class="fas fa-spinner fa-spin mr-2"></i> Memuat data layanan...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
             <div id="admin-services-pagination-container" class="px-4 py-3 border-t border-gray-200 bg-gray-50 text-xs text-gray-600 flex flex-col sm:flex-row justify-between items-center">
                <div id="admin-services-pagination-info">Menampilkan 0 hasil.</div>
                <div id="admin-services-pagination-controls" class="flex justify-end mt-2 sm:mt-0 space-x-1"></div>
            </div>
        </div>

        <div id="admin-service-filter-modal" class="fixed inset-0 z-50 hidden items-center justify-center bg-black bg-opacity-60 transition-opacity duration-300 ease-in-out p-4" aria-labelledby="admin-service-filter-modal-title" role="dialog" aria-modal="true">
            <div class="relative bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl mx-auto transform transition-all duration-300 ease-in-out scale-95 opacity-0" id="admin-service-filter-modal-content">
                <div class="flex items-center justify-between px-6 py-4 border-b border-gray-700">
                    <h3 class="text-lg font-semibold text-gray-100 flex items-center" id="admin-service-filter-modal-title">
                        <i class="fas fa-filter mr-2 text-blue-400"></i> Filter Layanan
                    </h3>
                    <button type="button" id="close-admin-service-filter-modal" class="text-gray-400 hover:text-white focus:outline-none">
                        <span class="sr-only">Tutup</span><i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                <form id="admin-service-filter-form" class="p-6 space-y-4">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                            <label for="filter_limit_admin_service" class="block text-sm font-medium text-gray-300 mb-1">Tampilkan</label>
                            <select id="filter_limit_admin_service" name="limit" class="admin-service-filter-input w-full px-3 py-2 text-sm bg-gray-700 border border-gray-600 text-gray-100 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                                <option value="15" <?php echo ($initialLimit == 15) ? 'selected' : ''; ?>>15 baris</option>
                                <option value="30" <?php echo ($initialLimit == 30) ? 'selected' : ''; ?>>30 baris</option>
                                <option value="50" <?php echo ($initialLimit == 50) ? 'selected' : ''; ?>>50 baris</option>
                                <option value="100" <?php echo ($initialLimit == 100) ? 'selected' : ''; ?>>100 baris</option>
                                <option value="250" <?php echo ($initialLimit == 250) ? 'selected' : ''; ?>>250 baris</option>
                            </select>
                        </div>
                        <div>
                            <label for="filter_status_admin_service" class="block text-sm font-medium text-gray-300 mb-1">Status</label>
                            <select id="filter_status_admin_service" name="status" class="admin-service-filter-input w-full px-3 py-2 text-sm bg-gray-700 border border-gray-600 text-gray-100 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                                <?php foreach ($statusOptionsServices as $value => $label): ?>
                                    <option value="<?php echo $value; ?>" <?php echo ($initialStatusFilter === $value) ? 'selected' : ''; ?>><?php echo htmlspecialchars($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                         <div>
                            <label for="filter_category_admin_service" class="block text-sm font-medium text-gray-300 mb-1">Kategori</label>
                            <select id="filter_category_admin_service" name="category_id" class="admin-service-filter-input w-full px-3 py-2 text-sm bg-gray-700 border border-gray-600 text-gray-100 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                                <option value="all">Semua Kategori</option>
                                <?php foreach ($categoriesForFilter as $category): ?>
                                    <option value="<?php echo $category['id']; ?>" <?php echo ($initialCategoryFilter == $category['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($category['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                     <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                         <div>
                            <label for="filter_provider_admin_service" class="block text-sm font-medium text-gray-300 mb-1">Provider</label>
                            <select id="filter_provider_admin_service" name="provider_id" class="admin-service-filter-input w-full px-3 py-2 text-sm bg-gray-700 border border-gray-600 text-gray-100 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                                <option value="all">Semua Provider</option>
                                <?php foreach ($providersForFilter as $provider): ?>
                                    <option value="<?php echo $provider['id']; ?>" <?php echo ($initialProviderFilter == $provider['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($provider['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div></div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label for="filter_search_column_admin_service" class="block text-sm font-medium text-gray-300 mb-1">Kolom Cari</label>
                            <select id="filter_search_column_admin_service" name="search_column" class="admin-service-filter-input w-full px-3 py-2 text-sm bg-gray-700 border border-gray-600 text-gray-100 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                                <?php foreach ($searchColumnOptionsServices as $value => $label): ?>
                                    <option value="<?php echo $value; ?>"><?php echo htmlspecialchars($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label for="filter_search_keyword_admin_service" class="block text-sm font-medium text-gray-300 mb-1">Kata Kunci</label>
                            <input type="text" id="filter_search_keyword_admin_service" name="search_keyword" value="<?php echo htmlspecialchars($initialSearchQuery); ?>" placeholder="Masukkan kata kunci..."
                                   class="admin-service-filter-input w-full px-3 py-2 text-sm bg-gray-700 border border-gray-600 text-gray-100 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label for="filter_sort_by_admin_service" class="block text-sm font-medium text-gray-300 mb-1">Urutkan</label>
                            <select id="filter_sort_by_admin_service" name="sort_by" class="admin-service-filter-input w-full px-3 py-2 text-sm bg-gray-700 border border-gray-600 text-gray-100 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                                <?php foreach ($sortColumnOptionsServices as $value => $label): ?>
                                    <option value="<?php echo $value; ?>" <?php echo ($value === 's.name') ? 'selected' : ''; ?>><?php echo htmlspecialchars($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label for="filter_sort_type_admin_service" class="block text-sm font-medium text-gray-300 mb-1">Tipe</label>
                            <select id="filter_sort_type_admin_service" name="sort_type" class="admin-service-filter-input w-full px-3 py-2 text-sm bg-gray-700 border border-gray-600 text-gray-100 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                                <?php foreach ($sortTypeOptionsServices as $value => $label): ?>
                                    <option value="<?php echo $value; ?>" <?php echo ($value === 'ASC') ? 'selected' : ''; ?>><?php echo htmlspecialchars($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="flex justify-end items-center pt-4 space-x-3 border-t border-gray-700 mt-5">
                        <button type="button" id="reset-admin-service-filter-button" class="px-4 py-2 text-sm font-medium text-gray-300 bg-gray-600 rounded-lg hover:bg-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-gray-500 transition">Reset</button>
                        <button type="submit" id="apply-admin-service-filter-button" class="px-5 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg shadow hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-blue-500 transition"><i class="fas fa-filter mr-1"></i> Terapkan</button>
                    </div>
                </form>
            </div>
        </div>

        <div id="add-edit-service-modal" class="fixed inset-0 z-50 hidden items-center justify-center bg-black bg-opacity-60 transition-opacity duration-300 ease-in-out p-4" aria-labelledby="add-edit-service-modal-title" role="dialog" aria-modal="true">
            <div class="relative bg-white rounded-xl shadow-xl w-full max-w-2xl transform transition-all duration-300 ease-in-out scale-95 opacity-0 flex flex-col max-h-[90vh]" id="add-edit-service-modal-content">
                <div class="flex items-center justify-between p-4 md:p-5 border-b rounded-t flex-shrink-0">
                    <h3 id="add-edit-service-modal-title" class="text-xl font-semibold text-gray-900 flex items-center">
                        <i class="fas fa-plus-circle mr-3 text-green-500"></i> Tambah Layanan Baru
                    </h3>
                    <button type="button" id="close-add-edit-service-modal" class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center">
                        <i class="fas fa-times text-xl"></i>
                        <span class="sr-only">Tutup modal</span>
                    </button>
                </div>
                <div class="p-4 md:p-5 space-y-4 overflow-y-auto flex-grow">
                    <form id="add-edit-service-form" class="space-y-4">
                        <input type="hidden" id="service_id" name="service_id" value="">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label for="service_category_id" class="block mb-1 text-sm font-medium text-gray-700">Kategori <span class="text-red-500">*</span></label>
                                <select id="service_category_id" name="category_id" required class="input-field w-full px-3 py-2 border border-gray-300 rounded-lg sm:text-sm bg-white focus:ring-blue-500 focus:border-blue-500">
                                    <option value="">-- Pilih Kategori --</option>
                                     <?php foreach ($categoriesForFilter as $category): ?>
                                        <option value="<?php echo $category['id']; ?>"><?php echo htmlspecialchars($category['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <span id="service_category_id-error" class="text-red-500 text-xs mt-1"></span>
                            </div>
                            <div>
                                <label for="service_provider_id" class="block mb-1 text-sm font-medium text-gray-700">Provider <span class="text-red-500">*</span></label>
                                <select id="service_provider_id" name="provider_id" required class="input-field w-full px-3 py-2 border border-gray-300 rounded-lg sm:text-sm bg-white focus:ring-blue-500 focus:border-blue-500">
                                     <option value="">-- Pilih Provider --</option>
                                     <?php foreach ($providersForFilter as $provider): ?>
                                        <option value="<?php echo $provider['id']; ?>"><?php echo htmlspecialchars($provider['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <span id="service_provider_id-error" class="text-red-500 text-xs mt-1"></span>
                            </div>
                        </div>
                         <div>
                            <label for="service_provider_service_id" class="block mb-1 text-sm font-medium text-gray-700">ID Layanan Provider <span class="text-red-500">*</span></label>
                            <input type="text" id="service_provider_service_id" name="provider_service_id" required placeholder="ID unik dari provider" class="input-field w-full px-3 py-2 border border-gray-300 rounded-lg sm:text-sm focus:ring-blue-500 focus:border-blue-500">
                            <span id="service_provider_service_id-error" class="text-red-500 text-xs mt-1"></span>
                        </div>
                        <div>
                            <label for="service_name" class="block mb-1 text-sm font-medium text-gray-700">Nama Layanan <span class="text-red-500">*</span></label>
                            <input type="text" id="service_name" name="name" required class="input-field w-full px-3 py-2 border border-gray-300 rounded-lg sm:text-sm focus:ring-blue-500 focus:border-blue-500">
                            <span id="service_name-error" class="text-red-500 text-xs mt-1"></span>
                        </div>
                         <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label for="service_price_per_1000" class="block mb-1 text-sm font-medium text-gray-700">Harga / 1000 <span class="text-red-500">*</span></label>
                                <input type="number" step="0.01" id="service_price_per_1000" name="price_per_1000" required placeholder="Contoh: 15000.50" class="input-field w-full px-3 py-2 border border-gray-300 rounded-lg sm:text-sm focus:ring-blue-500 focus:border-blue-500">
                                <span id="service_price_per_1000-error" class="text-red-500 text-xs mt-1"></span>
                            </div>
                             <div>
                                <label for="service_min_order" class="block mb-1 text-sm font-medium text-gray-700">Min Pesan <span class="text-red-500">*</span></label>
                                <input type="number" id="service_min_order" name="min_order" required placeholder="Contoh: 100" class="input-field w-full px-3 py-2 border border-gray-300 rounded-lg sm:text-sm focus:ring-blue-500 focus:border-blue-500">
                                <span id="service_min_order-error" class="text-red-500 text-xs mt-1"></span>
                            </div>
                             <div>
                                <label for="service_max_order" class="block mb-1 text-sm font-medium text-gray-700">Maks Pesan <span class="text-red-500">*</span></label>
                                <input type="number" id="service_max_order" name="max_order" required placeholder="Contoh: 10000" class="input-field w-full px-3 py-2 border border-gray-300 rounded-lg sm:text-sm focus:ring-blue-500 focus:border-blue-500">
                                <span id="service_max_order-error" class="text-red-500 text-xs mt-1"></span>
                            </div>
                        </div>
                        <div>
                            <label for="service_note" class="block mb-1 text-sm font-medium text-gray-700">Catatan / Deskripsi</label>
                            <textarea id="service_note" name="note" rows="4" class="input-field w-full px-3 py-2 border border-gray-300 rounded-lg sm:text-sm focus:ring-blue-500 focus:border-blue-500"></textarea>
                            <span id="service_note-error" class="text-red-500 text-xs mt-1"></span>
                        </div>
                        <div>
                            <label for="service_status" class="block mb-1 text-sm font-medium text-gray-700">Status <span class="text-red-500">*</span></label>
                            <select id="service_status" name="status" required class="input-field w-full px-3 py-2 border border-gray-300 rounded-lg sm:text-sm bg-white focus:ring-blue-500 focus:border-blue-500">
                                <option value="active" selected>Aktif</option>
                                <option value="inactive">Nonaktif</option>
                            </select>
                            <span id="service_status-error" class="text-red-500 text-xs mt-1"></span>
                        </div>
                        <div id="add-edit-service-message" class="text-sm"></div>
                    </form>
                </div>
                <div class="flex items-center justify-end p-4 md:p-5 space-x-3 rtl:space-x-reverse border-t border-gray-200 rounded-b flex-shrink-0">
                    <button id="cancel-add-edit-service-button" type="button" class="py-2.5 px-5 text-sm font-medium text-gray-900 focus:outline-none bg-white rounded-lg border border-gray-200 hover:bg-gray-100 hover:text-blue-700 focus:z-10 focus:ring-4 focus:ring-gray-100">Batal</button>
                    <button id="save-add-edit-service-button" type="submit" form="add-edit-service-form" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center">
                        Simpan Layanan
                    </button>
                </div>
            </div>
        </div>

        <div id="delete-service-confirm-modal" class="fixed inset-0 z-50 hidden items-center justify-center bg-black bg-opacity-60 transition-opacity duration-300 ease-in-out" aria-labelledby="delete-service-confirm-modal-title" role="dialog" aria-modal="true">
            <div class="relative bg-white rounded-lg shadow-xl w-full max-w-md mx-4 transform transition-all duration-300 ease-in-out scale-95 opacity-0" id="delete-service-confirm-modal-content">
                 <div class="flex items-center justify-between p-5 border-b rounded-t">
                     <h3 id="delete-service-confirm-modal-title" class="text-xl font-semibold text-gray-900 flex items-center">
                        <i class="fas fa-exclamation-triangle text-red-500 mr-3"></i> Konfirmasi Hapus
                     </h3>
                     <button type="button" class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center close-confirm-delete-service-btn">
                         <i class="fas fa-times text-xl"></i><span class="sr-only">Tutup</span>
                     </button>
                 </div>
                 <div class="p-6 text-center">
                     <i class="fas fa-trash-alt text-4xl text-red-400 mb-4"></i>
                     <p id="delete-service-confirm-modal-message" class="mb-5 text-lg font-normal text-gray-600">Apakah Anda yakin ingin menghapus layanan ini?</p>
                      <p class="text-xs text-red-600 mb-4">(Tindakan ini tidak dapat diurungkan!)</p>
                     <button type="button" class="text-white bg-red-600 hover:bg-red-800 focus:ring-4 focus:outline-none focus:ring-red-300 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2" id="confirm-delete-service-btn">
                         Ya, Hapus
                     </button>
                     <button type="button" class="text-gray-500 bg-white hover:bg-gray-100 focus:ring-4 focus:outline-none focus:ring-gray-200 rounded-lg border border-gray-200 text-sm font-medium px-5 py-2.5 hover:text-gray-900 focus:z-10 close-confirm-delete-service-btn">
                         Batal
                     </button>
                 </div>
            </div>
        </div>

    </main>
    