<?php


class Razer_Gold_Pin_Store_Plugin_RGPS
{
    /**
     * Filepath of main plugin file.
     *
     * @var string
     */
    public $file;
    /**
     * Plugin version.
     *
     * @var string
     */
    public $version;
    /**
     * Absolute plugin path.
     *
     * @var string
     */
    public $plugin_path;
    /**
     * Absolute plugin URL.
     *
     * @var string
     */
    public $plugin_url;
    /**
     * assets plugin.
     *
     * @var string
     */
    public $assets;
    /**
     * Absolute path to plugin includes dir.
     *
     * @var string
     */
    public $includes_path;
    /**
     * Absolute path to plugin lib dir
     *
     * @var string
     */
    public $lib_path;
    /**
     * @var bool
     */
    private $_bootstrapped = false;

    public function __construct($file, $version)
    {
        $this->file = $file;
        $this->version = $version;

        $this->plugin_path   = trailingslashit( plugin_dir_path( $this->file ) );
        $this->plugin_url    = trailingslashit( plugin_dir_url( $this->file ) );
        $this->includes_path = $this->plugin_path . trailingslashit( 'includes' );
        $this->lib_path = $this->plugin_path . trailingslashit( 'lib' );
        $this->assets = $this->plugin_url . trailingslashit( 'assets' );
    }

