<?php
declare(strict_types=1);

namespace App\Controllers;

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

use App\Core\Controller;
use App\Models\DictionaryModel;

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

        $model = new DictionaryModel();

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

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

        $model = new DictionaryModel();

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

            $data = [
                'lang_code' => trim((string) ($_POST['lang_code'] ?? '')),
                'dict_key' => trim((string) ($_POST['dict_key'] ?? '')),
                'dict_value' => trim((string) ($_POST['dict_value'] ?? '')),
                'group_name' => trim((string) ($_POST['group_name'] ?? '')),
            ];

            if ($data['lang_code'] === '' || $data['dict_key'] === '' || $data['dict_value'] === '') {
                flash('danger', trans('required_fields'));
                redirect('admin/dictionary/create');
            }

            $id = $model->create($data);
            audit_log('create', 'language_dictionary', $id, $data);
            flash('success', trans('dictionary_saved_success'));
            redirect('admin/dictionary');
        }

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

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

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

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

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

            $data = [
                'lang_code' => trim((string) ($_POST['lang_code'] ?? '')),
                'dict_key' => trim((string) ($_POST['dict_key'] ?? '')),
                'dict_value' => trim((string) ($_POST['dict_value'] ?? '')),
                'group_name' => trim((string) ($_POST['group_name'] ?? '')),
            ];

            if ($data['lang_code'] === '' || $data['dict_key'] === '' || $data['dict_value'] === '') {
                flash('danger', trans('required_fields'));
                redirect('admin/dictionary/edit?id=' . $id);
            }

            $model->update($id, $data);
            audit_log('update', 'language_dictionary', $id, $data);
            flash('success', trans('dictionary_saved_success'));
            redirect('admin/dictionary');
        }

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