<?php
namespace TbiBank\FusionPay\Block\Frontend;

// Import necessary classes
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use TbiBank\FusionPay\Helper\Data as FusionPayHelper;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableProductType;

use Magento\Framework\Exception\NoSuchEntityException;

/**
 * Advert Block for FusionPay
 *
 * This block class is designed to handle the advertisement functionalities
 * for FusionPay, including enabling the advert, fetching the advert URL, and
 * retrieving the TBI logo.
 */
class ProductButton extends Template
{
    /**
     * @var FusionPayHelper Helper instance to access FusionPay's functionalities
     */
    protected $fusionPayHelper;
    protected $productRepository;
    protected $configurableProductType;

    /**
     * Constructor
     *
     * @param Context $context Context object with environment data
     * @param FusionPayHelper $fusionPayHelper Helper object for FusionPay functionalities
     * @param array $data Additional data array
     */
    public function __construct(
        Context $context,
        FusionPayHelper $fusionPayHelper,
        ProductRepositoryInterface $productRepository,
        ConfigurableProductType $configurableProductType,
        array $data = []
    ) {
        parent::__construct($context, $data); // Call the parent constructor
        $this->fusionPayHelper = $fusionPayHelper; // Initialize FusionPay helper
        $this->productRepository = $productRepository;
        $this->configurableProductType = $configurableProductType;
    }
    /**
     * Check if the button in product page is enabled
     *
     * @return bool True if product page button is enabled, false otherwise
     */
    public function isEnabled()
    {
        return $this->fusionPayHelper->isProductFeatureEnabled();
    }

    /**
     * Get Loading Image URL
     *
     * @return string
     */
    public function getLoadingImg()
    {
        return $this->fusionPayHelper->getConstValue('TBI_LOADING_SVG');
    }

    /**
     * Get Origin
     *
     * @return string
     */
    public function getOrigin()
    {
        return $this->fusionPayHelper->Encode($this->fusionPayHelper->getConstValue('TBI_PLATFORM_URL'));
    }

    public function getButtonData($price)
    {
        return $this->fusionPayHelper->getData($price);
    }

    public function getLabelData(){
        return $this->fusionPayHelper->getLabelData();
    }

    /**
     * Get logo based on button style
     *
     * @param int $selectedOption
     * @return string
     */
    public function getLogo($selectedOption)
    {
        return $this->fusionPayHelper->getLogo($selectedOption);
    }

    /**
     * Get configuration value
     *
     * @param string $path
     * @return mixed
     */
    public function getConfigValue($path)
    {
        return $this->fusionPayHelper->getConfigValue($path);
    }


    /**
     * Retrieve the appropriate price based on product type and custom options.
     *
     * @return mixed The price data depending on product type, pricing, and custom options.
     */
    // public function getPrice()
    // {
    //     $productId = $this->_request->getParam('id');
    
    //     try {
    //         $product = $this->productRepository->getById($productId);
    //         $currentDate = new \DateTime('now');
    //         $basePrice = $product->getPrice();
    
    //         // Check for special price first
    //         $specialPrice = $product->getSpecialPrice();
    //         $specialFromDate = $product->getSpecialFromDate();
    //         $specialToDate = $product->getSpecialToDate();
    
    //         if ($specialPrice && $currentDate >= new \DateTime($specialFromDate) && (!$specialToDate || $currentDate <= new \DateTime($specialToDate))) {
    //             $basePrice = $specialPrice;
    //         }
    
    //         // Calculate price based on custom options
    //         $optionPrices = [];
    //         $options = $product->getOptions();

    //         foreach ($options as $option) {
    //             if ($option->getPriceType() == 'fixed') {
    //                 $optionPrices[] = $option->getPrice();
    //             } elseif ($option->getPriceType() == 'percent') {
    //                 $optionPrices[] = ($basePrice * $option->getPrice()) / 100;
    //             }
    //         }
    
    //         $finalPrice = $basePrice + array_sum($optionPrices);
            
    //         // Handle different product types
    //         switch ($product->getTypeId()) {
    //             case \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE:
    //                 return ['price' => $finalPrice];
    
    //             case \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE:
    //                 $children = $this->configurableProductType->getChildrenIds($productId);
    //                 $prices = [];
    //                 foreach ($children[0] as $childId) {
    //                     $child = $this->productRepository->getById($childId);
    //                     $prices[] = $child->getPrice();
    //                 }
    //                 return [
    //                     'minPrice' => min($prices) + array_sum($optionPrices),
    //                     'maxPrice' => max($prices) + array_sum($optionPrices)
    //                 ];
    
    //             default:
    //                 // Return final price as fallback
    //                 return ['price' => $finalPrice];
    //         }
    //     } catch (NoSuchEntityException $e) {
    //         return null; // Product not found
    //     }
    // }



    public function getPrice()
    {
        $productId = $this->_request->getParam('id');

        try {
            $product = $this->productRepository->getById($productId);
            $currentDate = new \DateTime('now');
            $basePrice = $product->getFinalPrice(); // Uses Magento's final price logic

            // Check for special price
            $specialPrice = $product->getSpecialPrice();
            $specialFromDate = $product->getSpecialFromDate();
            $specialToDate = $product->getSpecialToDate();

            $fromDateValid = $specialFromDate ? $currentDate >= new \DateTime($specialFromDate) : true;
            $toDateValid = $specialToDate ? $currentDate <= new \DateTime($specialToDate) : true;
            if ($specialPrice && $fromDateValid && $toDateValid) {
                $basePrice = $specialPrice;
            }

            //Get Selected Options Prices
            $optionPrices = 0;
            $selectedOptions = $this->_request->getParam('options', []); // Get selected options

            if (!empty($selectedOptions && is_array($selectedOptions))) {
                foreach ($selectedOptions as $optionId => $optionValue) {
                    $option = $product->getOptionById($optionId);
                    if ($option) {
                        foreach ($option->getValues() as $value) {
                            if ($value->getId() == $optionValue) {
                                if ($value->getPriceType() == 'fixed') {
                                    $optionPrices += $value->getPrice();
                                } elseif ($value->getPriceType() == 'percent') {
                                    $optionPrices += ($basePrice * $value->getPrice()) / 100;
                                }
                            }
                        }
                    }
                }
            }

            $finalPrice = $basePrice + $optionPrices;

            //Handle Configurable Products (Get Selected Child Price)
            if ($product->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
                $childProductId = $this->_request->getParam('selected_child_id'); // Assuming selected child ID is passed
                if ($childProductId) {
                    $childProduct = $this->productRepository->getById($childProductId);
                    $finalPrice = $childProduct->getFinalPrice() + $optionPrices;
                }
            }

            //Return Correct Price Format
            return ['price' => $finalPrice];

        } catch (NoSuchEntityException $e) {
            return null; // Product not found
        }
    }


    
}
