<?php
namespace App\Controllers\Admin;

use App\Models\Category;

class CategoryController extends AdminController
{
    public function index()
    {
        return $this->view('admin/categories', [
            'cats' => (new Category())->all(),
            'seg'  => $this->seg(),
        ]);
    }

    public function create()
    {
        return $this->view('admin/category_form', [
            'c'    => null,
            'mode' => 'fixed',
        ]);
    }

    public function store()
    {
        if (!csrf_check()) { $this->redirect('admin/categories'); }
        $cat = new Category();
        $mode = $this->post('mode') === 'builder' ? 'builder' : 'fixed';
        $description = ($mode === 'fixed') ? $this->post('description', '') : '';
        $id = $cat->insert([
            'name'        => $this->post('name'),
            'slug'        => '',
            'icon'        => $this->post('icon', '❄'),
            'description' => $description,
            'sort_order'  => (int)$this->post('sort_order', 0),
            'status'      => $this->post('status', 1) ? 1 : 0,
            'layout'      => $this->post('layout', ''),
            'mode'        => $mode,
        ]);
        // URL 标识留空时按记录序号顺序生成（短、稳定）
        $slug = $this->post('slug') ? slugify($this->post('slug')) : (string)$id;
        $cat->update($id, ['slug' => $slug]);
        // 新建时若选择「可视化编辑」，保存后直接进入可视化编辑器排版
        if ($mode === 'builder') {
            $this->redirect('admin/categories/edit/' . $id);
        }
        $this->redirect('admin/categories');
    }

    public function edit($id)
    {
        $cat = new Category();
        $c = $cat->find($id);
        if (!$c) { $this->redirect('admin/categories'); }
        $mode = empty($c['mode']) ? 'fixed' : $c['mode'];
        if ($mode === 'builder') {
            $layout = [];
            if (!empty($c['layout'])) {
                $dec = json_decode($c['layout'], true);
                if (is_array($dec)) $layout = $dec;
            }
            return $this->view('admin/category_builder', ['c' => $c, 'layout' => $layout, 'mode' => $mode]);
        }
        return $this->view('admin/category_form', ['c' => $c, 'mode' => $mode]);
    }

    /** 切换编辑模式（固定版面 <-> 可视化编辑），仅更新 mode 字段 */
    public function switchMode($id)
    {
        $c = (new Category())->find($id);
        if (!$c) { $this->redirect('admin/categories'); }
        $target = ($this->get('mode') === 'builder') ? 'builder' : 'fixed';
        (new Category())->update($id, ['mode' => $target]);
        $this->redirect('admin/categories/edit/' . $id);
    }

    public function update($id)
    {
        if (!csrf_check()) { $this->redirect('admin/categories'); }
        $cat = new Category();
        $c = $cat->find($id);
        if (!$c) { $this->redirect('admin/categories'); }
        $mode = $this->post('mode') === 'builder' ? 'builder' : 'fixed';

        $data = [
            'name'        => $this->post('name'),
            'slug'        => $this->post('slug') ? slugify($this->post('slug')) : (string)$id,
            'icon'        => $this->post('icon', '❄'),
            'sort_order'  => (int)$this->post('sort_order', 0),
            'status'      => $this->post('status', 1) ? 1 : 0,
            'mode'        => $mode,
        ];

        if ($mode === 'fixed') {
            $data['description'] = $this->post('description', '');
        } else {
            $layout = $this->post('layout', '');
            if ($layout !== '' && !is_array(json_decode($layout, true))) { $layout = ''; }
            $data['layout'] = $layout;
        }

        $cat->update($id, $data);
        $this->redirect('admin/categories');
    }

    public function delete($id)
    {
        if (csrf_check()) { (new Category())->delete($id); }
        $this->redirect('admin/categories');
    }
}
