<?php

namespace Opencart\Admin\Model\Extension\Alsendo\Module;

use Opencart\System\Engine\Model;
use Opencart\System\Engine\Registry;

class AlsendoOrderSelectedPickupPoints extends Model
{
    public function __construct(Registry $registry)
    {
        parent::__construct($registry);
    }

    public function create(string $pickupPoint, ?int $orderId = null): int
    {
        $this->db->query("
            INSERT INTO `" . DB_PREFIX . "alsendo_order_selected_pickup_points`
            (`pickup_point`, `order_id`)
            VALUES ('" . $this->db->escape($pickupPoint) . "', " . ($orderId !== null ? (int) $orderId : "NULL") . ")
        ");
        return (int) $this->db->getLastId();
    }

    public function findLatestWithoutOrderByCode(string $code): ?array
    {
        $codeEscaped = $this->db->escape($code);
        $result = $this->db->query("
            SELECT *
            FROM `" . DB_PREFIX . "alsendo_order_selected_pickup_points`
            WHERE `order_id` IS NULL
            AND JSON_UNQUOTE(JSON_EXTRACT(`pickup_point`, '$.code')) = '" . $codeEscaped . "'
            ORDER BY `created_at` DESC
            LIMIT 1
        ");
        if (!$result->num_rows) {
            return null;
        }
        return $result->row;
    }

    public function findLatestWithoutOrderCreatedAround(string $orderDate, int $minutesMargin = 2): ?array
    {
        $orderDateEscaped = $this->db->escape($orderDate);
        $result = $this->db->query("
            SELECT *
            FROM `" . DB_PREFIX . "alsendo_order_selected_pickup_points`
            WHERE `order_id` IS NULL
            AND `created_at` >= DATE_SUB('" . $orderDateEscaped . "', INTERVAL " . (int) $minutesMargin . " MINUTE)
            AND `created_at` <= DATE_ADD('" . $orderDateEscaped . "', INTERVAL " . (int) $minutesMargin . " MINUTE)
            ORDER BY `created_at` DESC
            LIMIT 1
        ");
        if (!$result->num_rows) {
            return null;
        }
        return $result->row;
    }

    public function assignOrderId(int $id, int $orderId): void
    {
        $this->db->query("
            UPDATE `" . DB_PREFIX . "alsendo_order_selected_pickup_points`
            SET `order_id` = '" . (int) $orderId . "'
            WHERE `id` = '" . (int) $id . "'
        ");
    }
}
