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

namespace WriteTextAI\WriteTextAI\Model;

use WriteTextAI\WriteTextAI\Model\AiProductFactory;
use WriteTextAI\WriteTextAI\Api\AiProductRepositoryInterface;

class AiProductManager
{
    /**
     * @var AiProductFactory
     */
    protected $aiProductFactory;

    /**
     * @var AiProductRepositoryInterface
     */
    protected $aiProductRepository;

    /**
     * Constructor
     *
     * @param AiProductFactory $aiProductFactory
     * @param AiProductRepositoryInterface $aiProductRepository
     */
    public function __construct(
        AiProductFactory $aiProductFactory,
        AiProductRepositoryInterface $aiProductRepository
    ) {
        $this->aiProductFactory = $aiProductFactory;
        $this->aiProductRepository = $aiProductRepository;
    }

    /**
     * Save date
     *
     * @param int $productId
     * @param int $storeId
     * @param string $type
     *
     * @return void
     */
    public function saveDate($productId, $storeId, $type)
    {
        $currDateTime = (new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT);

        $aiProduct = $this->aiProductFactory->create();

        $existing = $aiProduct->getCollection()
            ->addFieldToFilter('product_id', $productId)
            ->addFieldToFilter('store_id', $storeId)
            ->getFirstItem();

        if ($existing->getId()) {
            switch ($type) {
                case 'generated':
                    $existing->setGeneratedAt($currDateTime);
                    break;
                case 'edited':
                    $existing->setEditedAt($currDateTime);
                    break;
                case 'transferred':
                    $existing->setTransferredAt($currDateTime);
                    break;
                case 'reviewed':
                    $existing->setReviewedAt($currDateTime);
                    break;
            }

            // Update the existing record
            $aiProduct = $existing;
        } else {
            $data = [
                "product_id" => $productId,
                "store_id" => $storeId
            ];

            switch ($type) {
                case 'generated':
                    $data['generated_at'] = $currDateTime;
                    break;
                case 'edited':
                    $data['edited_at'] = $currDateTime;
                    break;
                case 'transferred':
                    $data['transferred_at'] = $currDateTime;
                    break;
                case 'reviewed':
                    $data['reviewed_at'] = $currDateTime;
                    break;
            }

            // Record not found, create a new one
            $aiProduct->setData($data);
        }

        $this->aiProductRepository->save($aiProduct);
    }

    /**
     * Set refresh date
     *
     * @param int $productId
     * @param int $storeId
     * @return void
     */
    public function setRefreshDate($productId, $storeId)
    {
        $aiProduct = $this->aiProductFactory->create();
        $refreshDate = (new \DateTime())->modify('+1 month')
            ->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT);

        $existing = $aiProduct->getCollection()
            ->addFieldToFilter('product_id', $productId)
            ->addFieldToFilter('store_id', $storeId)
            ->getFirstItem();

        if ($existing->getId()) {
            // Update the existing record
            $existing->setRefreshAt($refreshDate);
            $aiProduct = $existing;
        } else {
            // Record not found, create a new one
            $aiProduct->setData([
                "product_id" => $productId,
                "store_id" => $storeId,
                "refresh_at" => $refreshDate
            ]);
        }

        $this->aiProductRepository->save($aiProduct);
    }

    /**
     * Save attributes
     *
     * @param int $productId
     * @param int $storeId
     * @param string $selected
     * @param bool $checked
     * @param string $details
     * @return void
     */
    public function saveAttributesSelected(
        $productId,
        $storeId,
        $selected,
        $checked = null,
        $details = null
    ) {
        $aiProduct = $this->aiProductFactory->create();
        
        $checked = $checked ? 1 : 0;

        $existing = $aiProduct->getCollection()
            ->addFieldToFilter('product_id', $productId)
            ->addFieldToFilter('store_id', $storeId)
            ->getFirstItem();

        if ($existing->getProductsId()) {
            $existing->setProductAttributesSelected($selected);

            if ($checked !== null) {
                $existing->setOtherDetailsChecked($checked);
            }
            if ($details !== null) {
                $existing->setOtherDetails($details);
            }

            // Update the existing record
            $aiProduct = $existing;
        } else {
            // Record not found, create a new one
            $aiProduct->setData([
                "product_id" => $productId,
                "store_id" => $storeId,
                "product_attributes_selected" => $selected,
                "other_details_checked" => $checked,
                "other_details" => $details
            ]);
        }

        $this->aiProductRepository->save($aiProduct);
    }

    /**
     * Get product
     *
     * @param int $productId
     * @param int $storeId
     * @return bool
     */
    public function getProduct($productId, $storeId)
    {
        $aiProduct = $this->aiProductFactory->create();
        $aiProduct = $aiProduct->getCollection()
            ->addFieldToFilter('product_id', $productId)
            ->addFieldToFilter('store_id', $storeId)
            ->getFirstItem();

        return $aiProduct;
    }

    /**
     * Save additional prompt
     *
     * @param int $productId
     * @param int $storeId
     * @param string $additionalPrompt
     * @return void
     */
    public function saveAdditionalPrompt($productId, $storeId, $additionalPrompt)
    {
        $aiProduct = $this->aiProductFactory->create();

        $existing = $aiProduct->getCollection()
            ->addFieldToFilter('product_id', $productId)
            ->addFieldToFilter('store_id', $storeId)
            ->getFirstItem();

        if ($existing->getId()) {
            $existing->setAdditionalPrompt($additionalPrompt);
            $aiProduct = $existing;
        } else {
            $aiProduct->setData([
                "product_id" => $productId,
                "store_id" => $storeId,
                "additional_prompt" => $additionalPrompt
            ]);
        }

        $this->aiProductRepository->save($aiProduct);
    }
}