    public function run_razer()
    {
        try{
            if ($this->_bootstrapped){
                throw new Exception( 'Razer Gold Pin Store can only be called once');
            }
            $this->_run();
            $this->_bootstrapped = true;
        }catch (Exception $e){
            if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
                add_action('admin_notices', function() use($e) {
                    razer_gold_pin_store_generate_rgps_notices($e->getMessage());
                });
            }
        }
    }

    private function _run()
    {
        if (!class_exists('\Saulmoralespa\RazerGoldPin\Client'))
            require_once ($this->lib_path . 'vendor/autoload.php');
        require_once ($this->includes_path . 'class-razer-gold-pin-store-rgps-admin.php');

        $this->admin = new Razer_Gold_Pin_Store_RGPS_Admin();

        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts_admin' ) );
        add_action( 'wp_ajax_razer_gold_pin_store_generate_upload',array($this, 'razer_gold_pin_store_generate_upload'));
        add_action( 'wp_ajax_razer_gold_pin_store_generate_pin',array($this, 'razer_gold_pin_store_generate_pin'));
        add_action( 'wp_ajax_razer_gold_pin_store_generate_history',array($this, 'razer_gold_pin_store_generate_history'));
        add_action( 'wp_ajax_razer_gold_pin_store_generate_history_export',array($this, 'razer_gold_pin_store_generate_history_export'));
    }

    public function enqueue_scripts_admin($hook)
    {
        if($hook === 'razer-gold-pin_page_config-razer-gold-pin-store-generate' || $hook === 'razer-gold-pin_page_create-razer-gold-pin-store-generate') {
            wp_enqueue_script( 'razer-gold-pin-store-generate-sweetalert2',  $this->plugin_url . 'assets/js/sweetalert2.js', array( 'jquery' ), $this->version, true );
            wp_enqueue_script( 'razer-gold-pin-store-generate-config', $this->plugin_url . 'assets/js/razer-gold-pin-store-generate-config.js', array( 'jquery' ), $this->version, true );
            wp_enqueue_script( 'razer-gold-pin-store-generate-select2', $this->plugin_url . 'assets/js/select2.min.js', array( 'jquery' ), $this->version, true );
            wp_enqueue_style('razer-gold-pin-store-generate-select2', $this->plugin_url . 'assets/css/select2.min.css', array(), $this->version, null);
        }
        if($hook === 'razer-gold-pin_page_history-razer-gold-pin-store-generate') {
            wp_enqueue_script( 'razer-gold-pin-store-generate-datatables', $this->plugin_url . 'assets/js/dataTables.min.js', array( 'jquery' ), $this->version, true );
            wp_enqueue_script( 'razer-gold-pin-store-generate-datatables-config', $this->plugin_url . 'assets/js/datatables-config.js', array( 'jquery' ), $this->version, true );
            wp_enqueue_style('razer-gold-pin-store-generate-datatables', $this->plugin_url . 'assets/css/dataTables.min.css', array(), $this->version, null);
            wp_enqueue_script( 'razer-gold-pin-store-generate-sweetalert2',  $this->plugin_url . 'assets/js/sweetalert2.js', array( 'jquery' ), $this->version, true );
        }
    }

    public static function create_table()
    {
        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();
        $table_name = $wpdb->prefix . 'razer_gold_pin_store';

        if ( $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" ) === $table_name )
            return;

        $sql = "CREATE TABLE $table_name (
        id INT NOT NULL AUTO_INCREMENT,
		code VARCHAR(30) NOT NULL,
		description VARCHAR(90) NOT NULL,
		PRIMARY KEY  (id)
	) $charset_collate;";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );
    }

    public static function create_table_pins()
    {
        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();
        $table_name = $wpdb->prefix . 'razer_gold_pin_store_history';

        if ( $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" ) === $table_name )
            return;

        $sql = "CREATE TABLE $table_name (
        id INT NOT NULL AUTO_INCREMENT,
		user_name VARCHAR(60) NOT NULL,
		pins JSON NOT NULL,
		created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
		PRIMARY KEY  (id)
	) $charset_collate;";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );
    }

    public function razer_gold_pin_store_generate_upload()
    {
        if ( ! isset( $_POST['razer_gold_pin_store_generate_excel'] )
            || ! wp_verify_nonce( $_POST['razer_gold_pin_store_generate_excel'], 'razer_gold_pin_store_generate_excel' )
        )
            return;

        $fileTmpName = sanitize_text_field($_FILES["razer_gold_pin_store_generate_excel"]["tmp_name"]);

        $result = [
            'status' => true
        ];

        try{
            $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($fileTmpName);
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
            $reader->setReadDataOnly(true);
            $reader->setLoadAllSheets();
            $spreadsheet = $reader->load($fileTmpName);
            $rows = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
            $sheetCount = $spreadsheet->getSheetCount();

            $data = array_shift($rows);
            $keys_columns = $this->check_column_exist($data);
            if (empty($keys_columns))
                wp_send_json(
                    [
                        'status' => false,
                        'message' => 'El excel debe tener las columnas Description, PIN Store API Product Code'
                    ]
                );

            global $wpdb;
            $table_name = $wpdb->prefix . 'razer_gold_pin_store';

            if ( $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" ) === $table_name ){
                $sql = "DELETE FROM $table_name";
                $wpdb->query($sql);
            }

            self::create_table();

            for ($i = 0; $i < $sheetCount; $i++) {
                $sheet = $spreadsheet->getSheet($i);
                $sheetData = $sheet->toArray(null, true, true, true);

                foreach ($sheetData as $column){

                    if(!empty($column[$keys_columns[0]]) && !empty($column[$keys_columns[1]]) && is_numeric($column[$keys_columns[1]])){
                        $wpdb->insert(
                            $table_name,
                            [
                                'code' => $column[$keys_columns[1]],
                                'description' => $column[$keys_columns[0]]
                            ]
                        );
                    }
                }
            }
        }catch (\Exception $exception){
            $result = [
                'status' => false,
                'message' => $exception->getMessage()
            ];
        }

        wp_send_json($result);
    }

    public function check_column_exist($data)
    {
        $columns = [];

        if (!$description = array_keys($data, 'Description'))
            return [];
        $columns[] = $description[0];

        if (!$codigo = array_keys($data, 'PIN Store API Product Code'))
            return [];
        $columns[] = $codigo[0];

        return $columns;

    }

    public function razer_gold_pin_store_generate_pin()
    {
        global $wpdb;
        $product_code = sanitize_text_field($_REQUEST['razer_gold_pin_store']);
        $qty = sanitize_text_field($_REQUEST['razer_gold_pin_store_qty']);
        $qty = (int)$qty;

        $config = get_option('razer-gold-pin-store-generate', []);

        if (!empty($config)){
            $razer_gold_pin_store = new \Saulmoralespa\RazerGoldPin\Client($config['application_code'], $config['secret_key']);
            $razer_gold_pin_store->sandboxMode($config['enviroment']);

            try{

                $allowedQty = 5;

                $qt = $qty / $allowedQty;
                $rest = 0;

                if(is_float($qt)){
                    $rest = $qty % $allowedQty;
                }

                $qt = (int)$qt;

                $coupons = [];

                for ($i = 1; $i <= $qt; $i++){
                    $couponsCreated = $this->generate_pins($product_code, $allowedQty, $razer_gold_pin_store);
                    $coupons = array_merge($coupons, $couponsCreated);
                }

                if($rest){
                    $couponsCreated = $this->generate_pins($product_code, $rest, $razer_gold_pin_store);
                    $coupons = array_merge($coupons, $couponsCreated);
                }

                $logger = new WC_Logger();
                $logger->add('razer-export', print_r($coupons, true));

                $response = wp_json_encode($coupons);

                $table_name = $wpdb->prefix . 'razer_gold_pin_store_history';

                if (!$wpdb->get_var( "SHOW TABLES LIKE '$table_name'" )){
                    self::create_table_pins();
                }

                $current_user = wp_get_current_user();

                $wpdb->insert(
                    $table_name,
                    [
                        'user_name' => $current_user->display_name,
                        'pins' => $response
                    ]
                );

                $result = [
                    'status' => true,
                    'data' => $response
                ];

            }catch (\Exception $exception){
                $result = [
                    'status' => false,
                    'message' => $exception->getMessage()
                ];
            }

            wp_send_json($result);
        }
    }

    public function razer_gold_pin_store_generate_history()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'razer_gold_pin_store_history';
        $query = "SELECT * FROM $table_name";
        $result = $wpdb->get_results($query, ARRAY_A);
        $data = [];

        foreach ($result as $item) {
            $data[] = [
                $item['user_name'],
                $item['created_at'],
                $item['id']
            ];
        }

        $data = [
            'data' => $data
        ];

        wp_send_json($data);
    }

    public function razer_gold_pin_store_generate_history_export()
    {
        global $wpdb;
        $id = sanitize_text_field($_REQUEST['id']);
        $table_name = $wpdb->prefix . 'razer_gold_pin_store_history';
        $query = "SELECT pins, created_at FROM $table_name WHERE id=$id";
        $result = $wpdb->get_results($query);
        $data = $result[0];
        $pins = $data->pins;
        $created_at = $data->created_at;
        $timestamp = strtotime($created_at);
        $pins = json_decode($pins, true);
        $file_name = "$timestamp.txt";

        $upload_dir = wp_upload_dir();
        $dir = $upload_dir['basedir'] . '/razer-gold-pin-store-generate/';

        $file_created = "$dir$file_name";

        if (!is_dir($dir))
            mkdir($dir,0755);

        $pins_url = '';

        if (file_exists($file_created)){
            $pins_save = true;
        }else{
            $data = "         Pins                   Serials         " . PHP_EOL;
            foreach ($pins as $item){
                $pin = $item['pins'][0];
                $serial = $item['serials'][0];
                $data .= PHP_EOL . "         $pin         $serial";
            }
            $pins_save = file_put_contents("$file_created", $data);
        }

        if ($pins_save)
            $pins_url = $upload_dir['baseurl'] . "/razer-gold-pin-store-generate/$file_name";

        wp_send_json(['url' => $pins_url]);
    }

    public function generate_pins($product_code, int $qty, \Saulmoralespa\RazerGoldPin\Client $razer_gold_pin_store)
    {
        $params = [
            "referenceId" => uniqid(),
            "productCode" => $product_code,
            "quantity" => $qty,
        ];

        $response = $razer_gold_pin_store->purchaseInitiation($params);

        $paramsConfirmation = [
            "referenceId" => $response->referenceId,
            "validatedToken" => $response->validatedToken
        ];
        $response = $razer_gold_pin_store->purchaseConfirmation($paramsConfirmation);
        $coupons = $response->coupons;
        return $coupons;
    }
}