<?php

require_once BASE_PATH . '/app/controllers/owner/OwnerBaseController.php';
require_once BASE_PATH . '/app/models/ServiceCategory.php';
require_once BASE_PATH . '/app/models/SpaActivityLog.php';

class OwnerServiceCategoryController extends OwnerBaseController
{
    private ServiceCategory $categories; private SpaActivityLog $activityLog;
    public function __construct() { $this->requireOwner(); $this->categories = new ServiceCategory(); $this->activityLog = new SpaActivityLog(); }
    public function index(): void { $categories = $this->categories->getForOwner(); require BASE_PATH . '/app/views/owner/service-categories/index.php'; }
    public function store(): void { $this->save(); }
    public function update(): void { $this->save((int) ($_POST['category_id'] ?? 0)); }
    public function toggle(): void { $this->requirePost(); $this->validateCsrf(); $id = (int) ($_POST['category_id'] ?? 0); $this->categories->toggle($id); $this->activityLog->record((int) $_SESSION['user']['id'], 'owner.service_category.toggle', 'service_category', $id); $this->flashSuccess('Đã cập nhật trạng thái danh mục.'); $this->redirect('owner/service-categories'); }
    private function save(int $id = 0): void
    {
        $this->requirePost(); $this->validateCsrf();
        $name = trim((string) ($_POST['name'] ?? ''));
        if ($name === '' || (function_exists('mb_strlen') ? mb_strlen($name) : strlen($name)) > 120) { $this->flashError('Tên danh mục không hợp lệ.'); $this->redirect('owner/service-categories'); }
        if ($id && !$this->categories->findById($id)) { $this->flashError('Danh mục không tồn tại.'); $this->redirect('owner/service-categories'); }
        $slug = $this->uniqueSlug($name, $id ?: null);
        $data = ['name' => $name, 'slug' => $slug, 'description' => trim((string) ($_POST['description'] ?? '')) ?: null, 'sort_order' => (int) ($_POST['sort_order'] ?? 0), 'is_active' => isset($_POST['is_active']) ? 1 : 0];
        $isUpdate = $id > 0;
        if ($isUpdate) {
            $this->categories->update($id, $data);
        } else {
            $id = $this->categories->create($data);
        }
        $this->activityLog->record((int) $_SESSION['user']['id'], $isUpdate ? 'owner.service_category.update' : 'owner.service_category.create', 'service_category', $id, ['is_active' => (int) $data['is_active']]);
        $this->flashSuccess($id ? 'Đã cập nhật danh mục.' : 'Đã thêm danh mục.'); $this->redirect('owner/service-categories');
    }
    private function uniqueSlug(string $name, ?int $id): string
    {
        $text = str_replace(['Đ', 'đ'], ['D', 'd'], $name); $ascii = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $text); $base = trim((string) preg_replace('/[^a-z0-9]+/', '-', strtolower($ascii !== false ? $ascii : $text)), '-') ?: 'dich-vu'; $slug = $base; $i = 2;
        while ($this->categories->slugExists($slug, $id)) { $slug = $base . '-' . $i++; } return $slug;
    }
}
