<?php

namespace ScfPriceUpdater\Pages\Admin;

use ScfPriceUpdater\Assets;
use ScfPriceUpdater\Options;
use ScfPriceUpdater\Pages\AdminPage;
use WC_Data_Exception;

class UpdaterPage extends AdminPage
{

    private const MENU_SLUG = 'updater';

    public function __construct()
    {
        $this->menuSlug = self::MENU_SLUG;
        parent::__construct('updater');
    }

    /**
     * @throws WC_Data_Exception
     */
    public function init()
    {
        if (isset($_POST['file_separator'])) {
            if (isset($_FILES['price_file'])) {
                if (wp_verify_nonce($_POST['_wpnonce'], 'scf-price-updater')) {
                    if ($_FILES['price_file']['type'] === 'text/csv') {
                        $separator = sanitize_text_field($_POST['file_separator']);
                        $removeEmpty = isset($_POST['delete_empty']);
                        $skipTrash = isset($_POST['skip_trash']);
                        Options::updateOption('separator', $_POST['file_separator']);
                        Options::updateOption('delete_empty', $removeEmpty);
                        Options::updateOption('skip_trash', $skipTrash);

                        $file = fopen($_FILES['price_file']['tmp_name'], 'r');
                        $lineNumber = 0;
                        while ($raw = fgets($file)) {
                            $lineNumber++;
                            $item = str_getcsv($raw, $separator);
                            // Remove empty values and reset index
                            $item = array_values(array_filter($item));
                            // First row contains sku
                            $sku = $item[0] ?? false;
                            $rawPrice = $item[3] ?? false;
                            if ($sku && $rawPrice) {
                                $product_id =  wc_get_product_id_by_sku($sku);
                                if ($product_id) {
                                    $product = wc_get_product($product_id);
                                    $price = (int) $rawPrice;
                                    if ($price > 0) {
                                        if (isset($item[4])) {
                                            if ($removeEmpty) {
                                                if ($skipTrash) {
                                                    wp_delete_post($product_id, true);
                                                } else {
                                                    wp_trash_post($product_id);
                                                }
                                            } else {
                                                if ($product->get_status() === 'private') {
                                                    continue;
                                                }
                                                $product->set_status('private');
                                            }
                                        } else {
                                            if ($price === (int) $product->get_price()) {
                                                continue;
                                            }
                                            $product->set_regular_price($price);
                                            $product->set_price($price);
                                            $product->set_status('publish');
                                        }
                                    } else {
                                        if ($removeEmpty) {
                                            if ($skipTrash) {
                                                wp_delete_post($product_id, true);
                                            } else {
                                                wp_trash_post($product_id);
                                            }
                                        } else {
                                            if ($product->get_status() === 'private') {
                                                continue;
                                            }
                                            $product->set_status('private');
                                        }
                                    }
                                    $product->save();
                                }
                            }
                        }
                        add_action('admin_notices', function () {
                            echo '<div class="notice notice-success is-dismissible">
                            <p><strong>Secoff Price Updater:</strong> Prices have been updated!</p>
                          </div>';
                        });
                    } else {
                        add_action('admin_notices', function () {
                            echo '<div class="notice notice-error is-dismissible">
                            <p><strong>Secoff Price Updater:</strong> File type is not CSV!</p>
                          </div>';
                        });
                    }
                } else {
                    add_action('admin_notices', function () {
                        echo '<div class="notice notice-error is-dismissible">
                            <p><strong>Secoff Price Updater:</strong> Invalid NONCE!</p>
                          </div>';
                    });
                }
            } else {
                add_action('admin_notices', function () {
                    echo '<div class="notice notice-error is-dismissible">
                        <p><strong>Secoff Price Updater:</strong> No Upload file was found!</p>
                      </div>';
                });
            }
        }
    }

    /**
     * @inheritDoc
     */
    public function buildTwigContext(array $context = [])
    {
        return [
            'separator' => Options::getOption('separator'),
            'deleteEmpty' => Options::getOption('delete_empty'),
            'skipTrash' => Options::getOption('skip_trash'),
        ];
    }

    /**
     * @inheritDoc
     */
    public function enqueuePageScripts()
    {
        Assets::enqueueCompiledScript('main');
    }

    public function addAdminMenuItem()
    {
        add_menu_page(
            __('Secoff Price Updater'),
            __('Secoff Price Updater'),
            'administrator',
            self::MENU_SLUG,
            [$this, 'renderPage'],
            'dashicons-money-alt',
            58
        );
    }
}
