<?php

namespace Core\App\Services\Shipping;

use Core\App\Models\OrderModel;
use Core\App\Models\ShippingIntegrationModel;
use Core\App\Integrations\Shipping\YalidineClient;
use Core\App\Integrations\Shipping\EcotrackClient;
use Core\App\Support\OrderPricing;

class ShippingService
{
    protected OrderModel $orders;
    protected ShippingIntegrationModel $integrations;

    public function __construct()
    {
        $this->orders       = new OrderModel();
        $this->integrations = new ShippingIntegrationModel();
    }

    /**
     * ==================================================
     * Create Shipment for Order
     * ==================================================
     */
    public function createShipment(int $orderId): array
    {
        /* =============================
           Load Order
        ============================= */
        $order = $this->orders->getById($orderId);

        if (!$order) {
            return [
                'success' => false,
                'message' => __('orders.not_found', 'Order not found'),
            ];
        }

        if ($order['order_status'] !== 'confirmed') {
            return [
                'success' => false,
                'message' => __('shipping.order_not_confirmed', 'Order must be confirmed first'),
            ];
        }

        $extra = is_array($order['extra']) ? $order['extra'] : [];

        /* =============================
           Prevent duplicate shipment
        ============================= */
        if (!empty($extra['shipping']['tracking'])) {
            return [
                'success' => false,
                'message' => __('shipping.already_sent', 'Shipment already created'),
            ];
        }

        /* =============================
           Detect Shipping Provider
           (default: yalidine)
        ============================= */
        $provider = $extra['shipping']['provider'] ?? 'yalidine';

        $integration = $this->integrations->getByProvider($provider);

        if (
            !$integration ||
            (int)$integration['is_active'] !== 1 ||
            empty($integration['api_token'])
        ) {
            return [
                'success' => false,
                'message' => __('shipping.no_provider', 'No active shipping provider found'),
            ];
        }

        /* =============================
           Shared Order Data
        ============================= */
        $product     = $extra['product']   ?? [];
        $pricing     = OrderPricing::pricing($order);
        $destination = $extra['shipping']['destination'] ?? [];

        /* ==================================================
           PROVIDER SWITCH
        ================================================== */
        switch ($provider) {

            /* =============================
               YALIDINE
            ============================= */
            case 'yalidine':

                $client = new YalidineClient($integration['api_token']);

                $payload = [
                    'order_id'       => $order['id'],
                    'customer_name'  => $order['full_name'],
                    'phone'          => $order['phone'],
                    'address'        => $order['address'],
                    'wilaya'         => $destination['state_code'] ?? null,
                    'commune'        => $destination['city_name']  ?? null,
                    'product'        => $product['name'] ?? __('orders.product', 'Product'),
                    'price'          => OrderPricing::effectiveTotal($order),
                    'declared_value' => $pricing['products_total'] ?? $order['total_amount'],
                ];

                $response = $client->createParcel($payload);

                if (!$response['success']) {
                    $extra['shipping'] = array_merge(
                        $extra['shipping'] ?? [],
                        [
                            'provider' => 'yalidine',
                            'status'   => 'failed',
                            'error'    => $response['error'] ?? 'API_ERROR',
                            'raw'      => $response['raw'] ?? null,
                            'updated'  => date('Y-m-d H:i:s'),
                        ]
                    );

                    $this->orders->updateExtra($orderId, $extra);

                    return [
                        'success' => false,
                        'message' => __('shipping.failed', 'Shipment creation failed'),
                    ];
                }

                $extra['shipping'] = array_merge(
                    $extra['shipping'] ?? [],
                    [
                        'provider'   => 'yalidine',
                        'status'     => 'created',
                        'tracking'   => $response['data']['tracking'] ?? null,
                        'response'   => $response['data'],
                        'created_at' => date('Y-m-d H:i:s'),
                    ]
                );

                $this->orders->updateExtra($orderId, $extra);

                return [
                    'success' => true,
                    'message' => __('shipping.created', 'Shipment created successfully'),
                ];

/* =============================
   MAYSTRO
============================= */
case 'maystro':

    // تحميل Client
    $client = new \Core\App\Integrations\Shipping\MaystroClient(
        $integration['api_token']
    );

    /*
     * ⚠️ ملاحظة مهمة:
     * - Maystro يعتمد على commune_id
     * - نحن لا نفترض أي تحويل
     * - نمرر القيم كما هي محفوظة عندنا
     */

    $payload = [
        'customer_name' => $order['full_name'],
        'customer_phone'=> $order['phone'],
        'address'       => $order['address'],
        'wilaya_code'   => $destination['state_code'] ?? null,
        'commune_name'  => $destination['city_name']  ?? null,

        'order_reference' => (string) $order['id'],
        'amount'          => OrderPricing::effectiveTotal($order),

        // نوع التوصيل حسب ما هو مخزن
        'delivery_type'   => $extra['shipping']['type'] ?? 'home',
    ];

    // إرسال الطلب
    $response = $client->createOrder($payload);

    if (empty($response['success'])) {

        $extra['shipping'] = array_merge(
            $extra['shipping'] ?? [],
            [
                'provider' => 'maystro',
                'status'   => 'failed',
                'response' => $response,
                'updated'  => date('Y-m-d H:i:s'),
            ]
        );

        $this->orders->updateExtra($orderId, $extra);

        return [
            'success' => false,
            'message' => __('shipping.failed', 'Shipment creation failed'),
        ];
    }

    // محاولة استخراج tracking بدون افتراض
    $tracking = null;
    if (
        isset($response['data']) &&
        is_array($response['data']) &&
        isset($response['data']['order_id'])
    ) {
        $tracking = (string) $response['data']['order_id'];
    }

    $extra['shipping'] = array_merge(
        $extra['shipping'] ?? [],
        [
            'provider'   => 'maystro',
            'status'     => 'created',
            'tracking'   => $tracking,
            'response'   => $response['data'] ?? $response,
            'created_at' => date('Y-m-d H:i:s'),
        ]
    );

    $this->orders->updateExtra($orderId, $extra);

    return [
        'success' => true,
        'message' => __('shipping.created', 'Shipment created successfully'),
    ];

            /* =============================
               ECOTRACK (NOT ACTIVE YET)
            ============================= */
            case 'ecotrack':

                // ❗ في هذه المرحلة لا ننشئ شحنة
                // فقط نُثبت أن النظام يعرف ECOTRACK
                return [
                    'success' => false,
                    'message' => __('shipping.ecotrack_not_ready',
                        'ECOTRACK is registered but shipment creation is not enabled yet.'),
                ];

            /* =============================
               UNKNOWN PROVIDER
            ============================= */
            default:
                return [
                    'success' => false,
                    'message' => __('shipping.provider_unknown', 'Unknown shipping provider'),
                ];
        }
    }
    
    /**
 * Resolve shipping price for any provider (yalidine / maystro / ...)
 */
protected function resolvePrice(
    string $provider,
    string $deliveryType,
    string $wilayaCode
): float {

    $stmt = $this->db->prepare("
        SELECT price
        FROM shipping_prices
        WHERE provider = :provider
          AND wilaya_code = :wilaya
          AND delivery_type = :type
          AND is_active = 1
        LIMIT 1
    ");

    $stmt->execute([
        ':provider' => $provider,
        ':wilaya'   => $wilayaCode,
        ':type'     => $deliveryType,
    ]);

    return (float) ($stmt->fetchColumn() ?? 0);
}

}
