<?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;

/**
 * Способы доставки. Базовая реализация: фиксированная стоимость, бесплатно от
 * суммы, самовывоз. Платные плагины (Казпочта, Nova Poshta, DHL, UPS…) добавляют
 * свои способы через хук shop.shipping.methods и собственные контроллеры расчёта.
 */
final class ShippingAdminController 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_shipping_methods')
            ->orderBy('sort_order', 'asc')->orderBy('id', 'asc')->get();
        return $this->view('plugins/shop/admin/shipping_index', [
            'methods' => $rows,
            'total' => count($rows),
        ], 'shop-shipping', $this->tr()->translate('shop.shipping_list.title'));
    }

    public function create(Request $request): Response
    {
        if (!$this->auth->check()) return Response::redirect('/admin/login');
        return $this->view('plugins/shop/admin/shipping_form', [
            'row' => $this->emptyRow(),
            'form_action' => '/admin/shop/shipping/create',
        ], 'shop-shipping', $this->tr()->translate('shop.shipping_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/shipping/create', $this->tr()->translate('shop.flash.csrf'), 'error');
        }
        $data = $this->extract($request);
        if ($data['title'] === '') {
            return $this->redirect('/admin/shop/shipping/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/shipping/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_shipping_methods')->insert($data);
        return $this->redirect('/admin/shop/shipping', $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_shipping_methods')->where('id', '=', $id)->first();
        if ($row === null) return $this->redirect('/admin/shop/shipping', $this->tr()->translate('shop.flash.not_found'), 'error');
        return $this->view('plugins/shop/admin/shipping_form', [
            'row' => $row,
            'form_action' => '/admin/shop/shipping/' . $id . '/update',
        ], 'shop-shipping', 'Доставка: ' . $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/shipping', $this->tr()->translate('shop.flash.csrf'), 'error');
        }
        $id = Filter::int($params['id'] ?? 0);
        $existing = $this->conn->builder('shop_shipping_methods')->where('id', '=', $id)->first();
        if ($existing === null) return $this->redirect('/admin/shop/shipping', $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/shipping/' . $id . '/edit', $this->tr()->translate('shop.flash.slug_taken'), 'error');
        }
        $data['updated_at'] = date('Y-m-d H:i:s');
        $this->conn->builder('shop_shipping_methods')->where('id', '=', $id)->update($data);
        return $this->redirect('/admin/shop/shipping', $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/shipping', $this->tr()->translate('shop.flash.csrf'), 'error');
        }
        $id = Filter::int($params['id'] ?? 0);
        $this->conn->builder('shop_shipping_methods')->where('id', '=', $id)->delete();
        return $this->redirect('/admin/shop/shipping', $this->tr()->translate('shop.flash.deleted'));
    }

    private function emptyRow(): array
    {
        return [
            'id' => 0, 'slug' => '', 'title' => '', 'description' => '',
            'mode' => 'flat', 'cost' => 0, 'free_from' => '',
            'is_active' => true, 'sort_order' => 0,
        ];
    }

    private function extract(Request $request): array
    {
        $mode = (string) $request->input('mode', 'flat');
        if (!in_array($mode, ['flat', 'by_weight', 'free', 'pickup'], true)) {
            $mode = 'flat';
        }
        $freeFrom = (string) $request->input('free_from', '');
        return [
            'title'       => Filter::string($request->input('title'), 200),
            'slug'        => Filter::urlSlug($request->input('slug', '')),
            'description' => Filter::string($request->input('description'), 5000),
            'mode'        => $mode,
            'cost'        => (float) $request->input('cost', 0),
            'free_from'   => $freeFrom === '' ? null : (float) $freeFrom,
            '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_shipping_methods')->where('slug', '=', $slug)->first() !== null;
    }
}
