<?php
/**
 * Copyright © Autogedal. All rights reserved.
 */

namespace Autogedal\AjaxcartCustom\Controller\Cart;

use Exception;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Checkout\Controller\Cart\Add;
use Magento\Checkout\Model\Cart as CustomerCart;
use Magento\Checkout\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Framework\Registry;
use Magento\Store\Model\StoreManagerInterface;
use Tigren\Ajaxcart\Helper\Data as AjaxCartData;
use Zend_Filter_LocalizedToNormalized;

/**
 * Class ShowPopup - Fixed version that properly handles AJAX responses for simple products
 * @package Autogedal\AjaxcartCustom\Controller\Cart
 */
class ShowPopup extends Add
{
    /**
     * Core registry
     *
     * @var Registry
     */
    protected $_coreRegistry = null;

    /**
     * @var AjaxCartData Cart Data
     */
    protected $_ajaxCartData;

    /**
     * @param Context $context
     * @param ScopeConfigInterface $scopeConfig
     * @param Session $checkoutSession
     * @param StoreManagerInterface $storeManager
     * @param Validator $formKeyValidator
     * @param CustomerCart $cart
     * @param ProductRepositoryInterface $productRepository
     * @param Registry $registry
     * @param AjaxCartData $ajaxcartData
     * @codeCoverageIgnore
     */
    public function __construct(
        Context $context,
        ScopeConfigInterface $scopeConfig,
        Session $checkoutSession,
        StoreManagerInterface $storeManager,
        Validator $formKeyValidator,
        CustomerCart $cart,
        ProductRepositoryInterface $productRepository,
        Registry $registry,
        AjaxCartData $ajaxcartData
    ) {
        parent::__construct(
            $context,
            $scopeConfig,
            $checkoutSession,
            $storeManager,
            $formKeyValidator,
            $cart,
            $productRepository
        );
        $this->_ajaxCartData = $ajaxcartData;
        $this->_coreRegistry = $registry;
    }

    /**
     * Add product to shopping cart action
     *
     * @return ResponseInterface|Redirect|ResultInterface
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    public function execute()
    {
        if (!$this->_formKeyValidator->validate($this->getRequest())) {
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }

        $params = $this->getRequest()->getParams();
        
        // Debug logging
        $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/ajaxcart_debug.log');
        $logger = new \Zend_Log();
        $logger->addWriter($writer);
        $logger->info('AJAX Cart Request Params: ' . json_encode($params));

        try {
            if (isset($params['qty'])) {
                $filter = new Zend_Filter_LocalizedToNormalized(
                    [
                        'locale' => $this->_objectManager->get(
                            ResolverInterface::class
                        )->getLocale()
                    ]
                );
                $params['qty'] = $filter->filter($params['qty']);
            }

            $product = $this->_initProduct();

            /**
             * Check product availability
             */
            if (!$product) {
                return $this->goBack();
            }

