<?php
namespace Foxstudio\Plugins\Template\Utils;

use Foxstudio\Plugins\Template\Repository as Repository;
use Exception;

class PriceCalculator
{
    private Repository\ProductRepository $productRepository;
    public function __construct()
    {

        $this->productRepository = new Repository\ProductRepository(SERVER_URL);


        
        add_action('woocommerce_init', [$this, 'ensureWooSession']);


        add_action('wp_enqueue_scripts', [$this, 'loadArchiveImages']);


        // Calculator
        add_filter('woocommerce_single_product_summary', [$this, 'calculatorView']);

        add_action('template_redirect',             [$this, 'addToCart']);
        add_action('woocommerce_before_single_product', [$this, 'addToCart']);

        add_action('woocommerce_before_calculate_totals', [$this, 'updatePrice'], 10);
        
        // Show custom data
        add_filter('woocommerce_get_item_data', [$this, 'showCustomData'], 10, 3);
        add_action('woocommerce_checkout_create_order_line_item', [$this, 'wdm_add_custom_order_line_item_meta'], 10, 4);

        // Remove default add to cart 
        remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
        remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);

        // Add custom styles
        \wp_enqueue_style('hidden-add-to-cart', "/wp-content/plugins/pandaGadzety/assets/css/hidden-add-to-cart.css");

    }

    function wdm_add_custom_order_line_item_meta($item, $cart_item_key, $values, $order)
    {
        if (array_key_exists('custom_data', $values)) {
            
            if(!empty($values['custom_data']['option'])) {
                $item->add_meta_data('option', $values['custom_data']['option']);
            }

            if(!empty($values['custom_data']['technology'])) {
                $item->add_meta_data('Technologia', $values['custom_data']['technology']);
            }

            if(!empty($values['custom_data']['labeling_price'])) {
                $item->add_meta_data('Cena znakowania', $values['custom_data']['labeling_price']);
            }

            if(!empty($values['custom_data']['setup_price'])) {
                $item->add_meta_data('Cena przygotowania', $values['custom_data']['setup_price']);
            }

            if(!empty($values['custom_data']['product_price'])) {
                $item->add_meta_data('Cena produktu', $values['custom_data']['product_price']);
            }
            if(!empty($values['custom_data']['colors'])) {
                $item->add_meta_data('Ilość kolorów', $values['custom_data']['colors']);
            }

            if(!empty($values['custom_data']['photo'])) {
                $item->add_meta_data('Zdjęcie nadruku', \wp_get_attachment_image($values['custom_data']['photo'], array(800, 600)));
            }

        }
    }
    
    public function ensureWooSession() {
        if (!wc()->session->has_session()) {
            wc()->session->set_customer_session_cookie(true);
        }
    }

    public function loadArchiveImages() {
        
        $skus = [];
        
            global $wp_query;
            foreach ( $wp_query->posts as $post ) {
                $p = wc_get_product( $post->ID );
                if ( $p && $p->get_sku() ) {
                    $skus[] = $p->get_sku();
                }
            }
        

        
        if ( WC()->cart ) {
            foreach ( WC()->cart->get_cart() as $cart_item ) {
                $p = $cart_item['data'];
                if ( $p && $p->get_sku() ) {
                    $skus[] = $p->get_sku();
                }
            }
        }

        
        $skus = array_unique( $skus );

        
        $productData = [];
        foreach ( $skus as $sku ) {
            try {
                $info = $this->productRepository->getProductInfo( $sku );
                if ( ! empty( $info['message'] ) ) {
                    $productData[ $sku ] = [
                        'img' => $info['message']['productBaseInfo']['primary_img'] ?? null,
                    ];
                }
            } catch ( \Throwable $th ) {}
        }

        
        wp_enqueue_script(
        'archive-images-js',
        plugins_url( '/pandaGadzety/assets/js/archive-images.js' ),
        [ 'wc-cart-fragments' ],
        null,
        true
        );
        wp_localize_script( 'archive-images-js', 'archiveImagesData', [
            'products' => $productData,
        ] );
    }

    public function addToCart() {
        global $post;
        
        if($_SERVER['REQUEST_METHOD'] == 'POST') {

            // $item_data['custom_data']['new_price'] = 99;
            // $item_data['custom_data']['color'] = 'red';
            // $item_data['custom_data']['uuid'] = uniqid();
            
            $product = wc_get_product($post->ID);

            if (!$product) {
                wc_add_notice('Nie znaleziono produktu', 'error');
                return;
            }   

            $itemData = [];
            
            if(!empty($_POST['option'])) {
                $itemData['custom_data']['option'] = $_POST['option'];
            } 

            if(!empty($_POST['technology'])) {
                $itemData['custom_data']['technology'] = $_POST['technology'];
            } 

            if(!empty($_POST['quantity'])) {
                $itemData['custom_data']['quantity'] = $_POST['quantity'];
            } 

            if(!empty($_POST['labeling_price'])) {
                $itemData['custom_data']['labeling_price'] = $_POST['labeling_price'];
            } else {
                $itemData['custom_data']['labeling_price'] = 0;
            }

            if(!empty($_POST['setup_price'])) {
                $itemData['custom_data']['setup_price'] = $_POST['setup_price'];
            } else {
                $itemData['custom_data']['setup_price'] = 0;
            }

            if(!empty($_POST['colors'])) {
                $itemData['custom_data']['colors'] = $_POST['colors'];
            } else {
                $itemData['custom_data']['colors'] = 0;
            }

            if(!empty($_FILES['photo'])) {
                $itemData['custom_data']['photo'] = $this->uploadFile('photo', $product->get_id());
            } else {
                $itemData['custom_data']['photo'] = null;
            }


            $itemData['custom_data']['product_price'] = $_POST['product_price'];

            $itemData['custom_data']['total_price'] = floatval($_POST['product_price']) + floatval($_POST['labeling_price']);

            $attributes = []; 
            if(!empty($_POST['attributes'])) {
                foreach ($_POST['attributes'] as $key => $value) {
                    $attributes['attribute_' . $key] = $value; 
                    wc_add_notice('Błąd podczas dodawania do koszyka', 'error');
                }
            }


            try {
                $cart_item_key = WC()->cart->add_to_cart(
                    $product->get_id(), 
                    $_POST['quantity'], 
                    0, 
                    $attributes, 
                    $itemData
                );

                if ($cart_item_key) {
                    wp_redirect(wc_get_cart_url());
                    exit;
                } else {
                    wc_add_notice('Błąd podczas dodawania do koszyka', 'error');
                }
            } catch (\Throwable $th) {
                wc_add_notice('Wystąpił błąd: ' . $th->getMessage(), 'error');
            }

        }
    }

    public function updatePrice($cart) {
        if (is_admin() && !defined('DOING_AJAX'))
            return;

        if (did_action('woocommerce_before_calculate_totals') >= 2)
            return;

        foreach ($cart->get_cart() as $cart_item) {
            if (isset($cart_item['custom_data']['total_price'])) {
                $setup_price = !empty($cart_item['custom_data']['setup_price']) ? $cart_item['custom_data']['setup_price']: 0; 
                $price = $setup_price / $cart_item['quantity'] + $cart_item['custom_data']['total_price'];
                // TODO: calculate data after price update;
                $cart_item['data']->set_price($price);
            }
        }
    }

    public function showCustomData($item_data, $custom_data) 
    {
        // var_dump($custom_data);
        if(!empty($custom_data['custom_data']['option'])) {
            $item_data[] = [
                'key' => "Pozycja znakowania",
                'value' => wc_clean($custom_data['custom_data']['option']),
            ];
        }
        if(!empty($custom_data['custom_data']['technology'])) {
            $item_data[] = [
                'key' => "Technologia znakowania",
                'value' => wc_clean($custom_data['custom_data']['technology']),
            ];
        }
        // if(!empty($custom_data['custom_data']['quantity'])) {
        //     $item_data[] = [
        //         'key' => "Ilość",
        //         'value' => wc_clean($custom_data['custom_data']['quantity']),
        //     ];
        // }
        if(!empty($custom_data['custom_data']['labeling_price'])) {
            $item_data[] = [
                'key' => "Cena znakowania",
                'value' => wc_clean($custom_data['custom_data']['labeling_price']),
            ];
        }
        if(!empty($custom_data['custom_data']['setup_price'])) {
            $item_data[] = [
                'key' => "Koszt przygotowania",
                'value' => wc_clean($custom_data['custom_data']['setup_price']),
            ];
        }
        
        /*if(!empty($custom_data['custom_data']['product_price'])) {
            $item_data[] = [
                'key' => "Cena produktu",
                'value' => wc_clean($custom_data['custom_data']['product_price']),
            ];
        }*/

        if(!empty($custom_data['custom_data']['photo'])) {
            $attachment_id = $custom_data['custom_data']['photo'];
            
            if (is_numeric($attachment_id)) {
                $image_html = wp_get_attachment_image($attachment_id, array(800, 600));
                $item_data[] = [
                    'key' => "Zdjęcie nadruku",
                    'value' => $image_html,
                ];
            } else {
                $item_data[] = [
                    'key' => "Zdjęcie nadruku",
                    'value' => 'Brak przesłanego pliku',
                ];
            }
        }

        if(!empty($custom_data['custom_data']['color'])) {
            $item_data[] = [
                'key' => "Kolor",
                'value' => wc_clean($custom_data['custom_data']['color']),
            ];
        }

        if(!empty($custom_data['custom_data']['colors'])) {
            $item_data[] = [
                'key' => "Ilość kolorów",
                'value' => wc_clean($custom_data['custom_data']['colors']),
            ];
        }
        // if(!empty($custom_data['custom_data']['total_price'])) {
        //     $item_data[] = [
        //         'key' => "Suma",
        //         'value' => wc_clean($custom_data['custom_data']['total_price']),
        //     ];
        // }
        
        return $item_data;

    }


    public function calculatorView()
    {
        global $product;

        $productInfo = $this->productRepository->getProductInfo($product->get_sku());
        if(!empty($productInfo)) {
            $productInfo = $productInfo['message'];
    
            \wp_enqueue_script("calculatorScript", plugins_url("/pandaGadzety/assets/js/calculator.js"));
            wp_localize_script('calculatorScript', 'calculatorScriptVariables', array(
                'productInfo' => $productInfo
                )
            );
    
            \wp_enqueue_style("calculatorStyle", plugins_url("/pandaGadzety/assets/css/calculator.css"));

            $html = file_get_contents("wp-content/plugins/pandaGadzety/view/calculator.html");
            echo $html;
        }

    }

    /*private function uploadFile($key, $id) {
        // TODO: verify format
        require_once (ABSPATH . 'wp-admin/includes/image.php');
        require_once (ABSPATH . 'wp-admin/includes/file.php');
        require_once (ABSPATH . 'wp-admin/includes/media.php');
        return \media_handle_upload($key, $id);
    }*/


    private function uploadFile($key, $id) {
        require_once (ABSPATH . 'wp-admin/includes/image.php');
        require_once (ABSPATH . 'wp-admin/includes/file.php');
        require_once (ABSPATH . 'wp-admin/includes/media.php');
        
        $attachment_id = media_handle_upload($key, $id);
        
        if (is_wp_error($attachment_id)) {
           // error_log('Błąd przesyłania pliku: ' . $attachment_id->get_error_message());
            
            //wc_add_notice('Błąd przesyłania pliku: ' . $attachment_id->get_error_message(), 'error');
            return null;
        }
        
        return $attachment_id;
    }   

}