<?php
declare(strict_types=1);

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

require_permission($conn, 'services');

$categoryEditId = filter_input(INPUT_GET, 'category_id', FILTER_VALIDATE_INT);
$editingCategory = null;

if ($categoryEditId) {
    $categoryEditStmt = db_prepare($conn, "
        SELECT category_id, category_name
        FROM service_categories
        WHERE category_id = ?
        LIMIT 1
    ");
    $categoryEditStmt->bind_param('i', $categoryEditId);
    $categoryEditStmt->execute();
    $editingCategory = $categoryEditStmt->get_result()->fetch_assoc();
    $categoryEditStmt->close();
}

$oldInput = pull_old_input();
$categoryName = old_value($oldInput, 'category_name', (string) ($editingCategory['category_name'] ?? ''));

$categoryStats = array();
$categoryStatResult = $conn->query("
    SELECT
        sc.category_id,
        sc.category_name,
        COUNT(DISTINCT CASE WHEN s.service_type = 'main_service' THEN s.service_id END) AS main_service_count,
        COUNT(DISTINCT CASE WHEN s.service_type = 'sub_service' THEN s.service_id END) AS sub_service_count,
        COUNT(DISTINCT CASE WHEN s.service_type = 'package' THEN s.service_id END) AS package_count,
        COUNT(DISTINCT sg.group_id) AS group_count
    FROM service_categories sc
    LEFT JOIN services s ON s.category_id = sc.category_id
    LEFT JOIN service_groups sg ON sg.category_id = sc.category_id
    GROUP BY sc.category_id, sc.category_name
    ORDER BY sc.category_name ASC
");

if ($categoryStatResult instanceof mysqli_result) {
    while ($row = $categoryStatResult->fetch_assoc()) {
        $categoryStats[] = $row;
    }
}

$formReturnTo = service_management_page_url('service_categories.php', $editingCategory ? array('category_id' => (int) $editingCategory['category_id']) : array());

$pageTitle = ui_text('หมวดหมู่บริการ', 'Service Categories');
$pageHeading = ui_text('รายการหมวดหมู่', 'Category list');
$pageDescription = ui_text(
    'จัดการหมวดหมู่ระดับบนสุดที่ใช้กับรายการบริการ บริการหลัก แพ็กเกจ และกลุ่มบริการ',
    'Manage the top-level categories used across service items, main services, packages and service groups.'
);
$manageSystemLabel = ui_text('จัดการระบบ', 'Manage System');
$createBookingLabel = ui_text('เปิดบิล', 'Create booking');
$formTitle = $editingCategory
    ? ui_text('แก้ไขหมวดหมู่', 'Edit category')
    : ui_text('เพิ่มหมวดหมู่', 'Add category');
$formHelperLabel = ui_text(
    'หมวดหมู่คือส่วนบนสุด เช่น ฟิล์ม ล้างรถ ภายในรถ หรือเคลือบปกป้อง',
    'Category is the top section such as Film, Wash, Interior or Protection.'
);
$resetFormLabel = ui_text('เพิ่มหมวดหมู่', 'Add category');
$categoryNameLabel = ui_text('ชื่อหมวดหมู่', 'Category name');
$saveCategoryLabel = $editingCategory
    ? ui_text('บันทึกหมวดหมู่', 'Save category')
    : ui_text('เพิ่มหมวดหมู่', 'Add category');
$recordsLabel = ui_text('รายการ', 'record(s)');
$emptyStateLabel = ui_text('ยังไม่พบหมวดหมู่บริการ', 'No categories found.');
$categoryLabel = ui_text('หมวดหมู่', 'Category');
$mainServicesLabel = ui_text('บริการหลัก', 'Main services');
$groupsLabel = ui_text('กลุ่มบริการ', 'Groups');
$itemsLabel = ui_text('รายการย่อย', 'Items');
$actionLabel = ui_text('การทำรายการ', 'Action');
$editLabel = ui_text('แก้ไข', 'Edit');
$deleteLabel = ui_text('ลบ', 'Delete');
$deleteCategoryConfirmLabel = ui_text('ลบหมวดหมู่นี้ใช่หรือไม่', 'Delete this category?');
$inUseLabel = ui_text('กำลังถูกใช้งาน', 'In use');

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

<section class="page-hero">
    <div>
        <h1><?= e($pageHeading) ?></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('service_categories') ?>

<div class="grid">
    <section class="form-card" id="service-category-form">
        <div class="section-head">
            <div>
                <h2 class="section-title"><?= e($formTitle) ?></h2>
                <p class="helper"><?= e($formHelperLabel) ?></p>
            </div>
            <?php if ($editingCategory): ?>
                <a class="button button-ghost" href="service_categories.php"><?= e($resetFormLabel) ?></a>
            <?php endif; ?>
        </div>

        <form method="POST" action="../process/save_service_category.php">
            <input type="hidden" name="return_to" value="<?= e($formReturnTo) ?>">
            <?php if ($editingCategory): ?>
                <input type="hidden" name="category_id" value="<?= (int) $editingCategory['category_id'] ?>">
            <?php endif; ?>

            <div class="field">
                <label for="category_name"><?= e($categoryNameLabel) ?></label>
                <input id="category_name" name="category_name" type="text" value="<?= e($categoryName) ?>" required>
            </div>

            <button class="button button-accent" type="submit"><?= e($saveCategoryLabel) ?></button>
        </form>
    </section>
</div>

<section class="table-card" style="margin-top: 18px;">
    <div class="section-head" style="padding: 18px 18px 0;">
        <div>
            <h2 class="section-title"><?= e($pageHeading) ?></h2>
            <p class="helper"><?= count($categoryStats) ?> <?= e($recordsLabel) ?></p>
        </div>
    </div>

    <?php if (empty($categoryStats)): ?>
        <div class="empty-state" style="margin: 18px;"><?= e($emptyStateLabel) ?></div>
    <?php else: ?>
        <table style="min-width: 520px;">
            <thead>
            <tr>
                <th><?= e($categoryLabel) ?></th>
                <th><?= e($mainServicesLabel) ?></th>
                <th><?= e($groupsLabel) ?></th>
                <th><?= e($itemsLabel) ?></th>
                <th><?= e($actionLabel) ?></th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($categoryStats as $category): ?>
                <?php
                $categoryItemCount = (int) ($category['main_service_count'] ?? 0)
                    + (int) ($category['sub_service_count'] ?? 0)
                    + (int) ($category['package_count'] ?? 0);
                ?>
                <tr>
                    <td><strong><?= e((string) $category['category_name']) ?></strong></td>
                    <td><?= (int) ($category['main_service_count'] ?? 0) ?></td>
                    <td><?= (int) ($category['group_count'] ?? 0) ?></td>
                    <td><?= $categoryItemCount ?></td>
                    <td>
                        <div class="inline-actions">
                            <a class="button button-secondary" href="<?= e(service_management_page_url('service_categories.php', array('category_id' => (int) $category['category_id']))) ?>"><?= e($editLabel) ?></a>
                            <?php if ($categoryItemCount === 0 && (int) ($category['group_count'] ?? 0) === 0): ?>
                                <form class="inline-form" method="POST" action="../process/delete_service_category.php" onsubmit="return confirm('<?= e($deleteCategoryConfirmLabel) ?>');">
                                    <input type="hidden" name="category_id" value="<?= (int) $category['category_id'] ?>">
                                    <input type="hidden" name="return_to" value="service_categories.php">
                                    <button class="button button-danger" type="submit"><?= e($deleteLabel) ?></button>
                                </form>
                            <?php else: ?>
                                <span class="muted"><?= e($inUseLabel) ?></span>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</section>

<?php render_page_end(); ?>
