<?php

namespace Autogedal\Extend\Controller\Compatibility;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\CategoryRepository;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Catalog\Helper\Image as ImageHelper;

class Products extends Action implements HttpGetActionInterface
{
    const CATEGORY_ID = 2161;

    /**
     * @var JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * @var ProductCollectionFactory
     */
    protected $productCollectionFactory;

    /**
     * @var Visibility
     */
    protected $visibility;

    /**
     * @var CategoryRepository
     */
    protected $categoryRepository;

    /**
     * @var \Autogedal\Extend\Helper\ProductLabelsConfig
     */
    protected $productLabelsConfig;

    /**
     * @var ResourceConnection
     */
    protected $resourceConnection;

    /**
     * @var ImageHelper
     */
    protected $imageHelper;

    /**
     * @param Context $context
     * @param JsonFactory $resultJsonFactory
     * @param ProductCollectionFactory $productCollectionFactory
     * @param Visibility $visibility
     * @param CategoryRepository $categoryRepository
     * @param \Autogedal\Extend\Helper\ProductLabelsConfig $productLabelsConfig
     * @param ResourceConnection $resourceConnection
     * @param ImageHelper $imageHelper
     */
    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory,
        ProductCollectionFactory $productCollectionFactory,
        Visibility $visibility,
        CategoryRepository $categoryRepository,
        \Autogedal\Extend\Helper\ProductLabelsConfig $productLabelsConfig,
        ResourceConnection $resourceConnection,
        ImageHelper $imageHelper
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->productCollectionFactory = $productCollectionFactory;
        $this->visibility = $visibility;
        $this->categoryRepository = $categoryRepository;
        $this->productLabelsConfig = $productLabelsConfig;
        $this->resourceConnection = $resourceConnection;
        $this->imageHelper = $imageHelper;
        parent::__construct($context);
    }

    /**
     * Execute action
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultJsonFactory->create();

        try {
            $marca = $this->getRequest()->getParam('marca');
            $model = $this->getRequest()->getParam('model');
            $caroserie = $this->getRequest()->getParam('caroserie');
            $tpPlafon = $this->getRequest()->getParam('tp_plafon');
            $year = $this->getRequest()->getParam('year');

            if (!$marca || !$model || !$caroserie || !$tpPlafon || !$year) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Please select all filters'),
                    'products' => []
                ]);
            }

            $category = $this->categoryRepository->get(self::CATEGORY_ID);

            $collection = $this->productCollectionFactory->create();
            $collection->addAttributeToSelect(['name', 'price', 'special_price', 'special_from_date', 'special_to_date', 'created_at', 'small_image', 'auto_brand', 'auto_model', 'auto_body_bare', 'auto_roof_type_bare', 'auto_from_to_bare', 'auto_material_bare', 'auto_supported_weight_bare'])
                ->addCategoryFilter($category)
                ->addMinimalPrice()
                ->addFinalPrice()
                ->addTaxPercents()
                ->joinField(
                    'stock_qty',
                    'cataloginventory_stock_item',
                    'qty',
                    'product_id=entity_id',
                    '{{table}}.stock_id=1',
                    'left'
                )
                ->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
                ->addAttributeToFilter('auto_brand', ['eq' => $marca])
                ->addAttributeToFilter('auto_model', ['eq' => $model])
                ->addAttributeToFilter('auto_body_bare', ['eq' => $caroserie])
                ->addAttributeToFilter('auto_roof_type_bare', ['eq' => $tpPlafon])
                ->addAttributeToFilter('auto_from_to_bare', ['eq' => $year])
                ->addAttributeToFilter('visibility', ['in' => [
                    Visibility::VISIBILITY_IN_CATALOG,
                    Visibility::VISIBILITY_IN_SEARCH,
                    Visibility::VISIBILITY_BOTH
                ]]);

            $products = [];
            foreach ($collection as $product) {
                if ($product->getTypeId() == 'bundle') {
                    $priceInfo = $product->getPriceInfo();
                    $salePrice = $priceInfo->getPrice('final_price')->getMaximalPrice()->getValue();
                } else {
                    $salePrice = $product->getFinalPrice();
                }

                $supportedWeight = $this->getAttributeValue($product, 'auto_supported_weight_bare');
                if ($supportedWeight && strpos($supportedWeight, 'kg') === false) {
                    $supportedWeight .= ' kg';
                }

                if ($product->getTypeId() == 'bundle') {
                    $regularPrice = $product->getPriceInfo()->getPrice('regular_price')->getMaximalPrice()->getValue();
                } else {
                    $regularPrice = $product->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue();
                }
                $discountPercent = ($regularPrice > 0 && $regularPrice > $salePrice)
                    ? round((($regularPrice - $salePrice) / $regularPrice) * 100)
                    : 0;

                $products[] = [
                    'id' => $product->getId(),
                    'name' => $product->getName(),
                    'image' => $this->imageHelper->init($product, 'category_page_grid')->getUrl(),
                    'price' => $salePrice,
                    'regular_price' => $regularPrice,
                    'discount_percent' => $discountPercent,
                    'auto_roof_type_bare' => $this->getAttributeValue($product, 'auto_roof_type_bare'),
                    'auto_material_bare' => $this->getAttributeValue($product, 'auto_material_bare'),
                    'auto_supported_weight_bare' => $supportedWeight,
                    'url' => $product->getProductUrl(),
                    'is_new' => $this->isProductNew($product),
                    'is_on_sale' => $this->isOnSale($product),
                    'is_super_deal' => $this->isSuperDeal($product),
                    'is_limited_stock' => $this->isLimitedStock($product),
                    'is_bestseller' => $this->isBestseller($product)
                ];
            }

            // Sort products by price ascending (lowest to highest)
            usort($products, function($a, $b) {
                return $a['price'] <=> $b['price'];
            });

            return $result->setData([
                'success' => true,
                'products' => $products,
                'count' => count($products)
            ]);

        } catch (\Exception $e) {
            return $result->setData([
                'success' => false,
                'message' => $e->getMessage(),
                'products' => []
            ]);
        }
    }

    /**
     * Check if product is new based on created_at date
     *
     * @param \Magento\Catalog\Model\Product $product
     * @return bool
     */
    protected function isProductNew($product)
    {
        try {
            $createdAt = $product->getCreatedAt();
            if (!$createdAt) {
                return false;
            }

            $newProductDays = $this->productLabelsConfig->getNewProductDays();
            if (!$newProductDays) {
                return false;
            }

            $productDate = new \DateTime($createdAt);
            $currentDate = new \DateTime();
            $interval = $currentDate->diff($productDate);
            $daysDiff = $interval->days;

            return $daysDiff <= $newProductDays;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Check if product is on sale (has special price)
     *
     * @param \Magento\Catalog\Model\Product $product
     * @return bool
     */
    protected function isOnSale($product)
    {
        try {
            if ($product->getTypeId() == 'bundle') {
                $priceInfo = $product->getPriceInfo();
                $regularPrice = $priceInfo->getPrice('regular_price')->getAmount()->getValue();
                $finalPrice = $priceInfo->getPrice('final_price')->getAmount()->getValue();

                return $finalPrice < $regularPrice;
            } else {
                $specialPrice = $product->getSpecialPrice();
                $regularPrice = $product->getPrice();

                if (!$specialPrice) {
                    return false;
                }

                $now = new \DateTime();
                $specialFromDate = $product->getSpecialFromDate();
                $specialToDate = $product->getSpecialToDate();

                if ($specialFromDate && new \DateTime($specialFromDate) > $now) {
                    return false;
                }

                if ($specialToDate && new \DateTime($specialToDate) < $now) {
                    return false;
                }

                return $specialPrice < $regularPrice;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Check if product qualifies as Super Deal (discount > X%)
     *
     * @param \Magento\Catalog\Model\Product $product
     * @return bool
     */
    protected function isSuperDeal($product)
    {
        try {
            $superDealPercentage = $this->productLabelsConfig->getSuperDealPercentage();
            if (!$superDealPercentage) {
                return false;
            }

            $regularPrice = 0;
            $finalPrice = 0;

            if ($product->getTypeId() == 'bundle') {
                $priceInfo = $product->getPriceInfo();
                $regularPrice = $priceInfo->getPrice('regular_price')->getAmount()->getValue();
                $finalPrice = $priceInfo->getPrice('final_price')->getAmount()->getValue();
            } else {
                $regularPrice = $product->getPrice();
                $specialPrice = $product->getSpecialPrice();

                if (!$specialPrice) {
                    return false;
                }

                $now = new \DateTime();
                $specialFromDate = $product->getSpecialFromDate();
                $specialToDate = $product->getSpecialToDate();

                if ($specialFromDate && new \DateTime($specialFromDate) > $now) {
                    return false;
                }

                if ($specialToDate && new \DateTime($specialToDate) < $now) {
                    return false;
                }

                $finalPrice = $specialPrice;
            }

            if ($regularPrice <= 0 || $finalPrice >= $regularPrice) {
                return false;
            }

            $discountPercentage = (($regularPrice - $finalPrice) / $regularPrice) * 100;

            return $discountPercentage >= $superDealPercentage;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Check if product has limited stock
     *
     * @param \Magento\Catalog\Model\Product $product
     * @return bool
     */
    protected function isLimitedStock($product)
    {
        try {
            $limitedStockThreshold = $this->productLabelsConfig->getLimitedStockThreshold();
            if (!$limitedStockThreshold) {
                return false;
            }

            $stockQty = $this->getProductStockQty($product);

            if ($stockQty === null) {
                return false;
            }

            return $stockQty > 0 && $stockQty <= $limitedStockThreshold;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Get product stock quantity (handles bundle products)
     *
     * @param \Magento\Catalog\Model\Product $product
     * @return float|null
     */
    protected function getProductStockQty($product)
    {
        if ($product->getTypeId() !== 'bundle') {
            return $product->getData('stock_qty');
        }

        // For bundle products, get minimum stock from child products via SQL
        try {
            $connection = $this->resourceConnection->getConnection();
            $bundleSelectionTable = $this->resourceConnection->getTableName('catalog_product_bundle_selection');
            $stockItemTable = $this->resourceConnection->getTableName('cataloginventory_stock_item');

            $select = $connection->select()
                ->from(
                    ['bs' => $bundleSelectionTable],
                    []
                )
                ->join(
                    ['si' => $stockItemTable],
                    'bs.product_id = si.product_id AND si.stock_id = 1',
                    ['min_qty' => 'MIN(si.qty)']
                )
                ->where('bs.parent_product_id = ?', $product->getId());

            $minQty = $connection->fetchOne($select);

            if ($minQty !== false && $minQty !== null) {
                return (float) $minQty;
            }

            return $product->getData('stock_qty');
        } catch (\Exception $e) {
            return $product->getData('stock_qty');
        }
    }

    /**
     * Check if product is a bestseller based on sales in last X months
     *
     * @param \Magento\Catalog\Model\Product $product
     * @return bool
     */
    protected function isBestseller($product)
    {
        try {
            $bestsellerMonths = $this->productLabelsConfig->getBestsellerMonths();
            $bestsellerMinQty = $this->productLabelsConfig->getBestsellerMinQty();

            if (!$bestsellerMonths || !$bestsellerMinQty) {
                return false;
            }

            $fromDate = new \DateTime();
            $fromDate->modify('-' . $bestsellerMonths . ' months');
            $fromDateStr = $fromDate->format('Y-m-01');

            $connection = $this->resourceConnection->getConnection();
            $tableName = $this->resourceConnection->getTableName('sales_bestsellers_aggregated_monthly');

            $select = $connection->select()
                ->from($tableName, ['total_qty' => 'SUM(qty_ordered)'])
                ->where('product_id = ?', $product->getId())
                ->where('period >= ?', $fromDateStr);

            $totalQty = $connection->fetchOne($select);

            if ($totalQty === false || $totalQty === null) {
                return false;
            }

            return (float)$totalQty >= $bestsellerMinQty;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Get attribute value safely
     *
     * @param \Magento\Catalog\Model\Product $product
     * @param string $attributeCode
     * @return string|null
     */
    protected function getAttributeValue($product, $attributeCode)
    {
        try {
            $value = $product->getAttributeText($attributeCode);
            if (!$value) {
                $value = $product->getData($attributeCode);
            }
            return $value ?: null;
        } catch (\Exception $e) {
            return null;
        }
    }
}
