<?php
declare(strict_types=1);

namespace Celena\Plugin\Shop\Controllers;

use Celena\Core\Database\Connection;
use Celena\Core\Http\Request;
use Celena\Core\Http\Response;
use Celena\Core\Security\Csrf;
use Celena\Core\Security\Filter;

/**
 * Эндпоинт добавления отзыва. POST /shop/reviews/add — принимает форму
 * (product_id, author_name, author_email, rating, content). Возвращает JSON
 * для AJAX-форм или редиректит обратно на страницу товара для не-AJAX.
 */
final class ReviewsController
{
    public function __construct(
        private readonly Connection $conn,
    ) {
    }

    public function add(Request $request): Response
    {
        // CSRF-валидация (общая для всех POST в Celena).
        $token = (string) ($request->input('_csrf', '') ?: $request->header('X-CSRF-Token'));
        if (!Csrf::validate($token)) {
            return $this->respond($request, ['ok' => false, 'error' => 'csrf'], 419);
        }

        $productId = Filter::int($request->input('product_id', 0), 0);
        $name      = Filter::string($request->input('author_name', ''), 100);
        $email     = Filter::email($request->input('author_email', '')) ?? '';
        $rating    = Filter::int($request->input('rating', 0), 0);
        $content   = Filter::string($request->input('content', ''), 5000);

        $errors = [];
        if ($productId <= 0) $errors[] = 'product_id';
        if ($name === '' || mb_strlen($name, 'UTF-8') < 2) $errors[] = 'author_name';
        if ($rating < 1 || $rating > 5) $errors[] = 'rating';
        if (mb_strlen($content, 'UTF-8') < 5) $errors[] = 'content';
        if ($errors !== []) {
            return $this->respond($request, ['ok' => false, 'error' => 'validation', 'fields' => $errors], 422);
        }

        // Товар должен существовать
        $product = $this->conn->builder('shop_products')
            ->where('id', '=', $productId)
            ->where('is_active', '=', true)
            ->first();
        if ($product === null) {
            return $this->respond($request, ['ok' => false, 'error' => 'not_found'], 404);
        }

        $this->conn->builder('shop_reviews')->insert([
            'product_id'   => $productId,
            'author_name'  => $name,
            'author_email' => $email !== '' ? $email : null,
            'rating'       => $rating,
            'content'      => $content,
            'is_approved'  => true, // auto-approve; модерация — TODO
            'created_at'   => date('Y-m-d H:i:s'),
        ]);

        return $this->respond(
            $request,
            ['ok' => true, 'redirect' => '/shop/product/' . (string) $product['slug'] . '#cm-pp-reviews'],
            200,
            '/shop/product/' . (string) $product['slug'] . '#cm-pp-reviews'
        );
    }

    private function respond(Request $request, array $payload, int $status = 200, ?string $redirect = null): Response
    {
        $accept = (string) $request->header('Accept');
        $isAjax = str_contains($accept, 'json')
            || strtolower((string) $request->header('X-Requested-With')) === 'xmlhttprequest';
        if ($isAjax) {
            return Response::json($payload, $status);
        }
        if ($redirect !== null) {
            return Response::redirect($redirect);
        }
        // Fallback: редирект назад
        $back = (string) ($request->header('Referer') ?: '/shop');
        return Response::redirect($back);
    }
}
