<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/layout.php';
require_once __DIR__ . '/../includes/service_management.php';

require_permission($conn, 'services');

$editId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$filterCategoryId = filter_input(INPUT_GET, 'category_id', FILTER_VALIDATE_INT);
$showFormFlag = filter_input(INPUT_GET, 'show_form', FILTER_VALIDATE_INT);
$searchKeyword = trim((string) ($_GET['q'] ?? ''));
$editing = $editId ? service_catalog_row($conn, $editId) : null;
$oldInput = pull_old_input();

$categories = service_categories($conn);
$serviceGroups = service_group_options($conn);
$subServiceOptions = service_catalog_rows($conn, array('service_type' => 'sub_service'));

$selectedFilterCategoryId = 0;
$selectedFilterCategoryName = '';
foreach ($categories as $category) {
    if ((int) ($category['category_id'] ?? 0) === (int) $filterCategoryId) {
        $selectedFilterCategoryId = (int) $filterCategoryId;
        $selectedFilterCategoryName = (string) ($category['category_name'] ?? '');
        break;
    }
}

$defaultCategoryId = 0;
if ($editing) {
    $defaultCategoryId = (int) ($editing['category_id'] ?? 0);
} elseif ($selectedFilterCategoryId > 0) {
    $defaultCategoryId = $selectedFilterCategoryId;
} elseif (isset($categories[0])) {
    $defaultCategoryId = (int) ($categories[0]['category_id'] ?? 0);
}

$mainServices = service_main_service_options($conn);
$defaultMainServiceId = 0;
foreach ($mainServices as $mainService) {
    if ((int) ($mainService['category_id'] ?? 0) === $defaultCategoryId) {
        $defaultMainServiceId = (int) ($mainService['service_id'] ?? 0);
        break;
    }
}
if ($defaultMainServiceId === 0 && isset($mainServices[0])) {
    $defaultMainServiceId = (int) ($mainServices[0]['service_id'] ?? 0);
}

$serviceName = old_value($oldInput, 'service_name', (string) ($editing['service_name'] ?? ''));
$serviceType = old_value($oldInput, 'service_type', (string) ($editing['service_type'] ?? 'main_service'));
$categoryIdValue = (int) old_value($oldInput, 'category_id', (string) ($editing['category_id'] ?? $defaultCategoryId));
$mainServiceIdValue = (int) old_value($oldInput, 'main_service_id', (string) ($editing['main_service_id'] ?? '0'));
$groupIdValue = (int) old_value($oldInput, 'group_id', (string) ($editing['group_id'] ?? '0'));
$price = old_value($oldInput, 'price', (string) ($editing['price'] ?? '0'));
$description = old_value($oldInput, 'description', (string) ($editing['description'] ?? ''));
$isActive = old_value($oldInput, 'is_active', (string) ($editing['is_active'] ?? '1')) !== '0';
$packageVehicleScope = normalize_package_vehicle_scope(old_value($oldInput, 'package_vehicle_scope', (string) ($editing['package_vehicle_scope'] ?? 'member')));
$isQuickService = old_value($oldInput, 'is_quick_service', (string) ($editing['is_quick_service'] ?? '0')) === '1';

$packageServiceCounts = array();
$packageCountInput = old_array($oldInput, 'package_service_counts');
if (!empty($packageCountInput)) {
    foreach ($packageCountInput as $subServiceId => $count) {
        $packageServiceCounts[(int) $subServiceId] = (int) $count;
    }
} elseif ($editing && (string) ($editing['service_type'] ?? '') === 'package') {
    foreach (service_package_item_rows($conn, (int) $editing['service_id']) as $packageItem) {
        $packageServiceCounts[(int) $packageItem['sub_service_id']] = (int) $packageItem['included_uses'];
    }
}

$serviceOptions = array();
if ($selectedFilterCategoryId > 0) {
    $serviceOptions['category_id'] = $selectedFilterCategoryId;
}
$serviceOptions['search'] = $searchKeyword;
$services = service_catalog_rows($conn, $serviceOptions);

$showServiceForm = $editing !== null || !empty($oldInput) || (int) ($showFormFlag ?? 0) === 1;

