<?php
namespace App\Controllers\Admin;

use App\Models\CustomerCase;

/**
 * 后台「客户案例」管理：增删改查，与新闻管理同构。
 * 权限能力键：cases（在 Helper::admin_role_map 中分配）。
 */
class CaseController extends AdminController
{
    public function index()
    {
        return $this->view('admin/cases', [
            'cases' => (new CustomerCase())->all(),
            'seg'   => $this->seg(),
        ]);
    }

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

    public function store()
    {
        if (!csrf_check()) { $this->redirect('admin/cases'); }
        $mode = $this->post('mode') === 'builder' ? 'builder' : 'fixed';
        $cover = $this->uploadFile('cover') ?? $this->post('cover_url', '');
        $content = ($mode === 'fixed') ? $this->post('content', '') : '';
        $model = new CustomerCase();
        $id = $model->insert([
            'title'        => $this->post('title'),
            'slug'         => '',
            'customer'     => $this->post('customer', ''),
            'industry'     => $this->post('industry', ''),
            'cover'        => $cover,
            'summary'      => $this->post('summary'),
            'content'      => $content,
            'published_at' => $this->post('published_at', date('Y-m-d')),
            'sort_order'   => (int) $this->post('sort_order', 0),
            'status'       => $this->post('status', 1) ? 1 : 0,
            'views'        => 0,
            'layout'       => $this->post('layout', ''),
            'mode'         => $mode,
        ]);
        // URL 标识留空时按记录序号顺序生成（短、稳定），避免中文标题导致过长
        $slug = $this->post('slug') ? slugify($this->post('slug')) : (string)$id;
        $model->update($id, ['slug' => $slug]);
        // 新建时若选择「可视化编辑」，保存后直接进入可视化编辑器排版
        if ($mode === 'builder') {
            $this->redirect('admin/cases/edit/' . $id);
        }
        $this->redirect('admin/cases');
    }

    public function edit($id)
    {
        $model = new CustomerCase();
        $c = $model->find($id);
        if (!$c) { $this->redirect('admin/cases'); }
        $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/cases_builder', ['c' => $c, 'layout' => $layout, 'mode' => $mode]);
        }
        return $this->view('admin/cases_form', ['c' => $c, 'mode' => $mode]);
    }

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

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

        $cover = $this->uploadFile('cover');
        if (!$cover && $this->post('cover_url')) $cover = $this->post('cover_url');
        if (!$cover) $cover = $c['cover'] ?? '';

        $data = [
            'title'        => $this->post('title'),
            'slug'         => $this->post('slug') ? slugify($this->post('slug')) : (string)$id,
            'customer'     => $this->post('customer', ''),
            'industry'     => $this->post('industry', ''),
            'cover'        => $cover,
            'summary'      => $this->post('summary'),
            'published_at' => $this->post('published_at', date('Y-m-d')),
            'sort_order'   => (int) $this->post('sort_order', 0),
            'status'       => $this->post('status', 1) ? 1 : 0,
            'mode'         => $mode,
        ];

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

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

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