<?php

namespace Core\App\Controllers;

use Core\App\Models\OrderModel;
use Core\App\Services\Shipping\ShippingStatusPresenter;

class MyShipmentsController
{
    public function index()
    {
        $orderModel = new OrderModel();
        $orders = $orderModel->getShippedOrders();

        /* =============================
           SHIPPING STATISTICS
        ============================= */

        $stats = [
            'total'      => 0,
            'in_progress'=> 0,
            'delivered'  => 0,
            'returned'   => 0,
            'cancelled'  => 0,
            'providers'  => [
                'ecotrack' => 0,
                'maystro'  => 0,
            ],
        ];

        foreach ($orders as $order) {

            $shipping = $order['extra']['shipping'] ?? null;
            if (!$shipping) {
                continue;
            }

            $stats['total']++;

            $provider = strtolower($shipping['provider'] ?? '');
            if (isset($stats['providers'][$provider])) {
                $stats['providers'][$provider]++;
            }

            if ($provider === 'maystro') {
                if (ShippingStatusPresenter::isDelivered($provider, $shipping)) {
                    $stats['delivered']++;
                } elseif (ShippingStatusPresenter::isIssue($provider, $shipping)) {
                    $statusText = mb_strtolower((string)($shipping['status'] ?? ''));
                    $statusCode = isset($shipping['status_code']) ? (int)$shipping['status_code'] : null;

                    if ($statusCode === 50 || str_contains($statusText, 'cancel')) {
                        $stats['cancelled']++;
                    } else {
                        $stats['returned']++;
                    }
                } else {
                    $stats['in_progress']++;
                }
            } else {
                $status = mb_strtolower((string)($shipping['status'] ?? ''));

                if (str_contains($status, 'livr')) {
                    $stats['delivered']++;
                } elseif (str_contains($status, 'retour')) {
                    $stats['returned']++;
                } elseif (str_contains($status, 'annul') || str_contains($status, 'cancel')) {
                    $stats['cancelled']++;
                } else {
                    $stats['in_progress']++;
                }
            }
        }

        // نفس أسلوب SettingsController بالضبط
        extract([
            'orders' => $orders,
            'stats'  => $stats,
        ]);

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

