<?php

namespace Opencart\Extension\Alsendo\Handlers;

require_once(DIR_EXTENSION . 'alsendo/src/Models/OrderShipment.php');
require_once(DIR_EXTENSION . 'alsendo/src/DTO/Entity/AlsendoShipmentStatusEntity.php');

use Opencart\Extension\Alsendo\DTO\Entity\AlsendoShipmentStatusEntity;
use Opencart\Extension\Alsendo\Models\OrderShipment;
use Opencart\System\Engine\Registry;
use Opencart\System\Library\DB;

class AlsendoShipmentStatusChangeHandler
{
    private Registry $registry;
    private DB $db;

    public function __construct(Registry $registry, DB $db)
    {
        $this->registry = $registry;
        $this->db = $db;
    }

    public function handle(OrderShipment $orderShipment, bool $isCatalog = false): void {
        $this->registry->load->model('extension/alsendo/module/alsendo_shipment_status');
        /** @var AlsendoShipmentStatusEntity[] $shipmentStatuses */
        $shipmentStatuses = $this->registry->model_extension_alsendo_module_alsendo_shipment_status->getCurrentRegionShipmentStatuses();

        $currentShipmentStatusName = $orderShipment->getStatus();
        if (empty($currentShipmentStatusName)) {
            return;
        }

        $currentShipmentStatusName = strtolower($currentShipmentStatusName);

        foreach ($shipmentStatuses as $shipmentStatus) {
            $shipmentStatusName = strtolower($shipmentStatus->name);

            if ($shipmentStatusName !== $currentShipmentStatusName) {
                continue;
            }

            if (empty($shipmentStatus->orderStatusId)) {
                return;
            }

            if ($isCatalog) {
                $this->registry->load->model('checkout/order');
                $openCartOrderInfo = $this->registry->model_checkout_order->getOrder($orderShipment->getOrderId());
            } else {
                $this->registry->load->model('sale/order');
                $openCartOrderInfo = $this->registry->model_sale_order->getOrder($orderShipment->getOrderId());
            }

            if ((int)$openCartOrderInfo['order_status_id'] === $shipmentStatus->orderStatusId) {
                return;
            }

            $orderId = $orderShipment->getOrderId();
            $orderStatusId = $shipmentStatus->orderStatusId;

            $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order_history` WHERE `order_id` = " . (int)$orderId . " ORDER BY `date_added` DESC");

            $latestStatusId = $query->row['order_status_id'] ?? null;

            if ($latestStatusId !== (int)$orderStatusId) {
                try {
                    $this->db->query(
                        "INSERT INTO `" . DB_PREFIX . "order_history` 
                    SET `order_id` = " . $orderId . ",
                        `order_status_id` = " . $orderStatusId . ",
                        `notify` = 0,
                        `comment` = '',
                        `date_added` = NOW()"
                    );

                    // Update order table
                    $this->db->query(
                        "UPDATE `" . DB_PREFIX . "order` 
                    SET `order_status_id` = " . $orderStatusId . "
                    WHERE `order_id` = " . $orderId
                    );
                } catch (\Exception $e) {
                    return;
                }
            }


            return;
        }
    }
} 