<?php

require_once BASE_PATH
    . '/app/controllers/owner/OwnerBaseController.php';

require_once BASE_PATH
    . '/app/models/ProductCategory.php';


class OwnerCategoryController
    extends OwnerBaseController
{
    private ProductCategory $categoryModel;


    public function __construct()
    {
        $this->requireOwner();

        $this->categoryModel =
            new ProductCategory();
    }


    public function index(): void
    {
        $categories =
            $this->categoryModel
                ->getAllForOwner();


        require BASE_PATH
            . '/app/views/owner/categories/product-categories.php';
    }


    public function store(): void
    {
        $this->requirePost();

        $this->validateCsrf();


        $name =
            trim(
                $_POST['name']
                ?? ''
            );


        if ($name === '') {

            $this->flashError(
                'Tên danh mục không được để trống.'
            );

            $this->redirect(
                'owner/product-categories'
            );
        }


        $slug =
            $this->makeUniqueSlug(
                $name
            );


        $this->categoryModel
            ->create([
                'parent_id' =>
                    (int)
                    ($_POST['parent_id']
                        ?? 0),

                'name' =>
                    $name,

                'slug' =>
                    $slug,

                'description' =>
                    trim(
                        $_POST['description']
                        ?? ''
                    ),

                'image' =>
                    null,

                'sort_order' =>
                    (int)
                    ($_POST['sort_order']
                        ?? 0),

                'is_active' =>
                    isset(
                        $_POST['is_active']
                    )
                        ? 1
                        : 0
            ]);


        $this->flashSuccess(
            'Đã thêm danh mục.'
        );


        $this->redirect(
            'owner/product-categories'
        );
    }


    public function update(): void
    {
        $this->requirePost();

        $this->validateCsrf();


        $id =
            (int)
            ($_POST['category_id']
                ?? 0);


        $category =
            $this->categoryModel
                ->findAnyById($id);


        if (!$category) {

            $this->flashError(
                'Danh mục không tồn tại.'
            );

            $this->redirect(
                'owner/product-categories'
            );
        }


        $name =
            trim(
                $_POST['name']
                ?? ''
            );


        if ($name === '') {

            $this->flashError(
                'Tên danh mục không được để trống.'
            );

            $this->redirect(
                'owner/product-categories'
            );
        }


        $slug =
            $this->makeUniqueSlug(
                $name,
                $id
            );


        $parentId =
            (int)
            ($_POST['parent_id']
                ?? 0);


        if ($parentId === $id) {
            $parentId = 0;
        }


        $this->categoryModel
            ->update(
                $id,
                [
                    'parent_id' =>
                        $parentId,

                    'name' =>
                        $name,

                    'slug' =>
                        $slug,

                    'description' =>
                        trim(
                            $_POST['description']
                            ?? ''
                        ),

                    'sort_order' =>
                        (int)
                        ($_POST['sort_order']
                            ?? 0),

                    'is_active' =>
                        isset(
                            $_POST['is_active']
                        )
                            ? 1
                            : 0
                ]
            );


        $this->flashSuccess(
            'Đã cập nhật danh mục.'
        );


        $this->redirect(
            'owner/product-categories'
        );
    }


    public function toggle(): void
    {
        $this->requirePost();

        $this->validateCsrf();


        $id =
            (int)
            ($_POST['category_id']
                ?? 0);


        $this->categoryModel
            ->toggleActive($id);


        $this->flashSuccess(
            'Đã cập nhật trạng thái danh mục.'
        );


        $this->redirect(
            'owner/product-categories'
        );
    }


    private function makeUniqueSlug(
        string $name,
        ?int $excludeId = null
    ): string {

        $slug =
            $this->slugify($name);


        if ($slug === '') {

            $slug =
                'category';
        }


        $baseSlug =
            $slug;


        $counter = 2;


        while (
            $this->categoryModel
                ->slugExists(
                    $slug,
                    $excludeId
                )
        ) {

            $slug =
                $baseSlug
                . '-'
                . $counter;

            $counter++;
        }


        return $slug;
    }


    private function slugify(
        string $text
    ): string {

        $text =
            str_replace(
                ['Đ', 'đ'],
                ['D', 'd'],
                $text
            );


        $converted =
            iconv(
                'UTF-8',
                'ASCII//TRANSLIT//IGNORE',
                $text
            );


        if ($converted !== false) {
            $text = $converted;
        }


        $text =
            strtolower($text);


        $text =
            preg_replace(
                '/[^a-z0-9]+/',
                '-',
                $text
            );


        return trim(
            $text,
            '-'
        );
    }
}