<?php

namespace Core\App\Controllers;

use Core\App\Models\OrderModel;

class OrderTrackingController
{
    protected OrderModel $orders;

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

    /* =============================
       SHOW TRACKING (ADMIN)
    ============================= */
    public function index()
    {
        // إذا جاء tracking من الرابط
        if (!empty($_GET['tracking'])) {
            return $this->track($_GET['tracking']);
        }

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/orders/order_tracking.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    /* =============================
       HANDLE TRACKING REQUEST
    ============================= */
    public function track($value = null)
    {
        $value = trim(
            $value ??
            ($_POST['value'] ?? '') ??
            ($_GET['tracking'] ?? '')
        );

        require ROOT_PATH . '/admin/templates/header.php';

        if ($value === '') {
            $error = __('tracking.invalid', 'Invalid tracking data');
            require ROOT_PATH . '/admin/templates/orders/order_tracking.php';
            require ROOT_PATH . '/admin/templates/footer.php';
            return;
        }

        // مهم: أرقام التتبع عند بعض الشركات (مثل Maystro) تكون رقمية بالكامل
        // لذلك نبحث أولاً برقم التتبع ثم نرجع إلى رقم الطلب كخطة بديلة
        $order = $this->orders->getByTracking($value);

        if (!$order && ctype_digit($value)) {
            $order = $this->orders->getById((int)$value);
        }

        if (!$order) {
            $error = __('tracking.not_found', 'Order not found');
            require ROOT_PATH . '/admin/templates/orders/order_tracking.php';
            require ROOT_PATH . '/admin/templates/footer.php';
            return;
        }

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

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

        require ROOT_PATH . '/admin/templates/orders/order_tracking_result.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }
}
