<?php
namespace App\Controllers\Admin;

use App\Models\Page;

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

    /** 编辑：按页面 mode 渲染对应编辑器（固定版面 / 可视化编辑） */
    public function edit($id)
    {
        $p = (new Page())->find($id);
        if (!$p) { $this->redirect('admin/pages'); }
        $mode = empty($p['mode']) ? 'fixed' : $p['mode'];
        if ($mode === 'builder') {
            $layout = [];
            if (!empty($p['layout'])) {
                $dec = json_decode($p['layout'], true);
                if (is_array($dec)) $layout = $dec;
            }
            return $this->view('admin/page_builder', ['p' => $p, 'layout' => $layout, 'mode' => $mode]);
        }
        return $this->view('admin/page_form', ['p' => $p, 'mode' => $mode]);
    }

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

    /** 保存：兼容两种编辑器，按实际提交的字段写入（content / layout / mode） */
    public function update($id)
    {
        if (!csrf_check()) { $this->redirect('admin/pages'); }
        $data = [
            'title'      => $this->post('title'),
            'updated_at' => date('Y-m-d'),
        ];
        if ($this->post('content') !== null) {
            $data['content'] = $this->post('content');
        }
        if ($this->post('layout') !== null) {
            $layout = $this->post('layout', '');
            if ($layout !== '' && !is_array(json_decode($layout, true))) {
                $layout = '';
            }
            $data['layout'] = $layout;
        }
        $mode = $this->post('mode');
        if ($mode === 'builder' || $mode === 'fixed') {
            $data['mode'] = $mode;
        }
        (new Page())->update($id, $data);
        $this->redirect('admin/pages');
    }
}
