<?php
declare(strict_types=1);

require_once __DIR__ . '/CartService.php';
require_once __DIR__ . '/../models/Order.php';
require_once __DIR__ . '/../models/Product.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../core/Tracking.php';

class OrderService
{
    public function createPendingFromCart(array $customerData): array
    {
        $cart = new CartService();
        $items = $cart->getItems();
        if (!$items) {
            return ['success' => false, 'message' => 'سبد خرید خالی است.'];
        }

        $verifiedItems = $this->rebuildItemsAndCheckStock($items);
        if (!$verifiedItems['success']) {
            return $verifiedItems;
        }

        $totals = $cart->totals();
        $orderTrackingId = $this->uniqueOrderTrackingId();

        $payload = [
            'order_tracking_id' => $orderTrackingId,
            'customer_name' => trim((string)($customerData['customer_name'] ?? '')),
            'customer_phone' => trim((string)($customerData['customer_phone'] ?? '')),
            'customer_address' => trim((string)($customerData['customer_address'] ?? '')),
            'total_amount' => $totals['grand_total'],
            'status' => 'pending_payment',
            'payment_status' => 'pending',
            'payment_ref' => null,
            'payment_authority' => null,
            'gateway' => 'zarinpal',
            'tracking_code' => null,
            'shipping_amount' => $totals['shipping'],
            'discount_amount' => $totals['discount'],
        ];

        if ($payload['customer_name'] === '' || $payload['customer_phone'] === '' || $payload['customer_address'] === '') {
            return ['success' => false, 'message' => 'اطلاعات مشتری کامل نیست.'];
        }

        $orderModel = new Order();
        $orderId = $orderModel->create($payload);
        foreach ($verifiedItems['items'] as $item) {
            $orderModel->addItem($orderId, $item);
        }

        return [
            'success' => true,
            'order_id' => $orderId,
            'order_tracking_id' => $orderTrackingId,
            'totals' => $totals,
        ];
    }

    public function markPaid(int $orderId, string $refId, string $authority): void
    {
        (new Order())->markPaid($orderId, $refId, $authority);
    }

    public function markFailed(int $orderId, string $reason, ?string $authority = null): void
    {
        (new Order())->markFailed($orderId, $reason, $authority);
    }

    private function uniqueOrderTrackingId(): string
    {
        for ($i = 0; $i < 20; $i++) {
            $id = Tracking::orderPublicId();
            $stmt = db()->prepare('SELECT id FROM orders WHERE order_tracking_id = :t LIMIT 1');
            $stmt->execute(['t' => $id]);
            if (!$stmt->fetch()) {
                return $id;
            }
        }
        return Tracking::orderPublicId();
    }

    private function rebuildItemsAndCheckStock(array $cartItems): array
    {
        $productModel = new Product();
        $items = [];
        foreach ($cartItems as $item) {
            $product = $productModel->find((int)$item['product_id']);
            if (!$product) {
                return ['success' => false, 'message' => 'یکی از محصولات حذف شده است.'];
            }

            $qty = max(1, (int)$item['quantity']);
            if ((int)$product['stock'] < $qty) {
                return ['success' => false, 'message' => 'موجودی محصول ' . $product['title'] . ' کافی نیست.'];
            }

            $items[] = [
                'product_id' => (int)$product['id'],
                'product_tracking_code' => (string)($product['tracking_code'] ?? ''),
                'product_title' => (string)$product['title'],
                'quantity' => $qty,
                'price' => (float)$product['price'],
            ];
        }

        return ['success' => true, 'items' => $items];
    }
}
