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

namespace WriteTextAI\WriteTextAI\Model;

use WriteTextAI\WriteTextAI\Model\BulkTransferRequestsFactory;
use WriteTextAI\WriteTextAI\Api\BulkTransferRequestsRepositoryInterface;
use Magento\Framework\Stdlib\DateTime\DateTime;

class BulkTransferRequestsManager
{
    /**
     * @var BulkTransferRequestsFactory
     */
    protected $BulkTransferRequestsFactory;

    /**
     * @var BulkTransferRequestsRepositoryInterface
     */
    protected $BulkTransferRequestsRepository;

    /**
     * @var DateTime
     */
    protected $dateTime;

    /**
     * Constructor
     *
     * @param BulkTransferRequestsFactory $BulkTransferRequestsFactory
     * @param BulkTransferRequestsRepositoryInterface $BulkTransferRequestsRepository
     * @param DateTime $dateTime
     */
    public function __construct(
        BulkTransferRequestsFactory $BulkTransferRequestsFactory,
        BulkTransferRequestsRepositoryInterface $BulkTransferRequestsRepository,
        DateTime $dateTime
    ) {
        $this->BulkTransferRequestsFactory = $BulkTransferRequestsFactory;
        $this->BulkTransferRequestsRepository = $BulkTransferRequestsRepository;
        $this->dateTime = $dateTime;
    }

    /**
     * Save bulk request
     *
     * @param string $user
     * @param array $stores
     * @param string $storeFilter
     * @param array $fields
     * @param array $queueIds
     * @param array $completedIds
     * @param array $successIds
     * @param array $errorIds
     * @param array $skippedIds
     * @return int
     */
    public function saveBulkRequest(
        $user,
        $stores,
        $storeFilter,
        $fields,
        $queueIds = [],
        $completedIds = [],
        $successIds = [],
        $errorIds = [],
        $skippedIds = []
    ) {
        $queueIds = !empty($queueIds) ? implode(',', (array) $queueIds) : '';
        $completedIds = !empty($completedIds) ? implode(',', (array) $completedIds) : '';
        $successIds = !empty($successIds) ? implode(',', (array) $successIds) : '';
        $errorIds = !empty($errorIds) ? implode(',', (array) $errorIds) : '';
        $skippedIds = !empty($skippedIds) ? implode(',', (array) $skippedIds) : '';
        $stores = implode(',', (array) $stores);
        $fields = implode(',', (array) $fields);
        //set started at to current time in utc
        $startedAt = $this->dateTime->gmtDate();

        $BulkTransferRequests = $this->BulkTransferRequestsFactory->create();

        $existing = $BulkTransferRequests->getCollection()
            ->addFieldToFilter('user', $user)
            ->getFirstItem();

        if ($existing->getId()) {
            // Update the existing record
            $existing->setUser($user);
            $existing->setQueueIds($queueIds);
            $existing->setCompletedIds($completedIds);
            $existing->setSuccessIds($successIds);
            $existing->setErrorIds($errorIds);
            $existing->setSkippedIds($skippedIds);
            $existing->setStoresSelected($stores);
            $existing->setStoreFilter($storeFilter);
            $existing->setFieldsSelected($fields);
            $BulkTransferRequests = $existing;
        } else {
            // Record not found, create a new one
            $BulkTransferRequests->setData([
                "user" => $user,
                "queue_ids" => $queueIds,
                "completed_ids" => $completedIds,
                "success_ids" => $successIds,
                "error_ids" => $errorIds,
                "skipped_ids" => $skippedIds,
                "stores_selected" => $stores,
                "store_filter" => $storeFilter,
                "fields_selected" => $fields,
                "started_at" => $startedAt
            ]);
        }

        $savedData = $this->BulkTransferRequestsRepository->save($BulkTransferRequests);
        $id =  $savedData->getId();
        unset($BulkTransferRequests);
        unset($savedData);
        return $id;
    }

    /**
     * Create bulk request
     */
    public function createBulkRequest()
    {
        $BulkTransferRequests = $this->BulkTransferRequestsFactory->create();
        return $BulkTransferRequests;
    }

    /**
     * Save bulk request
     *
     * @param \WriteTextAI\WriteTextAI\Model\BulkTransferRequests $existing
     * @param string $user
     * @param array $stores
     * @param string $storeFilter
     * @param array $fields
     * @param array $queueIds
     * @param array $completedIds
     * @param array $successIds
     * @param array $errorIds
     * @param array $skippedIds
     * @return int
     */
    public function saveBulkRequestWithRequest(
        $existing,
        $user,
        $stores,
        $storeFilter,
        $fields,
        $queueIds = [],
        $completedIds = [],
        $successIds = [],
        $errorIds = [],
        $skippedIds = []
    ) {
        $queueIds = !empty($queueIds) ? implode(',', (array) $queueIds) : '';
        $completedIds = !empty($completedIds) ? implode(',', (array) $completedIds) : '';
        $successIds = !empty($successIds) ? implode(',', (array) $successIds) : '';
        $errorIds = !empty($errorIds) ? implode(',', (array) $errorIds) : '';
        $skippedIds = !empty($skippedIds) ? implode(',', (array) $skippedIds) : '';
        $stores = implode(',', (array) $stores);
        $fields = implode(',', (array) $fields);
        $startedAt = $this->dateTime->gmtDate();

        if ($existing->getId()) {
            // Update the existing record
            $existing->setUser($user);
            $existing->setQueueIds($queueIds);
            $existing->setCompletedIds($completedIds);
            $existing->setSuccessIds($successIds);
            $existing->setErrorIds($errorIds);
            $existing->setSkippedIds($skippedIds);
            $existing->setStoresSelected($stores);
            $existing->setStoreFilter($storeFilter);
            $existing->setFieldsSelected($fields);
            $BulkTransferRequests = $existing;
        } else {
            $BulkTransferRequests = $this->BulkTransferRequestsFactory->create();
            // Record not found, create a new one
            $BulkTransferRequests->setData([
                "user" => $user,
                "queue_ids" => $queueIds,
                "completed_ids" => $completedIds,
                "success_ids" => $successIds,
                "error_ids" => $errorIds,
                "skipped_ids" => $skippedIds,
                "stores_selected" => $stores,
                "store_filter" => $storeFilter,
                "fields_selected" => $fields,
                "started_at" => $startedAt
            ]);
        }

        $savedData = $this->BulkTransferRequestsRepository->save($BulkTransferRequests);
        $id =  $savedData->getId();
        unset($BulkTransferRequests);
        unset($savedData);
        return $id;
    }

