<?php
declare(strict_types=1);

namespace Autogedal\CheckoutFix\Plugin;

use Magento\Quote\Model\Quote;
use Psr\Log\LoggerInterface;

class QuoteTrackingPlugin
{
    public function __construct(
        private LoggerInterface $logger
    ) {
    }

    /**
     * Track when quotes are being saved as active
     */
    public function beforeSave(Quote $subject)
    {
        if ($subject->getIsActive() && $subject->getId()) {
            // Check if this quote already has orders
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $connection = $objectManager->get(\Magento\Framework\App\ResourceConnection::class)->getConnection();
            
            $orderCount = $connection->fetchOne(
                "SELECT COUNT(*) FROM sales_order WHERE quote_id = ?",
                [$subject->getId()]
            );
            
            if ($orderCount > 0) {
                // Log the reactivation with stack trace
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 15);
                $caller = '';
                foreach ($trace as $step) {
                    if (isset($step['class']) && isset($step['function'])) {
                        $caller .= $step['class'] . '::' . $step['function'] . "\n";
                    }
                }
                
                // Log to custom file with full stack trace
                $logFile = BP . '/var/log/quote_reactivation.log';
                $message = sprintf(
                    "[%s] Quote %d being saved as ACTIVE (has %d orders)\nStack trace:\n%s\n---\n",
                    date('Y-m-d H:i:s'),
                    $subject->getId(),
                    $orderCount,
                    $caller
                );
                file_put_contents($logFile, $message, FILE_APPEND | LOCK_EX);
                
                $this->logger->warning(sprintf(
                    'QUOTE SAVE AS ACTIVE: Quote %d (has %d orders)',
                    $subject->getId(),
                    $orderCount
                ));
            }
        }
        
        return [];
    }
}
