<?php
namespace App\Controllers;

use Core\View;

class Controller
{
    protected $layout = 'layouts/site';

    protected function view(string $view, array $data = []): string
    {
        return View::make($view, $data, $this->layout);
    }

    protected function redirect(string $url)
    {
        header('Location: ' . site_url($url));
        exit;
    }

    protected function back()
    {
        $this->redirect($_SERVER['HTTP_REFERER'] ?? '');
    }

    protected function json($data, int $code = 200)
    {
        http_response_code($code);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    /** 一次性会话消息（成功 ok / 错误 err），布局模板自动渲染 */
    protected function flash(string $msg, string $type = 'err'): void
    {
        $_SESSION['flash'] = ['msg' => $msg, 'type' => $type];
    }

    protected function get(string $key, $default = '')
    {
        return $_GET[$key] ?? $default;
    }

    protected function post(string $key, $default = '')
    {
        return $_POST[$key] ?? $default;
    }

    /**
     * 分系统（CRM / PSI）统一后台渲染：左侧导航 + 顶栏 + 内容区。
     * 与 layouts/admin.php 同源规范，保证团队多系统体验一致、可维护。
     * @param string $sys   crm | psi
     * @param string $view  视图名（如 crm/dashboard）
     * @param array  $nav   子系统导航项 [['k'=>, 'label'=>, 'icon'=>, 'url'=>]]
     * @param string $seg   当前激活导航 key
     */
    protected function renderSubsys(string $sys, string $view, array $data, array $nav, string $seg): string
    {
        $data['_sys']  = $sys;
        $data['_nav']  = $nav;
        $data['_seg']  = $seg;
        $data['_home'] = $sys; // 子系统首页路由段
        return View::make($view, $data, 'layouts/subsys');
    }
}