$formReturnParams = array();
if ($selectedFilterCategoryId > 0) {
    $formReturnParams['category_id'] = $selectedFilterCategoryId;
}
if ($searchKeyword !== '') {
    $formReturnParams['q'] = $searchKeyword;
}
if ($editing) {
    $formReturnParams['id'] = (int) $editing['service_id'];
} elseif ($showServiceForm) {
    $formReturnParams['show_form'] = 1;
}

$formReturnTo = service_management_page_url('services.php', $formReturnParams);
$createServiceParams = array('show_form' => 1);
if ($selectedFilterCategoryId > 0) {
    $createServiceParams['category_id'] = $selectedFilterCategoryId;
}
$createServiceParams['q'] = $searchKeyword;
$createServiceUrl = service_management_page_url('services.php', $createServiceParams);
$listOnlyParams = array();
if ($selectedFilterCategoryId > 0) {
    $listOnlyParams['category_id'] = $selectedFilterCategoryId;
}
if ($searchKeyword !== '') {
    $listOnlyParams['q'] = $searchKeyword;
}
$listOnlyUrl = service_management_page_url('services.php', $listOnlyParams);

$pageTitle = ui_text('รายการบริการ', 'Service Items');
$pageDescription = ui_text(
    'ตรวจสอบรายการบริการทั้งหมด กรองตามหมวดหมู่ และจัดการบริการหลัก บริการย่อย หรือแพ็กเกจได้จากหน้าเดียว',
    'Review all service items, filter them by category and manage each main service, sub service or package from one page.'
);
$manageSystemLabel = ui_text('จัดการระบบ', 'Manage System');
$createBookingLabel = ui_text('เปิดบิล', 'Create booking');
$addServiceItemLabel = ui_text('เพิ่มรายการบริการ', 'Add service item');
$editServiceItemLabel = ui_text('แก้ไขรายการบริการ', 'Edit service item');
$hideFormLabel = ui_text('ซ่อนฟอร์ม', 'Hide form');
$serviceFormTitle = $editing ? $editServiceItemLabel : $addServiceItemLabel;
$serviceFormHelperLabel = ui_text(
    'ใช้ "บริการหลัก" สำหรับขั้นตอนแรกที่ลูกค้าเลือก "บริการย่อย" สำหรับตัวเลือกละเอียด และ "แพ็กเกจ" สำหรับสิทธิ์การใช้งานแบบเหมาจ่าย',
    'Use `Main Service` for the parent step customers choose first, `Sub Service` for detailed options, and `Package` for bundled usage rights.'
);
$serviceNameLabel = ui_text('ชื่อบริการ', 'Service name');
$itemTypeLabel = ui_text('ประเภทรายการ', 'Item type');
$categoryLabel = ui_text('หมวดหมู่', 'Category');
$selectCategoryLabel = ui_text('เลือกหมวดหมู่', 'Select category');
$parentMainServiceLabel = ui_text('บริการหลักแม่', 'Parent main service');
$noMainServiceLabel = ui_text('ไม่มีบริการหลัก', 'No main service');
$serviceGroupLabel = ui_text('กลุ่มบริการ', 'Service group');
$noGroupLabel = ui_text('ไม่มีกลุ่ม', 'No group');
$priceLabel = ui_text('ราคา', 'Price');
$descriptionLabel = ui_text('รายละเอียด', 'Description');
$packageContentsLabel = ui_text('รายการในแพ็กเกจ', 'Package contents');
$packageContentsHelperLabel = ui_text(
    'กำหนดจำนวนครั้งที่แต่ละบริการย่อยสามารถใช้งานได้จากแพ็กเกจนี้',
    'Set how many times each sub service can be used from this package.'
);
$packageVehicleAccessLabel = ui_text('สิทธิ์การใช้แพ็กเกจกับรถ', 'Package vehicle access');
$packageVehicleAccessHelperLabel = ui_text(
    'เลือกว่าจะให้แพ็กเกจใช้ได้กับรถทุกคันในบัญชีสมาชิก หรือเฉพาะรถที่ซื้อแพ็กเกจนี้',
    'Choose whether the package can be used by all vehicles in the member account or only the vehicle that purchased it.'
);
$createSubServicesFirstLabel = ui_text('กรุณาสร้างบริการย่อยก่อนจึงจะประกอบแพ็กเกจได้', 'Create sub services before building package contents.');
$activeForBookingLabel = ui_text('เปิดใช้งานสำหรับการจอง', 'Active for booking');
$activeForBookingHelperLabel = ui_text(
    'ปิดตัวเลือกนี้เพื่อเก็บประวัติเดิมไว้ แต่ซ่อนรายการนี้จากการเปิดบิลใหม่',
    'Turn this off to preserve history while hiding the item from new bookings.'
);
$availableInQuickServiceLabel = ui_text('เปิดใช้ในควิกเซอร์วิส', 'Available in Quick Service');
$availableInQuickServiceHelperLabel = ui_text(
    'ใช้รายการนี้ในบิลควิกเซอร์วิสของสาขา ซึ่งรับชำระทันทีและไม่เข้าคิวงานปกติ',
    'Use this item in branch quick bills that are paid immediately and do not enter the running queue.'
);
$saveChangesLabel = ui_text('บันทึกการเปลี่ยนแปลง', 'Save changes');
$serviceFiltersLabel = ui_text('ตัวกรองรายการบริการ', 'Service filters');
$serviceFiltersHelperLabel = ui_text(
    'แสดงเฉพาะรายการของหมวดหมู่ที่เลือก หรือรีเซ็ตเพื่อดูแคตตาล็อกทั้งหมด',
    'Show only the items from a selected category, or reset to view the full catalog.'
);
$searchLabel = ui_text('ค้นหา', 'Search');
$searchPlaceholderLabel = ui_text('ค้นหาชื่อบริการ หมวดหมู่ บริการหลัก หรือกลุ่มบริการ', 'Search service name, category, main service or group');
$filterLabel = ui_text('กรอง', 'Filter');
$resetLabel = ui_text('รีเซ็ต', 'Reset');
$serviceListLabel = ui_text('รายการบริการ', 'Service list');
$itemRecordsLabel = ui_text('รายการ', 'item(s)');
$matchingLabel = ui_text('ตรงกับคำค้น', 'matching');
$noServiceItemsFoundLabel = ui_text('ไม่พบรายการบริการ', 'No service items found.');
$itemLabel = ui_text('รายการ', 'Item');
$typeLabel = ui_text('ประเภท', 'Type');
$mainServiceLabel = ui_text('บริการหลัก', 'Main service');
$groupLabel = ui_text('กลุ่ม', 'Group');
$quickServiceLabel = ui_text('ควิกเซอร์วิส', 'Quick Service');
$statusLabel = ui_text('สถานะ', 'Status');
$usedLabel = ui_text('การใช้งาน', 'Used');
$actionLabel = ui_text('การทำรายการ', 'Action');
$accessLabel = ui_text('สิทธิ์ใช้แพ็กเกจ', 'Access');
$linkedGroupsLabel = ui_text('กลุ่มที่เชื่อมโยง', 'linked group(s)');
$linkedSubServicesLabel = ui_text('บริการย่อยที่เชื่อมโยง', 'linked sub service(s)');
$enabledLabel = ui_text('เปิดใช้งาน', 'Enabled');
$offLabel = ui_text('ปิด', 'Off');
$activeLabel = ui_text('ใช้งาน', 'Active');
$inactiveLabel = ui_text('ปิดใช้งาน', 'Inactive');
$keepForHistoryLabel = ui_text('เก็บไว้เพื่อประวัติ', 'Keep for history');
$editLabel = ui_text('แก้ไข', 'Edit');
$deleteLabel = ui_text('ลบ', 'Delete');
$deleteServiceConfirmLabel = ui_text('ลบรายการบริการนี้ใช่หรือไม่', 'Delete this service item?');
$linkedItemsLabel = ui_text('มีรายการที่เชื่อมโยง', 'Linked items');
$usedInHistoryLabel = ui_text('ถูกใช้ในประวัติแล้ว', 'Used in history');

