<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Grid\Transfer;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use WriteTextAI\WriteTextAI\Model\BulkTransferRequestsManager;
use WriteTextAI\WriteTextAI\Model\ApiManager;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;
use Magento\Framework\Stdlib\DateTime\DateTime;

class Cancel extends Action
{
    /**
     * @var ApiManager
     */
    protected $apiManager;

    /**
     * @var BulkTransferRequestsManager
     */
    protected $bulkTransferRequestsManager;
    
    /**
     * @var StoreHelper
     */
    protected $storeHelper;
    
    /**
     * @var DateTime
     */
    protected $dateTime;
    
    /**
     * Constructor
     *
     * @param Context $context
     * @param ApiManager $apiManager
     * @param BulkTransferRequestsManager $bulkTransferRequestsManager
     * @param StoreHelper $storeHelper
     * @param DateTime $dateTime
     */
    public function __construct(
        Context $context,
        ApiManager $apiManager,
        BulkTransferRequestsManager $bulkTransferRequestsManager,
        StoreHelper $storeHelper,
        DateTime $dateTime
    ) {
        $this->apiManager = $apiManager;
        $this->bulkTransferRequestsManager = $bulkTransferRequestsManager;
        $this->storeHelper = $storeHelper;
        $this->dateTime = $dateTime;
        parent::__construct($context);
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        try {
            $id = $this->getRequest()->getParam('id');
            $user = $this->getRequest()->getParam('user');
            
            // Get current progress before deleting
            $existingProgress = $this->bulkTransferRequestsManager->getByUser($user);
            
            // Delete the record after sending notification
            //$this->bulkTransferRequestsManager->delete($user);
            
            if ($existingProgress) {
                // Send cancellation notification with current progress
                $this->sendCancellationNotification(
                    $existingProgress->getQueueIds() ?: [],
                    $existingProgress->getCompletedIds() ?: [],
                    $existingProgress->getStoreFilter() ?: 0,
                    $user
                );
            }
            $result = [
                'success' => true,
            ];
        } catch (\Exception $e) {
            $message = $e->getMessage();
            if (!$message) {
                $message = __(
                    'A system error has occurred. Please try again. If the issue persists,'
                    . ' please contact our support team at support@writetext.ai.'
                );
            }
            
            $result = [
                'success' => false,
                'message' => $message
            ];
        }

        $response->setData($result);

        return $response;
    }
    
    /**
     * Send cancellation notification
     *
     * @param array $queueIds
     * @param array $completedIds
     * @param int $storeFilter
     * @param string $userName
     * @return void
     */
    private function sendCancellationNotification(
        array $queueIds,
        array $completedIds,
        int $storeFilter,
        string $userName
    ): void {
        try {
            $language = $this->storeHelper->getFormattedLanguage($storeFilter);
            $allIds = array_merge($queueIds, $completedIds);
            $total = count($allIds);
            $completed = count($completedIds);
            
            // Generate a unique transfer ID for cancellation
            $transferId = 'cancel_' . count($allIds) . '_' . time();
            
            $notificationData = [
                'type' => "8",
                'subType' => 'transfer',
                'id' => $transferId,
                'userName' => $userName,
                'recordType' => 'Product',
                'storeId' => (string) $storeFilter,
                'status' => 'Cancelled',
                'startTime' => $this->dateTime->gmtDate(),
                'endTime' => $this->dateTime->gmtDate(),
                'queuedIds' => [], //array_values($queueIds), // Ensure proper array format
                'runningIds' => [],
                'completedIds' => array_values($completedIds), // Ensure proper array format
                'failedIds' => [],
                'completed' => $completed,
                'failed' => 0,
                'total' => $total,
                'language' => $language,
                'metaData' => []
            ];
            
            // Send notification with single retry
            try {
                $this->apiManager->sendCustomNotification($notificationData);
            } catch (\Exception $retryException) {
                // Single retry attempt
                $this->apiManager->sendCustomNotification($notificationData);
            }
        } catch (\Exception $e) {
            // Log error but don't fail the cancellation
            error_log('Failed to send cancellation notification: ' . $e->getMessage());
        }
    }
}
