<?php
namespace App\Controllers\PSI;

use Core\Controller;
use App\Models\Setting;

/**
 * PSI 通知设置（仅 PSI 管理员可访问）
 *  - 总开关 + 邮件（SMTP）/ 企业微信（群机器人 webhook）配置
 *  - 负责人邮箱、被@手机号
 *  - 低库存预警开关与阈值
 * 通过 PSI 仪表盘统一分发：PSI/notifications[/save]
 */
class NotificationsController extends Controller
{
    private const KEYS = [
        'notify_enabled', 'notify_email_enabled', 'notify_email_smtp_host', 'notify_email_smtp_port',
        'notify_email_smtp_user', 'notify_email_smtp_pass', 'notify_email_from', 'notify_email_to',
        'notify_wechat_enabled', 'notify_wechat_webhook', 'notify_wechat_mention',
        'notify_lowstock_enabled', 'notify_lowstock_threshold',
    ];

    /** 统一入口 */
    public function handle(array $args = []): void
    {
        if (!subsys_admin('psi')) { http_response_code(403); echo '无权限：仅 PSI 管理员可配置通知'; return; }
        $action = $args[0] ?? 'index';
        if ($action === 'save') {
            $this->save();
            return;
        }
        $this->index();
    }

    public function index(): void
    {
        $s = new Setting();
        $v = [];
        foreach (self::KEYS as $k) {
            $v[$k] = $s->get($k, '');
        }
        // 布尔项默认值
        if ($v['notify_lowstock_enabled'] === '') $v['notify_lowstock_enabled'] = 1;
        if ($v['notify_lowstock_threshold'] === '') $v['notify_lowstock_threshold'] = 20;

        $this->renderSubsys('psi', 'psi/notifications', ['v' => $v], \psi_nav(), 'notifications');
    }

    public function save(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !csrf_check()) {
            $this->redirect('PSI/notifications');
        }
        $s = new Setting();
        $post = $_POST;
        $s->set('notify_enabled', isset($post['notify_enabled']) ? 1 : 0);
        $s->set('notify_email_enabled', isset($post['notify_email_enabled']) ? 1 : 0);
        $s->set('notify_email_smtp_host', trim((string) ($post['notify_email_smtp_host'] ?? '')));
        $s->set('notify_email_smtp_port', (int) ($post['notify_email_smtp_port'] ?? 465));
        $s->set('notify_email_smtp_user', trim((string) ($post['notify_email_smtp_user'] ?? '')));
        $s->set('notify_email_smtp_pass', trim((string) ($post['notify_email_smtp_pass'] ?? '')));
        $s->set('notify_email_from', trim((string) ($post['notify_email_from'] ?? '')));
        $s->set('notify_email_to', trim((string) ($post['notify_email_to'] ?? '')));
        $s->set('notify_wechat_enabled', isset($post['notify_wechat_enabled']) ? 1 : 0);
        $s->set('notify_wechat_webhook', trim((string) ($post['notify_wechat_webhook'] ?? '')));
        $s->set('notify_wechat_mention', trim((string) ($post['notify_wechat_mention'] ?? '')));
        $s->set('notify_lowstock_enabled', isset($post['notify_lowstock_enabled']) ? 1 : 0);
        $s->set('notify_lowstock_threshold', max(0, (float) ($post['notify_lowstock_threshold'] ?? 20)));

        $this->flash('通知设置已保存', 'ok');
        $this->redirect('PSI/notifications');
    }
}