render_page_start($pageTitle, 'services', array('translation_buffer' => false));
?>

<style>
.services-explicit-layout .summary-panel form > .service-management-filter-actions:not(.explicit-actions),
.services-explicit-layout .summary-panel .card > .service-management-filter-actions:not(.explicit-actions) {
    display: none;
}
</style>

<div class="services-explicit-layout">

<?php if (false): ?>
<section class="page-hero">
    <div>
        <h1>รายการ service</h1>
        <p>Review all service items, filter them by category and manage each main service, sub service or package from one page.</p>
    </div>
    <div class="hero-actions">
        <a class="button button-secondary" href="manage_system.php">Manage System</a>
        <a class="button button-secondary" href="booking.php">Create booking</a>
    </div>
</section>
<?php endif; ?>

<section class="page-hero">
    <div>
        <h1><?= e($pageTitle) ?></h1>
        <p><?= e($pageDescription) ?></p>
    </div>
    <div class="hero-actions">
        <a class="button button-secondary" href="manage_system.php"><?= e($manageSystemLabel) ?></a>
        <a class="button button-secondary" href="booking.php"><?= e($createBookingLabel) ?></a>
    </div>
</section>

<?= render_service_management_tabs('services') ?>

<div class="content-grid service-content-grid<?= $showServiceForm ? '' : ' is-form-hidden' ?>">
    <section class="form-card" id="service-item-form"<?= $showServiceForm ? '' : ' hidden' ?>>
        <div class="section-head">
            <div>
                <h2 class="section-title"><?= e($serviceFormTitle) ?></h2>
                <p class="helper"><?= e($serviceFormHelperLabel) ?></p>
            </div>
            <?php if ($editing): ?>
                <a class="button button-ghost" href="<?= e($createServiceUrl) ?>"><?= e($addServiceItemLabel) ?></a>
            <?php elseif ($showServiceForm): ?>
                <a class="button button-ghost" href="<?= e($listOnlyUrl) ?>"><?= e($hideFormLabel) ?></a>
            <?php endif; ?>
        </div>

        <form method="POST" action="../process/save_service.php" data-service-structure-form>
            <input type="hidden" name="return_to" value="<?= e($formReturnTo) ?>">
            <?php if ($editing): ?>
                <input type="hidden" name="service_id" value="<?= (int) $editing['service_id'] ?>">
            <?php endif; ?>

            <div class="form-grid">
                <div class="field">
                    <label for="service_name"><?= e($serviceNameLabel) ?></label>
                    <input id="service_name" name="service_name" type="text" value="<?= e($serviceName) ?>" required>
                </div>

                <div class="field">
                    <label for="service_type"><?= e($itemTypeLabel) ?></label>
                    <select id="service_type" name="service_type" data-service-type-select required>
                        <?php foreach (service_type_options() as $value => $label): ?>
                            <option value="<?= e($value) ?>" <?= $serviceType === $value ? 'selected' : '' ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="field">
                    <label for="category_id"><?= e($categoryLabel) ?></label>
                    <select id="category_id" name="category_id" data-service-category-select required>
                        <option value=""><?= e($selectCategoryLabel) ?></option>
                        <?php foreach ($categories as $category): ?>
                            <option value="<?= (int) $category['category_id'] ?>" <?= $categoryIdValue === (int) $category['category_id'] ? 'selected' : '' ?>>
                                <?= e((string) $category['category_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="field" data-main-service-field>
                    <label for="main_service_id"><?= e($parentMainServiceLabel) ?></label>
                    <select id="main_service_id" name="main_service_id" data-service-main-select>
                        <option value=""><?= e($noMainServiceLabel) ?></option>
                        <?php foreach ($mainServices as $mainService): ?>
                            <option
                                value="<?= (int) $mainService['service_id'] ?>"
                                data-category-id="<?= (int) $mainService['category_id'] ?>"
                                <?= $mainServiceIdValue === (int) $mainService['service_id'] ? 'selected' : '' ?>
                            >
                                <?= e((string) $mainService['category_name']) ?> / <?= e((string) $mainService['service_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="field" data-group-field>
                    <label for="group_id"><?= e($serviceGroupLabel) ?></label>
                    <select id="group_id" name="group_id" data-service-group-select>
                        <option value=""><?= e($noGroupLabel) ?></option>
                        <?php foreach ($serviceGroups as $serviceGroup): ?>
                            <option
                                value="<?= (int) $serviceGroup['group_id'] ?>"
                                data-category-id="<?= (int) $serviceGroup['category_id'] ?>"
                                data-main-service-id="<?= (int) $serviceGroup['main_service_id'] ?>"
                                <?= $groupIdValue === (int) $serviceGroup['group_id'] ? 'selected' : '' ?>
                            >
                                <?= e((string) $serviceGroup['category_name']) ?> / <?= e((string) $serviceGroup['main_service_name']) ?> / <?= e((string) $serviceGroup['group_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="field">
                    <label for="price"><?= e($priceLabel) ?></label>
                    <input id="price" name="price" type="number" step="0.01" min="0" value="<?= e($price) ?>" required>
                </div>
            </div>

            <div class="field">
                <label for="description"><?= e($descriptionLabel) ?></label>
                <textarea id="description" name="description"><?= e($description) ?></textarea>
            </div>

            <div class="card" data-package-builder <?= $serviceType === 'package' ? '' : 'hidden' ?>>
                <div class="section-head">
                    <div>
                        <h3 class="section-title"><?= e($packageContentsLabel) ?></h3>
                        <p class="helper"><?= e($packageContentsHelperLabel) ?></p>
                    </div>
                </div>

                <div class="field">
                    <label for="package_vehicle_scope"><?= e($packageVehicleAccessLabel) ?></label>
                    <select id="package_vehicle_scope" name="package_vehicle_scope">
                        <?php foreach (package_vehicle_scope_options() as $scopeValue => $scopeLabel): ?>
                            <option value="<?= e($scopeValue) ?>" <?= $packageVehicleScope === $scopeValue ? 'selected' : '' ?>><?= e($scopeLabel) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="helper"><?= e($packageVehicleAccessHelperLabel) ?></p>
                </div>

                <?php if (empty($subServiceOptions)): ?>
                    <div class="empty-state"><?= e($createSubServicesFirstLabel) ?></div>
                <?php else: ?>
                    <div class="grid">
                        <?php foreach ($subServiceOptions as $subService): ?>
                            <?php
                            $subServiceId = (int) $subService['service_id'];
                            $subServiceCount = (int) ($packageServiceCounts[$subServiceId] ?? 0);
                            $subServiceMeta = array_filter(array(
                                (string) ($subService['category_name'] ?? ''),
                                (string) ($subService['main_service_name'] ?? ''),
                                (string) ($subService['group_name'] ?? ''),
                            ));
                            ?>
                            <div class="service-option compact-option package-item-option">
                                <span>
                                    <strong><?= e((string) $subService['service_name']) ?></strong>
                                    <span class="muted"><?= e(implode(' / ', $subServiceMeta)) ?></span>
                                </span>
                                <input
                                    id="package_service_count_<?= $subServiceId ?>"
                                    name="package_service_counts[<?= $subServiceId ?>]"
                                    type="number"
                                    min="0"
                                    value="<?= $subServiceCount ?>"
                                >
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <label class="service-option compact-option">
                <input type="checkbox" name="is_active" value="1" <?= $isActive ? 'checked' : '' ?>>
                <span>
                    <strong><?= e($activeForBookingLabel) ?></strong>
                    <span class="muted"><?= e($activeForBookingHelperLabel) ?></span>
                </span>
            </label>

            <label class="service-option compact-option" data-quick-service-field <?= $serviceType === 'package' ? 'hidden' : '' ?>>
                <input type="checkbox" name="is_quick_service" value="1" <?= $isQuickService ? 'checked' : '' ?>>
                <span>
                    <strong><?= e($availableInQuickServiceLabel) ?></strong>
                    <span class="muted"><?= e($availableInQuickServiceHelperLabel) ?></span>
                </span>
            </label>

            <button class="button button-accent" type="submit"><?= e($editing ? $saveChangesLabel : $addServiceItemLabel) ?></button>
        </form>
    </section>

    <aside class="grid summary-panel">
        <section class="card">
            <div class="section-head">
                <div>
                    <h2 class="section-title"><?= e($serviceFiltersLabel) ?></h2>
                    <p class="helper"><?= e($serviceFiltersHelperLabel) ?></p>
                </div>
            </div>

            <form method="GET">
                <?php if ($editing): ?>
                    <input type="hidden" name="id" value="<?= (int) $editing['service_id'] ?>">
                <?php endif; ?>
                <div class="field">
                    <label for="service_search_keyword"><?= e($searchLabel) ?></label>
                    <input id="service_search_keyword" name="q" type="text" value="<?= e($searchKeyword) ?>" placeholder="<?= e($searchPlaceholderLabel) ?>">
                </div>
                <div class="field">
                    <label for="filter_category_id"><?= e($categoryLabel) ?></label>
                    <select id="filter_category_id" name="category_id">
                        <option value=""><?= e(ui_text('ทุกหมวดหมู่', 'All categories')) ?></option>
                        <?php foreach ($categories as $category): ?>
                            <option value="<?= (int) $category['category_id'] ?>" <?= $selectedFilterCategoryId === (int) $category['category_id'] ? 'selected' : '' ?>>
                                <?= e((string) $category['category_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="actions service-management-filter-actions">
                    <button class="button button-secondary app-action-button" type="submit"><?= app_button_content('sliders', ui_text('กรอง', 'Filter')) ?></button>
                    <a class="button button-ghost app-action-button" href="<?= e($editing ? service_management_page_url('services.php', array('id' => (int) $editing['service_id'])) : 'services.php') ?>"><?= app_button_content('rotate-ccw', ui_text('รีเซ็ต', 'Reset')) ?></a>
                </div>
            </form>

            <div class="actions service-management-filter-actions" style="margin-top: 18px;">
                <a class="button button-accent app-action-button" href="<?= e($createServiceUrl) ?>#service-item-form"><?= app_button_content('plus-square', ui_text('เพิ่ม service item', 'Add service item')) ?></a>
            </div>
            <div class="actions service-management-filter-actions explicit-actions">
                <button class="button button-secondary app-action-button" type="button" onclick="this.closest('.card').querySelector('form').requestSubmit()"><?= app_button_content('sliders', $filterLabel) ?></button>
                <a class="button button-ghost app-action-button" href="<?= e($editing ? service_management_page_url('services.php', array('id' => (int) $editing['service_id'])) : 'services.php') ?>"><?= app_button_content('rotate-ccw', $resetLabel) ?></a>
            </div>

            <div class="actions service-management-filter-actions explicit-actions" style="margin-top: 18px;">
                <a class="button button-accent app-action-button" href="<?= e($createServiceUrl) ?>#service-item-form"><?= app_button_content('plus-square', $addServiceItemLabel) ?></a>
            </div>
        </section>
    </aside>
</div>

<section class="table-card" style="margin-top: 18px;">
    <div class="section-head" style="padding: 18px 18px 0;">
        <div>
            <h2 class="section-title"><?= e($serviceListLabel) ?></h2>
            <p class="helper">
                <?= count($services) ?> <?= e($itemRecordsLabel) ?>
                <?php if ($selectedFilterCategoryId > 0): ?>
                    <?= e(ui_text('ใน', 'in')) ?> <?= e($selectedFilterCategoryName) ?>
                <?php endif; ?>
                <?php if ($searchKeyword !== ''): ?>
                    <?= e($matchingLabel) ?> "<?= e($searchKeyword) ?>"
                <?php endif; ?>
            </p>
        </div>
    </div>

    <?php if (empty($services)): ?>
        <div class="empty-state" style="margin: 18px;"><?= e($noServiceItemsFoundLabel) ?></div>
    <?php else: ?>
        <table>
            <thead>
            <tr>
                <th><?= e($itemLabel) ?></th>
                <th><?= e($typeLabel) ?></th>
                <th><?= e($categoryLabel) ?></th>
                <th><?= e($mainServiceLabel) ?></th>
                <th><?= e($groupLabel) ?></th>
                <th><?= e($priceLabel) ?></th>
                <th><?= e($quickServiceLabel) ?></th>
                <th><?= e($statusLabel) ?></th>
                <th><?= e($usedLabel) ?></th>
                <th><?= e($actionLabel) ?></th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($services as $service): ?>
                <?php
                $serviceTypeRow = (string) ($service['service_type'] ?? 'sub_service');
                $serviceTypeLabel = service_type_options()[$serviceTypeRow] ?? $serviceTypeRow;
                $serviceCategoryName = trim((string) ($service['category_name'] ?? $service['category'] ?? ''));
                $serviceMainServiceName = $serviceTypeRow === 'main_service'
                    ? '-'
                    : trim((string) ($service['main_service_name'] ?? ''));
                $serviceGroupName = trim((string) ($service['group_name'] ?? ''));
                $hasLinkedChildren = (int) ($service['linked_sub_service_count'] ?? 0) > 0 || (int) ($service['linked_group_count'] ?? 0) > 0;
                $packageItemLines = array();
                if ($serviceTypeRow === 'package') {
                    $packageItemLines[] = $accessLabel . ': ' . package_vehicle_scope_label((string) ($service['package_vehicle_scope'] ?? 'member'));
                    foreach (service_package_item_rows($conn, (int) $service['service_id']) as $packageItem) {
                        $packageItemLines[] = (string) $packageItem['service_name'] . ' x' . (int) $packageItem['included_uses'];
                    }
                }
                $editParams = array('id' => (int) $service['service_id']);
                if ($selectedFilterCategoryId > 0) {
                    $editParams['category_id'] = $selectedFilterCategoryId;
                }
                if ($searchKeyword !== '') {
                    $editParams['q'] = $searchKeyword;
                }
                ?>
                <tr>
                    <td>
                        <div class="stack">
                            <strong><?= e((string) $service['service_name']) ?></strong>
                            <?php if ($descriptionLine = trim((string) ($service['description'] ?? ''))): ?>
                                <span class="muted"><?= e($descriptionLine) ?></span>
                            <?php endif; ?>
                            <?php if ($serviceTypeRow === 'main_service' && (int) ($service['linked_group_count'] ?? 0) > 0): ?>
                                <span class="muted"><?= (int) $service['linked_group_count'] ?> <?= e($linkedGroupsLabel) ?></span>
                            <?php endif; ?>
                            <?php if ($serviceTypeRow === 'main_service' && (int) ($service['linked_sub_service_count'] ?? 0) > 0): ?>
                                <span class="muted"><?= (int) $service['linked_sub_service_count'] ?> <?= e($linkedSubServicesLabel) ?></span>
                            <?php endif; ?>
                            <?php foreach ($packageItemLines as $packageItemLine): ?>
                                <span class="muted"><?= e($packageItemLine) ?></span>
                            <?php endforeach; ?>
                        </div>
                    </td>
                    <td><?= e($serviceTypeLabel) ?></td>
                    <td><?= e($serviceCategoryName !== '' ? $serviceCategoryName : '-') ?></td>
                    <td><?= e($serviceMainServiceName !== '' ? $serviceMainServiceName : '-') ?></td>
                    <td><?= e($serviceGroupName !== '' ? $serviceGroupName : '-') ?></td>
                    <td><?= format_money($service['price']) ?></td>
                    <td><?= (int) ($service['is_quick_service'] ?? 0) === 1 ? e($enabledLabel) : e($offLabel) ?></td>
                    <td>
                        <div class="stack">
                            <span class="<?= (int) $service['is_active'] === 1 ? 'badge badge-paid' : 'badge badge-unpaid' ?>">
                                <?= (int) $service['is_active'] === 1 ? e($activeLabel) : e($inactiveLabel) ?>
                            </span>
                            <?php if ((int) $service['usage_count'] > 0): ?>
                                <span class="muted"><?= e($keepForHistoryLabel) ?></span>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td><?= (int) $service['usage_count'] ?></td>
                    <td>
                        <div class="inline-actions">
                            <a class="button button-secondary" href="<?= e(service_management_page_url('services.php', $editParams)) ?>"><?= e($editLabel) ?></a>
                            <?php if ((int) $service['usage_count'] === 0 && !$hasLinkedChildren): ?>
                                <form class="inline-form" method="POST" action="../process/delete_service.php" onsubmit="return confirm('<?= e($deleteServiceConfirmLabel) ?>');">
                                    <input type="hidden" name="service_id" value="<?= (int) $service['service_id'] ?>">
                                    <input type="hidden" name="return_to" value="<?= e($listOnlyUrl) ?>">
                                    <button class="button button-danger" type="submit"><?= e($deleteLabel) ?></button>
                                </form>
                            <?php elseif ($hasLinkedChildren): ?>
                                <span class="muted"><?= e($linkedItemsLabel) ?></span>
                            <?php else: ?>
                                <span class="muted"><?= e($usedInHistoryLabel) ?></span>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</section>

</div>

<?php render_page_end(); ?>
