<?php
declare(strict_types=1);

namespace Celena\Plugin\Shop\Admin;

use Celena\Core\Database\Connection;
use Celena\Core\Http\Request;
use Celena\Core\Http\Response;
use Celena\Core\Security\Auth;
use Celena\Core\Security\Csrf;
use Celena\Core\Security\Filter;
use Celena\Core\Template\Engine;
use Celena\Module\AdminBase\AdminController;
use Celena\Module\Settings\Options;

/**
 * Способы оплаты. Здесь — лишь регистрация: название и режим. Логика
 * платёжных шлюзов (Kaspi, Stripe, ЮKassa…) живёт в отдельных
 * под-плагинах, которые добавляют свои варианты через хук shop.payments
 * и читают config из колонки `config` (JSON).
 */
final class PaymentsAdminController extends AdminController
{
    private function tr(): \Celena\Core\I18n\Translator
    {
        return \Celena\Core\Kernel::container()->make(\Celena\Core\I18n\Translator::class);
    }

    public function __construct(
        Engine $engine,
        Auth $auth,
        Options $options,
        private readonly Connection $conn,
    ) {
        parent::__construct($engine, $auth, $options);
    }

    public function index(Request $request): Response
    {
        if (!$this->auth->check()) return Response::redirect('/admin/login');
        $rows = $this->conn->builder('shop_payment_methods')
            ->orderBy('sort_order', 'asc')->orderBy('id', 'asc')->get();
        return $this->view('plugins/shop/admin/payments_index', [
            'methods' => $rows,
            'total' => count($rows),
        ], 'shop-payments', $this->tr()->translate('shop.payments_list.title'));
    }

    public function create(Request $request): Response
    {
        if (!$this->auth->check()) return Response::redirect('/admin/login');
        return $this->view('plugins/shop/admin/payments_form', [
            'row' => $this->emptyRow(),
            'form_action' => '/admin/shop/payments/create',
        ], 'shop-payments', $this->tr()->translate('shop.payments_list.new'));
    }

    public function store(Request $request): Response
    {
        if (!$this->auth->check()) return Response::redirect('/admin/login');
        if (!Csrf::validate((string) $request->input('_csrf'))) {
            return $this->redirect('/admin/shop/payments/create', $this->tr()->translate('shop.flash.csrf'), 'error');
        }
        $data = $this->extract($request);
        if ($data['title'] === '') {
            return $this->redirect('/admin/shop/payments/create', $this->tr()->translate('shop.flash.title_required'), 'error');
        }
        if ($data['slug'] === '') $data['slug'] = Filter::slug($data['title']);
        if ($this->slugExists($data['slug'])) {
            return $this->redirect('/admin/shop/payments/create', $this->tr()->translate('shop.flash.slug_taken'), 'error');
        }
        $now = date('Y-m-d H:i:s');
        $data['created_at'] = $now;
        $data['updated_at'] = $now;
        $this->conn->builder('shop_payment_methods')->insert($data);
        return $this->redirect('/admin/shop/payments', $this->tr()->translate('shop.flash.method_added'));
    }

    public function edit(Request $request, array $params): Response
    {
        if (!$this->auth->check()) return Response::redirect('/admin/login');
        $id = Filter::int($params['id'] ?? 0);
        $row = $this->conn->builder('shop_payment_methods')->where('id', '=', $id)->first();
        if ($row === null) return $this->redirect('/admin/shop/payments', $this->tr()->translate('shop.flash.not_found'), 'error');
        return $this->view('plugins/shop/admin/payments_form', [
            'row' => $row,
            'form_action' => '/admin/shop/payments/' . $id . '/update',
        ], 'shop-payments', 'Оплата: ' . $row['title']);
    }

    public function update(Request $request, array $params): Response
    {
        if (!$this->auth->check()) return Response::redirect('/admin/login');
        if (!Csrf::validate((string) $request->input('_csrf'))) {
            return $this->redirect('/admin/shop/payments', $this->tr()->translate('shop.flash.csrf'), 'error');
        }
        $id = Filter::int($params['id'] ?? 0);
        $existing = $this->conn->builder('shop_payment_methods')->where('id', '=', $id)->first();
        if ($existing === null) return $this->redirect('/admin/shop/payments', $this->tr()->translate('shop.flash.not_found'), 'error');
        $data = $this->extract($request);
        if ($data['slug'] === '') $data['slug'] = Filter::slug($data['title']);
        if ($data['slug'] !== $existing['slug'] && $this->slugExists($data['slug'])) {
            return $this->redirect('/admin/shop/payments/' . $id . '/edit', $this->tr()->translate('shop.flash.slug_taken'), 'error');
        }
        $data['updated_at'] = date('Y-m-d H:i:s');
        $this->conn->builder('shop_payment_methods')->where('id', '=', $id)->update($data);
        return $this->redirect('/admin/shop/payments', $this->tr()->translate('shop.flash.saved'));
    }

    public function delete(Request $request, array $params): Response
    {
        if (!$this->auth->check()) return Response::redirect('/admin/login');
        if (!Csrf::validate((string) $request->input('_csrf'))) {
            return $this->redirect('/admin/shop/payments', $this->tr()->translate('shop.flash.csrf'), 'error');
        }
        $id = Filter::int($params['id'] ?? 0);
        $this->conn->builder('shop_payment_methods')->where('id', '=', $id)->delete();
        return $this->redirect('/admin/shop/payments', $this->tr()->translate('shop.flash.deleted'));
    }

    private function emptyRow(): array
    {
        return [
            'id' => 0, 'slug' => '', 'title' => '', 'description' => '',
            'kind' => 'cash', 'config' => '', 'is_active' => true, 'sort_order' => 0,
        ];
    }

    private function extract(Request $request): array
    {
        $kind = (string) $request->input('kind', 'cash');
        if (!in_array($kind, ['cash', 'card_offline', 'online_gateway', 'invoice'], true)) {
            $kind = 'cash';
        }
        $configRaw = (string) $request->input('config', '');
        $config = null;
        if ($configRaw !== '') {
            $decoded = json_decode($configRaw, true);
            $config = is_array($decoded) ? json_encode($decoded, JSON_UNESCAPED_UNICODE) : null;
        }
        return [
            'title'       => Filter::string($request->input('title'), 200),
            'slug'        => Filter::urlSlug($request->input('slug', '')),
            'description' => Filter::string($request->input('description'), 5000),
            'kind'        => $kind,
            'config'      => $config,
            'is_active'   => Filter::bool($request->input('is_active')),
            'sort_order'  => Filter::int($request->input('sort_order'), 0),
        ];
    }

    private function slugExists(string $slug): bool
    {
        return $this->conn->builder('shop_payment_methods')->where('slug', '=', $slug)->first() !== null;
    }
}
