<?php
declare(strict_types=1);

namespace App\Controllers;

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

use App\Core\Controller;
use App\Models\SettingsModel;

final class SettingsController extends Controller
{
    public function index(): void
    {
        require_permission('settings.view');

        $model = new SettingsModel();

        $this->view('admin/settings/index', [
            'rows' => $model->all(),
        ]);
    }

    public function create(): void
    {
        require_permission('settings.manage');

        $model = new SettingsModel();

        if ($this->isPost()) {
            csrf_check();

            $data = [
                'setting_key' => trim((string) ($_POST['setting_key'] ?? '')),
                'setting_value' => trim((string) ($_POST['setting_value'] ?? '')),
                'setting_group' => trim((string) ($_POST['setting_group'] ?? '')),
                'is_public' => isset($_POST['is_public']) ? 1 : 0,
            ];

            if ($data['setting_key'] === '') {
                flash('danger', trans('required_fields'));
                redirect('admin/settings/create');
            }

            $id = $model->create($data);
            audit_log('create', 'system_settings', $id, $data);
            flash('success', trans('setting_saved_success'));
            redirect('admin/settings');
        }

        $this->view('admin/settings/create');
    }

    public function edit(): void
    {
        require_permission('settings.manage');

        $id = (int) ($_GET['id'] ?? 0);
        $model = new SettingsModel();
        $row = $model->findById($id);

        if (!$row) {
            redirect('admin/settings');
        }

        if ($this->isPost()) {
            csrf_check();

            $data = [
                'setting_key' => trim((string) ($_POST['setting_key'] ?? '')),
                'setting_value' => trim((string) ($_POST['setting_value'] ?? '')),
                'setting_group' => trim((string) ($_POST['setting_group'] ?? '')),
                'is_public' => isset($_POST['is_public']) ? 1 : 0,
            ];

            if ($data['setting_key'] === '') {
                flash('danger', trans('required_fields'));
                redirect('admin/settings/edit?id=' . $id);
            }

            $model->update($id, $data);
            audit_log('update', 'system_settings', $id, $data);
            flash('success', trans('setting_saved_success'));
            redirect('admin/settings');
        }

        $this->view('admin/settings/edit', [
            'row' => $row,
        ]);
    }
}
