<?php

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

class OwnerServiceController extends OwnerBaseController
{
    private Service $services; private ServiceCategory $categories; private SpaActivityLog $activityLog;
    public function __construct() { $this->requireOwner(); $this->services = new Service(); $this->categories = new ServiceCategory(); $this->activityLog = new SpaActivityLog(); }
    public function index(): void { $services = $this->services->getForOwner(trim((string) ($_GET['search'] ?? ''))); require BASE_PATH . '/app/views/owner/services/index.php'; }
    public function create(): void { $service = null; $categories = $this->categories->getActive(); require BASE_PATH . '/app/views/owner/services/form.php'; }
    public function edit(): void { $service = $this->services->findForOwner((int) ($_GET['id'] ?? 0)); if (!$service) { $this->notFound(); return; } $categories = $this->categories->getActive(); require BASE_PATH . '/app/views/owner/services/form.php'; }
    public function store(): void { $this->save(); }
    public function update(): void { $this->save((int) ($_POST['service_id'] ?? 0)); }
    public function toggle(): void { $this->requirePost(); $this->validateCsrf(); $id = (int) ($_POST['service_id'] ?? 0); $this->services->toggle($id); $this->activityLog->record((int) $_SESSION['user']['id'], 'owner.service.toggle', 'service', $id); $this->flashSuccess('Đã cập nhật trạng thái dịch vụ.'); $this->redirect('owner/services'); }
    private function save(int $id = 0): void
{
    $this->requirePost();
    $this->validateCsrf();


    /*
    |--------------------------------------------------------------------------
    | Phân biệt Thêm mới / Cập nhật
    |--------------------------------------------------------------------------
    */

    $isUpdate = $id > 0;


    $current =
        $isUpdate
            ? $this->services->findForOwner($id)
            : null;


    if ($isUpdate && !$current) {

        $this->notFound();

        return;
    }


    try {

        /*
        |--------------------------------------------------------------------------
        | Validate dữ liệu
        |--------------------------------------------------------------------------
        */

        $data =
            $this->validated(
                $current
            );


        /*
        |--------------------------------------------------------------------------
        | Tạo slug
        |--------------------------------------------------------------------------
        */

        $data['slug'] =
            $this->uniqueSlug(
                $data['name'],
                $isUpdate
                    ? $id
                    : null
            );


        /*
        |--------------------------------------------------------------------------
        | LƯU DỊCH VỤ
        |--------------------------------------------------------------------------
        */

        if ($isUpdate) {

            $this->services
                ->update(
                    $id,
                    $data
                );

        } else {

            $id =
                $this->services
                    ->create(
                        $data
                    );

        }


        /*
        |--------------------------------------------------------------------------
        | Nếu đổi ảnh thì xóa ảnh cũ
        |--------------------------------------------------------------------------
        */

        if (
            $current
            &&
            $data['featured_image']
                !== $current['featured_image']
        ) {

            $this->deleteManagedImage(
                (string) $current[
                    'featured_image'
                ]
            );

        }


        /*
        |--------------------------------------------------------------------------
        | Activity Log
        |--------------------------------------------------------------------------
        */

        $this->activityLog->record(

            (int) $_SESSION['user']['id'],

            $isUpdate
                ? 'owner.service.update'
                : 'owner.service.create',

            'service',

            $id,

            [
                'category_id' =>
                    $data['category_id'],

                'is_active' =>
                    (int) $data['is_active']
            ]

        );


        /*
        |--------------------------------------------------------------------------
        | THÔNG BÁO THÀNH CÔNG
        |--------------------------------------------------------------------------
        */

        if ($isUpdate) {

            $this->flashSuccess(
                'Cập nhật dịch vụ thành công!'
            );

        } else {

            $this->flashSuccess(
                'Thêm dịch vụ thành công!'
            );

        }


        /*
        |--------------------------------------------------------------------------
        | QUAY VỀ DANH SÁCH
        |--------------------------------------------------------------------------
        */

        $this->redirect(
            'owner/services'
        );


    } catch (Throwable $e) {


        $this->flashError(
            $e->getMessage()
        );


        /*
         * Nếu đang sửa → quay lại trang sửa
         */
        if ($isUpdate) {

            $this->editRedirect(
                $id
            );

        }


        /*
         * Nếu đang thêm → quay lại trang thêm
         */

        $this->redirect(
            'owner/service/create'
        );

    }
}    private function validated(?array $current): array
    {
        $name = trim((string) ($_POST['name'] ?? '')); $price = (string) ($_POST['price'] ?? ''); $duration = (int) ($_POST['duration_minutes'] ?? 0); $category = (int) ($_POST['category_id'] ?? 0);
        if ($name === '' || (function_exists('mb_strlen') ? mb_strlen($name) : strlen($name)) > 200 || !is_numeric($price) || (float) $price < 0 || $duration < 5 || $duration > 1440) { throw new InvalidArgumentException('Thông tin dịch vụ không hợp lệ.'); }
        if ($category && !$this->categories->findById($category)) { throw new InvalidArgumentException('Danh mục không hợp lệ.'); }
        return ['category_id' => $category ?: null, 'name' => $name, 'short_description' => trim((string) ($_POST['short_description'] ?? '')) ?: null, 'description' => trim((string) ($_POST['description'] ?? '')) ?: null, 'price' => number_format((float) $price, 2, '.', ''), 'duration_minutes' => $duration, 'featured_image' => $this->uploadImage($current['featured_image'] ?? null), 'is_active' => isset($_POST['is_active']) ? 1 : 0, 'sort_order' => (int) ($_POST['sort_order'] ?? 0)];
    }
    private function uploadImage(?string $existing): ?string
    {
        if (empty($_FILES['featured_image']['tmp_name']) || (int) $_FILES['featured_image']['error'] === UPLOAD_ERR_NO_FILE) return $existing;
        if ((int) $_FILES['featured_image']['error'] !== UPLOAD_ERR_OK || (int) $_FILES['featured_image']['size'] > 5 * 1024 * 1024) throw new RuntimeException('Ảnh dịch vụ không hợp lệ hoặc vượt quá 5MB.');
        $mime = (new finfo(FILEINFO_MIME_TYPE))->file($_FILES['featured_image']['tmp_name']); $ext = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'][$mime] ?? null; if (!$ext) throw new RuntimeException('Chỉ chấp nhận ảnh JPG, PNG hoặc WEBP.');
        $dir = BASE_PATH . '/public/uploads/services'; if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) throw new RuntimeException('Không thể tạo thư mục ảnh.');
        $file = 'service_' . bin2hex(random_bytes(12)) . '.' . $ext; if (!move_uploaded_file($_FILES['featured_image']['tmp_name'], $dir . '/' . $file)) throw new RuntimeException('Không thể tải ảnh lên.'); return 'uploads/services/' . $file;
    }
    private function deleteManagedImage(string $path): void
    {
        if (!str_starts_with($path, 'uploads/services/')) return;
        $file = BASE_PATH . '/public/' . $path;
        if (is_file($file)) @unlink($file);
    }
    private function uniqueSlug(string $name, ?int $id): string { $ascii = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', str_replace(['Đ', 'đ'], ['D', 'd'], $name)); $base = trim((string) preg_replace('/[^a-z0-9]+/', '-', strtolower($ascii !== false ? $ascii : $name)), '-') ?: 'dich-vu'; $slug = $base; $i = 2; while ($this->services->slugExists($slug, $id)) $slug = $base . '-' . $i++; return $slug; }
    private function editRedirect(int $id): never { header('Location: ' . BASE_URL . '/?url=owner/service/edit&id=' . $id); exit; }
    private function notFound(): void { http_response_code(404); require BASE_PATH . '/app/views/errors/404.php'; }
}
