<?php

namespace Opencart\Extension\Alsendo\Providers;

require_once(DIR_EXTENSION . 'alsendo/src/DTO/FullOrderDTO.php');
require_once(DIR_EXTENSION . 'alsendo/src/Providers/OrderPickupPointProvider.php');
require_once(DIR_EXTENSION . 'alsendo/src/Providers/OrderShipmentProvider.php');
require_once(DIR_EXTENSION . 'alsendo/src/Repositories/OrderPickupPointRepository.php');
require_once(DIR_EXTENSION . 'alsendo/src/Repositories/OrderShipmentRepository.php');
require_once(DIR_EXTENSION . 'alsendo/src/Repositories/OrderShipmentPackageRepository.php');

use Opencart\Extension\Alsendo\DTO\FullOrderDTO;
use Opencart\Extension\Alsendo\Providers\OrderPickupPointProvider;
use Opencart\Extension\Alsendo\Providers\OrderShipmentProvider;
use Opencart\Extension\Alsendo\Repositories\OrderPickupPointRepository;
use Opencart\Extension\Alsendo\Repositories\OrderShipmentRepository;
use Opencart\Extension\Alsendo\Repositories\OrderShipmentPackageRepository;
use Opencart\System\Engine\Registry;

class FullOrderProvider
{
    private Registry $registry;
    private object $db;
    private string $dbPrefix;
    private OrderPickupPointProvider $orderPickupPointProvider;
    private OrderShipmentProvider $orderShipmentProvider;

    public function __construct(Registry $registry, object $db)
    {
        $this->registry = $registry;
        $this->db = $db;
        $this->dbPrefix = defined('\DB_PREFIX') ? \DB_PREFIX : '';

        $orderPickupPointRepository = new OrderPickupPointRepository($this->db, $this->dbPrefix);
        $orderShipmentRepository = new OrderShipmentRepository($this->db, $this->dbPrefix);
        $orderShipmentPackageRepository = new OrderShipmentPackageRepository($this->db, $this->dbPrefix);

        $this->orderPickupPointProvider = new OrderPickupPointProvider($orderPickupPointRepository);
        $this->orderShipmentProvider = new OrderShipmentProvider($orderShipmentRepository, $orderShipmentPackageRepository);
    }

    public function getByOrderId(int $orderId): FullOrderDTO
    {
        $openCartOrder = $this->getOpenCartOrder($orderId);
        $this->registry->load->model('extension/alsendo/module/alsendo_order_details');
        $orderDetails = $this->registry->model_extension_alsendo_module_alsendo_order_details->getOrderDetailsByOrderId($orderId);
        $orderShipments = $this->orderShipmentProvider->getAllByOrderIdWithPackages($orderId);
        $orderPickupPoint = $this->orderPickupPointProvider->getOrderPickupPointByOrderId($orderId);

        return new FullOrderDTO(
            $openCartOrder,
            $orderDetails,
            $orderShipments,
            $orderPickupPoint
        );
    }

    private function getOpenCartOrder(int $orderId): array
    {
        $query = $this->db->query("SELECT * FROM `" . $this->dbPrefix . "order` WHERE `order_id` = '" . (int)$orderId . "'");
        
        if (!$query->num_rows) {
            return [];
        }

        return $query->row;
    }
}
