<?php
namespace TbiBank\FusionPay\Model;

use Magento\Framework\App\ResourceConnection;

/**
 * Class TbiStatusUpdate
 *
 * This class provides functionality to update the custom 'tbi_status' field
 * in the 'sales_order' table for a given order ID.
 */
class TbiStatusUpdate
{
    /**
     * @var ResourceConnection
     */
    protected $resource;

    /**
     * Constructor
     *
     * @param ResourceConnection $resource Resource connection to interact with the database.
     */
    public function __construct(ResourceConnection $resource)
    {
        $this->resource = $resource;
    }

    /**
     * Update the 'tbi_status' of an order.
     *
     * @param int|string $orderId The ID of the order to update.
     * @param string $newStatus The new status to set for 'tbi_status'.
     * @param string|null $contractId Optional contract id to persist alongside status.
     */
    // public function updateStatus($orderId, $newStatus)
    // {
    //     // Obtain the database connection object
    //     $connection = $this->resource->getConnection();
        
    //     // Get the table name for 'sales_order', considering table prefix if set
    //     $table = $this->resource->getTableName('sales_order');

    //     // Data to update: set 'tbi_status' to the new status
    //     $data = ['tbi_status' => $newStatus];
        
    //     // Condition for which rows to update: match the 'entity_id' with the provided order ID
    //     $where = ['entity_id = ?' => (int)$orderId];

    //     // Execute the update query
    //     $connection->update($table, $data, $where);
    // }

    public function updateStatus($orderId, $newStatus, $contractId = null)
    {
        // Obtain the database connection object
        $connection = $this->resource->getConnection();

        // Data to update: set 'tbi_status' to the new status
        $data = ['tbi_status' => $newStatus];

        if ($contractId !== null && $contractId !== '') {
            $data['tbi_contract_id'] = (string) $contractId;
        }

        // Condition for which rows to update: match the 'increment_id' with the provided order ID
        $where = ['increment_id = ?' => (int)$orderId];

        $connection->beginTransaction();

        try {
            // Update the canonical 'sales_order' row...
            $connection->update($this->resource->getTableName('sales_order'), $data, $where);

            // ...and the denormalized 'sales_order_grid' row, since this update bypasses the
            // order model/events and would otherwise never reach the grid.
            $connection->update($this->resource->getTableName('sales_order_grid'), $data, $where);

            $connection->commit();
        } catch (\Throwable $e) {
            $connection->rollBack();
            throw $e;
        }
    }
}