    /**
     * Delete bulk request
     *
     * @param string $user
     * @return void
     */
    public function delete($user)
    {
        $BulkTransferRequests = $this->BulkTransferRequestsFactory->create();

        $existing = $BulkTransferRequests->getCollection()
            ->addFieldToFilter('user', $user)
            ->getFirstItem();

        if ($existing->getId()) {
            $this->BulkTransferRequestsRepository->delete($existing);
        }
    }

    /**
     * Cancel bulk request
     *
     * @param string $user
     * @return void
     */
    public function cancel($user)
    {
        $BulkTransferRequests = $this->BulkTransferRequestsFactory->create();

        $existing = $BulkTransferRequests->getCollection()
            ->addFieldToFilter('user', $user)
            ->getFirstItem();

        if ($existing->getId()) {
            $existing->setIsCancelled(1);
            $this->BulkTransferRequestsRepository->save($existing);
        }
    }

    /**
     * Delete all bulk requests
     *
     * @return void
     */
    public function deleteAll()
    {
        $BulkTransferRequests = $this->BulkTransferRequestsFactory->create();
        $BulkTransferRequests->getCollection()->walk('delete');
    }

    /**
     * Update request
     *
     * @param \WriteTextAI\WriteTextAI\Model\BulkTransferRequests $bulkRequest
     */
    public function update($bulkRequest)
    {
        if ($bulkRequest->getId()) {
            $this->BulkTransferRequestsRepository->save($bulkRequest);
        }
    }

    /**
     * Get bulk request by user
     *
     * @param string $user
     * @return \WriteTextAI\WriteTextAI\Model\BulkTransferRequests|null
     */
    public function getByUser($user)
    {
        $BulkTransferRequests = $this->BulkTransferRequestsFactory->create();

        $existing = $BulkTransferRequests->getCollection()
            ->addFieldToFilter('user', $user)
            ->getFirstItem();

        if ($existing->getId()) {
            // Convert comma-separated strings to arrays
            $queueIds = $existing->getQueueIds() ?
                explode(',', (string) $existing->getQueueIds()) : [];
            $completedIds = $existing->getCompletedIds() ?
                explode(',', (string) $existing->getCompletedIds()) : [];
            $successIds = $existing->getSuccessIds() ?
                explode(',', (string) $existing->getSuccessIds()) : [];
            $errorIds = $existing->getErrorIds() ?
                explode(',', (string) $existing->getErrorIds()) : [];
            $skippedIds = $existing->getSkippedIds() ?
                explode(',', (string) $existing->getSkippedIds()) : [];
            
            // Set arrays for easier access
            $existing->setQueueIds($queueIds);
            $existing->setCompletedIds($completedIds);
            $existing->setSuccessIds($successIds);
            $existing->setErrorIds($errorIds);
            $existing->setSkippedIds($skippedIds);
            
            return $existing;
        }

        return null;
    }

    /**
     * Get bulk requests
     *
     * @return bool
     */
    public function getBulkRequests()
    {
        $BulkTransferRequests = $this->BulkTransferRequestsFactory->create();
        $BulkTransferRequests = $BulkTransferRequests->getCollection();

        $requests = [];
        foreach ($BulkTransferRequests as $BulkTransferRequest) {
            $requests[] = [
                'queue_ids' => $BulkTransferRequest->getQueueIds() ?
                    explode(',', (string) $BulkTransferRequest->getQueueIds()) : [],
                'completed_ids' => $BulkTransferRequest->getCompletedIds() ?
                    explode(',', (string) $BulkTransferRequest->getCompletedIds()) : [],
                'success_ids' => $BulkTransferRequest->getSuccessIds() ?
                    explode(',', (string) $BulkTransferRequest->getSuccessIds()) : [],
                'error_ids' => $BulkTransferRequest->getErrorIds() ?
                    explode(',', (string) $BulkTransferRequest->getErrorIds()) : [],
                'skipped_ids' => $BulkTransferRequest->getSkippedIds() ?
                    explode(',', (string) $BulkTransferRequest->getSkippedIds()) : [],
                'user' => $BulkTransferRequest->getUser(),
                'stores' => explode(',', (string) $BulkTransferRequest->getStoresSelected()),
                'store_filter' => $BulkTransferRequest->getStoreFilter(),
                'fields' => explode(',', (string) $BulkTransferRequest->getFieldsSelected())
            ];
        }

        return $requests;
    }
}
