<?php
namespace App\Controllers\PSI;

use Core\Controller;
use Core\Notify;
use App\Models\PSI\Event;

/**
 * PSI 紧急事件 / 提醒中心
 *  - 列出所有“紧急事件”（站内提醒，所有 PSI 人员可见）
 *  - 支持单条标记已读 / 全部已读
 *  - 支持手动发起一条紧急提醒（通知负责人）
 * 通过 PSI 仪表盘统一分发：PSI/reminders[/动作[/id]]
 */
class RemindersController extends Controller
{
    /** 统一入口，由 DashboardController 分发 */
    public function handle(array $args = []): void
    {
        $action = $args[0] ?? 'index';
        $id = (int) ($args[1] ?? 0);

        if ($action === 'create') {
            $this->create();
            return;
        }
        if ($action === 'mark' && $id > 0) {
            $this->markRead($id);
            return;
        }
        if ($action === 'markAll') {
            $this->markAll();
            return;
        }
        $this->index();
    }

    public function index(): void
    {
        if (!subsys_user('psi')) { http_response_code(403); echo '无权限'; return; }

        $events = (new Event())->all();
        $events = array_reverse($events); // 最新在前
        $uid = (int) ($_SESSION['admin_uid'] ?? 0);
        $unread = 0;
        foreach ($events as &$ev) {
            $read = json_decode($ev['read_by'] ?? '[]', true) ?: [];
            $ev['_read'] = in_array($uid, $read, true);
            if (!$ev['_read']) $unread++;
        }

        $this->renderSubsys('psi', 'psi/reminders', [
            'events' => $events,
            'unread' => $unread,
        ], \psi_nav(), 'reminders');
    }

    public function markRead(int $id): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { $this->redirect('PSI/reminders'); }
        if (!subsys_user('psi')) { http_response_code(403); return; }
        $uid = (int) ($_SESSION['admin_uid'] ?? 0);
        $ev = (new Event())->find($id);
        if ($ev) {
            $read = json_decode($ev['read_by'] ?? '[]', true) ?: [];
            if (!in_array($uid, $read, true)) {
                $read[] = $uid;
                (new Event())->update($id, ['read_by' => json_encode($read, JSON_UNESCAPED_UNICODE)]);
            }
        }
        $this->redirect('PSI/reminders');
    }

    public function markAll(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { $this->redirect('PSI/reminders'); }
        if (!subsys_user('psi')) { http_response_code(403); return; }
        $uid = (int) ($_SESSION['admin_uid'] ?? 0);
        $events = (new Event())->all();
        foreach ($events as $ev) {
            $read = json_decode($ev['read_by'] ?? '[]', true) ?: [];
            if (!in_array($uid, $read, true)) {
                $read[] = $uid;
                (new Event())->update($ev['id'], ['read_by' => json_encode($read, JSON_UNESCAPED_UNICODE)]);
            }
        }
        $this->redirect('PSI/reminders');
    }

    /** 手动发起一条紧急提醒（通知负责人） */
    public function create(): void
    {
        if (!subsys_user('psi')) { http_response_code(403); echo '无权限'; return; }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!csrf_check()) { $this->flash('表单已过期，请重试', 'err'); $this->redirect('PSI/reminders'); }
            $title = trim($this->post('title', ''));
            $body  = trim($this->post('body', ''));
            if ($title === '') { $this->flash('请填写提醒标题', 'err'); $this->redirect('PSI/reminders'); }
            Notify::fire('manual', $title, $body ?: $title, [
                'level' => 'urgent', 'url' => 'PSI/reminders',
            ]);
            $this->flash('已发起紧急提醒，并已通知相关负责人', 'ok');
            $this->redirect('PSI/reminders');
        }

        $this->renderSubsys('psi', 'psi/reminder_form', [
            'title' => '', 'body' => '',
        ], \psi_nav(), 'reminders');
    }
}
