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

namespace WriteTextAI\WriteTextAI\Model;

use WriteTextAI\WriteTextAI\Model\AiCategoryFactory;
use WriteTextAI\WriteTextAI\Api\AiCategoryRepositoryInterface;

class AiCategoryManager
{
    /**
     * @var AiCategoryFactory
     */
    protected $aiCategoryFactory;

    /**
     * @var AiCategoryRepositoryInterface
     */
    protected $aiCategoryRepository;

    /**
     * Constructor
     *
     * @param AiCategoryFactory $aiCategoryFactory
     * @param AiCategoryRepositoryInterface $aiCategoryRepository
     */
    public function __construct(
        AiCategoryFactory $aiCategoryFactory,
        AiCategoryRepositoryInterface $aiCategoryRepository
    ) {
        $this->aiCategoryFactory = $aiCategoryFactory;
        $this->aiCategoryRepository = $aiCategoryRepository;
    }

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

        $aiCategory = $this->aiCategoryFactory->create();

        $existing = $aiCategory->getCollection()
            ->addFieldToFilter('category_id', $categoryId)
            ->addFieldToFilter('store_id', $storeId)
            ->getFirstItem();

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

            // Update the existing record
            $aiCategory = $existing;
        } else {
            $data = [
                "category_id" => $categoryId,
                "store_id" => $storeId
            ];

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

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

        $this->aiCategoryRepository->save($aiCategory);
    }

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

        $existing = $aiCategory->getCollection()
            ->addFieldToFilter('category_id', $categoryId)
            ->addFieldToFilter('store_id', $storeId)
            ->getFirstItem();

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

        $this->aiCategoryRepository->save($aiCategory);
    }

    /**
     * Save attributes
     *
     * @param int $categoryId
     * @param int $storeId
     * @param string $selected
     * @param bool $checked
     * @param string $details
     * @return void
     */
    public function saveRepresentativeSelected(
        $categoryId,
        $storeId,
        $selected,
        $checked = null,
        $details = null
    ) {
        $aiCategory = $this->aiCategoryFactory->create();
        
        $checked = filter_var($checked, FILTER_VALIDATE_BOOLEAN) ? 1 : 0;

        $existing = $aiCategory->getCollection()
            ->addFieldToFilter('category_id', $categoryId)
            ->addFieldToFilter('store_id', $storeId)
            ->getFirstItem();

        if ($existing->getCategoriesId()) {
            $existing->setRepresentativeProductsSelected($selected);

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

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

        $this->aiCategoryRepository->save($aiCategory);
    }

    /**
     * Get category
     *
     * @param int $categoryId
     * @param int $storeId
     * @return bool
     */
    public function getCategory($categoryId, $storeId)
    {
        $aiCategory = $this->aiCategoryFactory->create();
        $aiCategory = $aiCategory->getCollection()
            ->addFieldToFilter('category_id', $categoryId)
            ->addFieldToFilter('store_id', $storeId)
            ->getFirstItem();

        return $aiCategory;
    }

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

        $existing = $aiCategory->getCollection()
            ->addFieldToFilter('category_id', $categoryId)
            ->addFieldToFilter('store_id', $storeId)
            ->getFirstItem();

        if ($existing->getId()) {
            $existing->setAdditionalPrompt($additionalPrompt);
            $aiCategory = $existing;
        } else {
            $aiCategory->setData([
                "category_id" => $categoryId,
                "store_id" => $storeId,
                "additional_prompt" => $additionalPrompt
            ]);
        }

        $this->aiCategoryRepository->save($aiCategory);
    }
}
