<?php

namespace Core\App\Controllers;

use Core\App\Models\OrderModel;
use Core\App\Models\ShippingIntegrationModel;
use Core\App\Integrations\Shipping\YalidineClient;

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

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

    /**
     * ============================================
     * Prepare Shipment (Confirmed Orders Only)
     * ============================================
     */
    public function prepare($orderId)
    {
        $order = $this->orders->getById((int)$orderId);
        if (!$order) {
            echo __('orders.not_found', 'Order not found');
            exit;
        }

        $extra = $order['extra'] ?? [];

        // تأكيد الطلب فقط
        if ($order['order_status'] !== 'confirmed') {
            echo __('orders.must_be_confirmed', 'Order must be confirmed first.');
            exit;
        }

        // منع إعادة الشحن
        if (!empty($extra['shipping']['tracking'])) {
            echo __('shipping.already_prepared', 'Shipment already prepared.');
            exit;
        }

        // جلب إعدادات Yalidine
        $integration = $this->integrations->findByProvider('yalidine');
        if (!$integration || (int)$integration['enabled'] !== 1) {
            echo __('shipping.provider_not_enabled', 'Shipping provider not enabled.');
            exit;
        }

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

        // ===== إنشاء الشحنة (مثال أساسي) =====
        $response = $client->createParcel([
            'order_id'      => $order['id'],
            'customer_name' => $order['full_name'],
            'phone'         => $order['phone'],
            'address'       => $order['address'],
            'price'         => $order['total_amount'],
        ]);

        if (!$response['success']) {
            $extra['shipping_error'] = [
                'provider' => 'yalidine',
                'message'  => $response['error'] ?? 'Unknown error',
                'time'     => date('Y-m-d H:i:s'),
            ];

            $this->orders->updateExtra($order['id'], $extra);

            echo __('shipping.failed', 'Shipment creation failed.');
            exit;
        }

        // حفظ نتيجة الشحن
        $extra['shipping'] = [
            'provider'   => 'yalidine',
            'tracking'   => $response['data']['tracking'] ?? '',
            'status'     => 'created',
            'created_at' => date('Y-m-d H:i:s'),
            'response'   => $response['data'],
        ];

        $this->orders->updateExtra($order['id'], $extra);

        header('Location: /admin/orders/view/' . $order['id']);
        exit;
    }
}
