<?php

namespace PortalPeople\OrderWebhook\Plugin\Sales\Model\ResourceModel\Order\Grid;

use Magento\Sales\Model\ResourceModel\Order\Grid\Collection;

/**
 * Joins ngauge columns from sales_order into the order grid collection.
 */
class CollectionPlugin
{
    /**
     * Track whether we have already applied the join in this request.
     */
    private bool $isJoined = false;

    /**
     * Join the three NGauge columns before the collection loads.
     *
     * @param Collection $subject
     * @param bool       $printQuery
     * @param bool       $logQuery
     * @return array
     */
    public function beforeLoad(Collection $subject, $printQuery = false, $logQuery = false): array
    {
        if (!$this->isJoined && !$subject->isLoaded()) {
            $subject->getSelect()->joinLeft(
                ['ngauge_so' => $subject->getTable('sales_order')],
                'main_table.entity_id = ngauge_so.entity_id',
                ['ngauge_order_no', 'ngauge_order_id', 'ngauge_order_link']
            );
            $this->isJoined = true;
        }

        return [$printQuery, $logQuery];
    }
}
