<?php
/**
 *  Magento 2 Google Indexing API
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Anowave license that is
 * available through the world-wide-web at this URL:
 * http://www.anowave.com/license-agreement/
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category 	Anowave
 * @package 	Anowave_Indexing
 * @copyright 	Copyright (c) 2026 Anowave (http://www.anowave.com/)
 * @license  	http://www.anowave.com/license-agreement/
 */
 
namespace Anowave\Ec\Model;

use Anowave\Ec\Model\TransactionFactory;
use Anowave\Ec\Model\ResourceModel\Transaction\CollectionFactory;
use Anowave\Ec\Api\TransactionRepositoryInterface;
use Anowave\Ec\Api\Data\TransactionInterface;

class TransactionRepository implements TransactionRepositoryInterface
{
    protected CollectionFactory $transactionCollectionFactory;
    protected TransactionFactory $transactionFactory;

    public function __construct
    (
        TransactionFactory $transactionFactory,
        CollectionFactory $transactionCollectionFactory
    )
    {
        $this->transactionFactory = $transactionFactory;
        $this->transactionCollectionFactory = $transactionCollectionFactory;
    }

    /**
     * Get by order id
     * 
     * @param int $order_id
     * 
     * @return [type]
     */
    public function getByOrderId(int $order_id = 0)
    {
        $collection = $this->transactionCollectionFactory->create()->addFieldToFilter('ec_order_id', $order_id)->addFieldToSelect('*');


        if ($collection->getSize())
        {
            return $collection->getFirstItem();
        }
        else 
        {
            $transaction = $this->transactionFactory->create()->setData(
            [
                'ec_track'          => 0,
                'ec_order_id'       => 0,
                'ec_order_type'     => 0,
                'ec_consent_id'     => null,
                'ec_consent_uuid'   => null,
                'ec_cookie_ga'      => null,
                'ec_user_agent'     => null,
                'ec_payload'        => null,
                'ec_placed_at'      => null,
                'ec_updated_at'     => null
            ]);
        }

        return $transaction;
    }

    /**
     * Get by id
     * 
     * @param int $id
     * 
     * @return [type]
     */
    public function getById(int $id = 0)
    {
        $transaction = $this->transactionFactory->create()->load($id);

        if (!$transaction->getId()) 
        {
            throw new \Magento\Framework\Exception\NoSuchEntityException();
        }

        return $transaction;
    }

    public function save(TransactionInterface $transaction)
    {
        $transaction->getResource()->save($transaction);
    }
}