            if (!empty($params['ajaxcart_error'])) {
                $this->_coreRegistry->register('product', $product);
                $this->_coreRegistry->register('current_product', $product);

                $htmlPopup = $this->_ajaxCartData->getErrorHtml($product);
                $result['error'] = true;
                $result['html_popup'] = $htmlPopup;

                return $this->getResponse()->representJson(
                    $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result)
                );
            }

            if (!empty($params['ajaxcart_success'])) {
                $this->_coreRegistry->register('product', $product);
                $this->_coreRegistry->register('current_product', $product);

                $htmlPopup = $this->_ajaxCartData->getSuccessHtml($product);
                $result['success'] = true;
                $result['html_popup'] = $htmlPopup;

                return $this->getResponse()->representJson(
                    $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result)
                );
            }

            $isEmptySuperAttribute = false;
            if (empty($params['super_attribute'])) {
                $isEmptySuperAttribute = true;
            } elseif ($product->getTypeId() === 'configurable') {
                foreach ($params['super_attribute'] as $superAttributeValue) {
                    if (!$superAttributeValue) {
                        $isEmptySuperAttribute = true;
                        break;
                    }
                }
            }

            $isEmptySuperGroup = false;
            if (empty($params['super_group'])) {
                $isEmptySuperGroup = true;
            } elseif ($product->getTypeId() === 'grouped') {
                foreach ($params['super_group'] as $superGroupValue) {
                    if (!$superGroupValue) {
                        $isEmptySuperGroup = true;
                        break;
                    }
                }
            }

            /* return options popup content when product type is grouped */
            if ($product->getHasOptions()
                || ($product->getTypeId() === 'grouped' && $isEmptySuperGroup)
                || ($product->getTypeId() === 'configurable' && $isEmptySuperAttribute)
                || $product->getTypeId() === 'bundle'
                || $product->getTypeId() === 'downloadable'
            ) {
                $this->_coreRegistry->register('product', $product);
                $this->_coreRegistry->register('current_product', $product);

                $htmlPopup = $this->_ajaxCartData->getOptionsPopupHtml($product);
                $result['success'] = true;
                $result['html_popup'] = $htmlPopup;

                if ($product->getTypeId() === 'configurable') {
                    $count = 0;
                    foreach ($params['super_attribute'] as $param) {
                        if ($param) {
                            $count++;
                        }
                    }
                    $configurableAttributes = $product->getTypeInstance()->getConfigurableAttributes($product);
                    if ($count === $configurableAttributes->getSize()) {
                        // Add to cart and return success response for AJAX
                        $addToCartResult = $this->addToCartAndGetResult($params, $product);
                        if ($addToCartResult) {
                            return $addToCartResult;
                        }
                    } else {
                        return $this->getResponse()->representJson(
                            $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result)
                        );
                    }
                } else {
                    return $this->getResponse()->representJson(
                        $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result)
                    );
                }
            } else {
                // FIXED: For simple products, add to cart and return proper AJAX response
                $logger->info('Simple product detected, adding to cart...');
                $addToCartResult = $this->addToCartAndGetResult($params, $product);
                if ($addToCartResult) {
                    return $addToCartResult;
                }
            }
        } catch (LocalizedException $e) {
            if ($this->_checkoutSession->getUseNotice(true)) {
                $this->messageManager->addNotice(
                    $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($e->getMessage())
                );
            } else {
                $messages = array_unique(explode("\n", $e->getMessage()));
                foreach ($messages as $message) {
                    $this->messageManager->addError(
                        $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($message)
                    );
                }
            }

            $url = $this->_checkoutSession->getRedirectUrl(true);

            if (!$url) {
                $cartUrl = $this->_objectManager->get('Magento\Checkout\Helper\Cart')->getCartUrl();
                $url = $this->_redirect->getRedirectUrl($cartUrl);
            }

            return $this->goBack($url);
        } catch (Exception $e) {
            $this->messageManager->addException($e, __('We can\'t add this item to your shopping cart right now.'));
            $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
            return $this->goBack();
        }

        return $this->goBack();
    }

    /**
     * Add product to cart and return proper AJAX response using Tigren's success popup
     *
     * @param array $params
     * @param \Magento\Catalog\Model\Product $product
     * @return ResponseInterface|null
     */
    private function addToCartAndGetResult($params, $product)
    {
        // Debug logging
        $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/ajaxcart_debug.log');
        $logger = new \Zend_Log();
        $logger->addWriter($writer);
        $logger->info('addToCartAndGetResult called with product ID: ' . $product->getId());
        
        try {
            // Try to add the product to cart
            $this->cart->addProduct($product, $params);
            $this->cart->save();
            $logger->info('Product added to cart successfully');

            // Register product for template rendering (CRITICAL for popup content)
            if (!$this->_coreRegistry->registry('product')) {
                $this->_coreRegistry->register('product', $product);
            }
            if (!$this->_coreRegistry->registry('current_product')) {
                $this->_coreRegistry->register('current_product', $product);
            }

            // Use Tigren's success HTML generation for full popup content
            $htmlPopup = $this->_ajaxCartData->getSuccessHtml($product);
            $logger->info('Generated HTML popup length: ' . strlen($htmlPopup));
            
            $result = [
                'success' => true,
                'addto' => true, // This flag tells the frontend it's a successful add-to-cart
                'html_popup' => $htmlPopup, // Full popup HTML with all content
                'product' => [
                    'statusText' => __('Product successfully added to cart.')
                ]
            ];

            // Get minicart HTML for cart update
            try {
                $minicartBlock = $this->_objectManager->get('Magento\Checkout\Block\Cart\Sidebar');
                if ($minicartBlock) {
                    $result['minicart'] = $minicartBlock->toHtml();
                }
            } catch (Exception $e) {
                // If minicart fails, continue without it
                $result['minicart'] = '';
            }

            $jsonResult = $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result);
            $logger->info('Returning JSON result length: ' . strlen($jsonResult));
            $logger->info('First 500 chars of result: ' . substr($jsonResult, 0, 500));
            
            return $this->getResponse()->representJson($jsonResult);

        } catch (LocalizedException $e) {
            // Register product for error template
            if (!$this->_coreRegistry->registry('product')) {
                $this->_coreRegistry->register('product', $product);
            }
            if (!$this->_coreRegistry->registry('current_product')) {
                $this->_coreRegistry->register('current_product', $product);
            }

            // Use Tigren's error popup
            $htmlPopup = $this->_ajaxCartData->getErrorHtml($product);
            
            $result = [
                'error' => true,
                'html_popup' => $htmlPopup,
                'message' => $e->getMessage()
            ];

            return $this->getResponse()->representJson(
                $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result)
            );
        } catch (Exception $e) {
            $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
            
            // Register product for error template
            if (!$this->_coreRegistry->registry('product')) {
                $this->_coreRegistry->register('product', $product);
            }
            if (!$this->_coreRegistry->registry('current_product')) {
                $this->_coreRegistry->register('current_product', $product);
            }

            // Use Tigren's error popup
            $htmlPopup = $this->_ajaxCartData->getErrorHtml($product);
            
            $result = [
                'error' => true,
                'html_popup' => $htmlPopup,
                'message' => __('We can\'t add this item to your shopping cart right now.')
            ];

            return $this->getResponse()->representJson(
                $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result)
            );
        }
    }
}