<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

use App\Core\Controller;
use App\Core\Database;

final class AdminSettingsController extends Controller
{
    public function index(): void
    {
        require_login();
        if (!can_admin()) { http_response_code(403); echo "Forbidden"; return; }
        $db = Database::getInstance();
        $rows = $db->query("SELECT * FROM system_settings ORDER BY id DESC LIMIT 1000")->fetchAll();
        $this->view('admin/settings/index', ['rows'=>$rows, 'err'=>null]);
    }

    public function save(): void
    {
        require_login();
        if (!can_admin()) { http_response_code(403); echo "Forbidden"; return; }
        csrf_check();
        $db = Database::getInstance();

        $key = trim((string)($_POST['setting_key'] ?? ''));
        $val = (string)($_POST['setting_value'] ?? '');
        $act = (int)($_POST['is_active'] ?? 1);

        if ($key==='') { header('Location: '.base_path('admin/settings')); exit; }

        $st = $db->prepare("INSERT INTO system_settings(setting_key,setting_value,is_active)
                            VALUES(:k,:v,:a)
                            ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value), is_active=VALUES(is_active)");
        $st->execute([':k'=>$key, ':v'=>$val, ':a'=>$act?1:0]);

        header('Location: '.base_path('admin/settings')); exit;
    }

    public function delete(): void
    {
        require_login();
        if (!can_admin()) { http_response_code(403); echo "Forbidden"; return; }
        csrf_check();
        $db = Database::getInstance();
        $id = (int)($_POST['id'] ?? 0);
        if ($id>0) $db->prepare("DELETE FROM system_settings WHERE id=:id")->execute([':id'=>$id]);
        header('Location: '.base_path('admin/settings')); exit;
    }
}
