<?php
namespace App\Controllers\Admin;

use App\Models\News;

class NewsController extends AdminController
{
    public function index()
    {
        return $this->view('admin/news', [
            'news' => (new News())->all(),
            'seg'  => $this->seg(),
        ]);
    }

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

    public function store()
    {
        if (!csrf_check()) { $this->redirect('admin/news'); }
        $news = new News();
        $mode = $this->post('mode') === 'builder' ? 'builder' : 'fixed';
        $cover = $this->uploadFile('cover') ?? $this->post('cover_url', '');
        $content = ($mode === 'fixed') ? $this->post('content', '') : '';
        $id = $news->insert([
            'title'        => $this->post('title'),
            'slug'         => '',
            'cover'        => $cover,
            'summary'      => $this->post('summary'),
            'content'      => $content,
            'author'       => $this->post('author', '酷冰甲'),
            'published_at' => $this->post('published_at', date('Y-m-d')),
            '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;
        $news->update($id, ['slug' => $slug]);
        // 新建时若选择「可视化编辑」，保存后直接进入可视化编辑器排版
        if ($mode === 'builder') {
            $this->redirect('admin/news/edit/' . $id);
        }
        $this->redirect('admin/news');
    }

    public function edit($id)
    {
        $news = new News();
        $n = $news->find($id);
        if (!$n) { $this->redirect('admin/news'); }
        $mode = empty($n['mode']) ? 'fixed' : $n['mode'];
        if ($mode === 'builder') {
            $layout = [];
            if (!empty($n['layout'])) {
                $dec = json_decode($n['layout'], true);
                if (is_array($dec)) $layout = $dec;
            }
            return $this->view('admin/news_builder', ['n' => $n, 'layout' => $layout, 'mode' => $mode]);
        }
        return $this->view('admin/news_form', ['n' => $n, 'mode' => $mode]);
    }

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

    public function update($id)
    {
        if (!csrf_check()) { $this->redirect('admin/news'); }
        $news = new News();
        $n = $news->find($id);
        if (!$n) { $this->redirect('admin/news'); }
        $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 = $n['cover'] ?? '';

        $data = [
            'title'        => $this->post('title'),
            'slug'         => $this->post('slug') ? slugify($this->post('slug')) : (string)$id,
            'cover'        => $cover,
            'summary'      => $this->post('summary'),
            'author'       => $this->post('author', '酷冰甲'),
            'published_at' => $this->post('published_at', date('Y-m-d')),
            '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;
        }

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

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