<?php

namespace Opencart\Extension\Alsendo\Repositories;

require_once(DIR_EXTENSION . 'alsendo/src/Models/OrderPickupPoint.php');

use Opencart\Extension\Alsendo\Models\OrderPickupPoint;

class OrderPickupPointRepository
{
    private object $db;
    private string $tablePrefix;
    private string $tableName;

    public function __construct(object $db, string $tablePrefix = '')
    {
        $this->db = $db;
        $this->tablePrefix = $tablePrefix ?: (defined('\DB_PREFIX') ? \DB_PREFIX : '');
        $this->tableName = $this->tablePrefix . 'alsendo_order_pickup_points';
    }

    public function getByOrderId(int $orderId): ?OrderPickupPoint
    {
        $query = $this->db->query("SELECT * FROM `" . $this->tableName . "` WHERE `order_id` = '" . $orderId . "'");
        
        if (!$query->num_rows) {
            return null;
        }
        
        return $this->createOrderPickupPointFromRow($query->row);
    }

    public function deleteByOrderId(int $orderId): void
    {
        $this->db->query("DELETE FROM `" . $this->tableName . "` WHERE `order_id` = '" . (int)$orderId . "'");
    }

    private function createOrderPickupPointFromRow(array $row): OrderPickupPoint
    {
        return new OrderPickupPoint(
            (int)$row['order_id'],
            $row['pickup_point']
        );
    }
}
