<?php
declare(strict_types=1);
// use PaymentService;
require_once __DIR__ . '/../models/Product.php';
require_once __DIR__ . '/../models/Order.php';
require_once __DIR__ . '/../services/PaymentService.php';
require_once __DIR__ . '/../services/OrderService.php';
require_once __DIR__ . '/../services/CartService.php';

class ShopController
{
    public function products(): array
    {
        return (new Product())->all(100);
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function catalogue(?string $q, ?string $category): array
    {
        return (new Product())->listPublic($q, $category, 500);
    }

    public function product(int $id): ?array
    {
        return (new Product())->find($id);
    }

    public function search(string $q): array
    {
        return (new Product())->search($q);
    }

    public function checkout(array $orderData, array $items): array
    {
        // Legacy compatibility: old callers may still invoke checkout().
        // The new flow always builds items from server-side cart.
        unset($items);
        return $this->startCheckout($orderData);
    }

    public function cartSummary(): array
    {
        $cart = new CartService();
        return [
            'items' => $cart->getItems(),
            'totals' => $cart->totals(),
        ];
    }

    public function startCheckout(array $customerData): array
    {
        $orderService = new OrderService();
        $created = $orderService->createPendingFromCart($customerData);
        if (!$created['success']) {
            return $created;
        }

        $orderId = (int)$created['order_id'];
        $payment = (new PaymentService())->requestPayment(
            (float)$created['totals']['grand_total'],
            'پرداخت سفارش #' . $orderId,
            (string)$customerData['customer_phone'],
            $orderId
        );

        if (empty($payment['success'])) {
            $orderService->markFailed($orderId, $payment['message'] ?? 'gateway_error');
            return ['success' => false, 'message' => $payment['message'] ?? 'خطای پرداخت'];
        }

        (new \Order())->markAuthority($orderId, (string)$payment['authority']);
        return [
            'success' => true,
            'order_id' => $orderId,
            'gateway_url' => (string)$payment['gateway_url'],
        ];
    }
}
