<?php
/**
 * NOTICE OF LICENSE.
 *
 * Copyright 2022 Kosmonaft.dev
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 *  @author    Alexandre DEBUSSCHÈRE <alexandre@kosmonaft.dev>
 *  @copyright 2022 - 2023 Kosmonaft.dev
 *  @license   MIT
 */

if (!defined('_PS_VERSION_')) {
    exit;
}

/**
 * Class MRMaxDelivery
 */
class MRMaxDelivery extends ObjectModel
{

    /** @var int */
    public $id_cart;

    /** @var int */
    public $id_customer;

    /** @var string */
    public $type;

    /** @var string */
    public $prid;

    /** @var float */
    public $weight;

    /** @var int */
    public $nb_labels;

    /** @var string */
    public $date_add;

    /** @var string */
    public $date_upd;

    /** @var array */
    public static $definition = [
        'table' => 'mrmax_delivery',
        'primary' => 'id_mrmax_delivery',
        'multilang' => false,
        'multilang_shop' => false,
        'fields' => [
            'id_cart' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'],
            'id_customer' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'],
            'type' => ['type' => self::TYPE_STRING],
            'prid' => ['type' => self::TYPE_STRING],
            'weight' => ['type' => self::TYPE_FLOAT],
            'nb_labels' => ['type' => self::TYPE_INT],
            'date_add' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
            'date_upd' => ['type' => self::TYPE_DATE, 'validate' => 'isDate']
        ]
    ];

    /**
     * @param int $id_cart
     * @return MRMaxDelivery|null
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public static function getByIdCart($id_cart)
    {
        $id_mrmax_delivery = (int)Db::getInstance()->getValue(
            'SELECT `id_mrmax_delivery`
            FROM `'._DB_PREFIX_.'mrmax_delivery`
            WHERE `id_cart` = '.(int)$id_cart
        );

        return $id_mrmax_delivery ? new self($id_mrmax_delivery) : null;
    }

    /**
     * @param int $id_cart
     * @return MRMaxDelivery
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public static function getByIdCartOrNew($id_cart)
    {
        $delivery = self::getByIdCart($id_cart) ?: new self();
        $delivery->id_cart = $id_cart;

        return $delivery;
    }

    /**
     * @param int $id_customer
     * @return MRMaxDelivery|null
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public static function getByIdCustomer($id_customer)
    {
        $id_mrmax_delivery = (int)Db::getInstance()->getValue(
            'SELECT `id_mrmax_delivery`
            FROM `'._DB_PREFIX_.'mrmax_delivery`
            WHERE `id_customer` = '.(int)$id_customer.'
            ORDER BY `id_customer` DESC'
        );

        return $id_mrmax_delivery ? new self($id_mrmax_delivery) : null;
    }

    /**
     * @param int $id_customer
     * @return MRMaxDelivery
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public static function getByIdCustomerOrNew($id_customer)
    {
        $delivery = self::getByIdCustomer($id_customer) ?: new self();
        $delivery->id_customer = $id_customer;

        return $delivery;
    }

    /**
     * @param int $id_cart
     * @return string
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public static function getPrIdByIdCart($id_cart)
    {
        return self::getByIdCartOrNew($id_cart)->prid;
    }

    /**
     * @param int $limit
     * @param int $offset
     * @param bool $cron
     * @return array|bool|resource|null
     * @throws PrestaShopDatabaseException
     */
    public static function getPaginatedOrders($limit = 0, $offset = 25, $cron = false)
    {
        $query = new DbQuery();

        if ($cron) {
            // Tracking cron, only get the id_order and shipping_number
            $earlier_date = date('Y-m-d H:i:s', strtotime('1 MONTH AGO MIDNIGHT'));
            $query = $query
                ->select('o.`id_order`, oc.`tracking_number` AS `shipping_number`')
                ->from('orders', 'o')
                ->leftJoin('order_carrier', 'oc', 'oc.`id_order` = o.`id_order`')
                ->where('oc.`tracking_number` != ""')
                ->where('o.`date_upd` >= "'.pSQL($earlier_date).'"')
                ->where('oc.`id_carrier` IN (SELECT c.`id_carrier`
                    FROM `'._DB_PREFIX_.'carrier` c
                    LEFT JOIN `'._DB_PREFIX_.'mrmax_carrier` mc ON c.`id_reference` = mc.`id_reference`
                    WHERE c.`id_reference` = mc.`id_reference`
                )');
        } else {
            $query = $query
                ->select('*')
                ->from(self::$definition['table'], 'bo')
                ->innerJoin(
                    'orders',
                    'o',
                    'bo.`id_cart` = o.`id_cart`'
                )
                ->orderBy('bo.`date_add` DESC');
        }

        $query = $query
            ->limit($limit, $offset);

        return Db::getInstance()->executeS($query);
    }
}
