<?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') {
                        Options::updateOption('separator', $_POST['file_separator']);

                        $csv = array_map(fn($item) => str_getcsv($item, ';'), file($_FILES['price_file']['tmp_name']));
                        foreach ($csv as $index => $item) {
                            if ($index !== 0) {
                                // First row contains SKU
                                $sku = $item[0];
                                // Third/Fourth row contain price or comment
                                $raw = !empty($item[3]) ? $item[3] : $item[4];
                                $price = !empty($item[3]) ? (int) $item[3] : (int) $item[4];
                                // Check if something is placed on the 3rd/4rd column (price or something else)
                                if (!empty($raw)) {
                                    $product_id =  wc_get_product_id_by_sku($sku);
                                    if ($product_id) {
                                        $product = wc_get_product($product_id);
                                        // If the price is available update it otherwise make product private
                                        if ($price > 0) {
                                            $product->set_regular_price($price);
                                            $product->set_price($price);
                                            $product->set_status('publish');
                                        } else {
                                            $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')
        ];
    }

    /**
     * @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
        );
    }
}
