<?php

/**
 * Created by PhpStorm.
 * User: Igor Ratsun
 * Date: 30.09.2021
 * Time: 19:56
 */
class Import_api extends \MX_Controller
{
    protected $steps = [
        'file'    => 'upload_file',
        'check'   => 'check',
        'process' => 'process',
    ];

    protected $columns = [];
    protected $display_as = [];
    protected $table;
    protected $uniq_field;

    public function set_table($table)
    {
        $this->table = $table;
        return $this;
    }

    public function set_uniq_field($uniq_field)
    {
        $this->uniq_field = $uniq_field;
        return $this;
    }

    /**
     * @param $columns array
     * @return $this
     */
    public function set_columns(array $columns)
    {
        $this->columns = $columns;
        return $this;
    }

    public function display_as($column, $value)
    {
        $this->display_as[$column] = $value;
        return $this;
    }

    public function render()
    {
        if (empty($this->table)) {
            show_error(sprintf('Set table first'));
        }

        if (empty($this->uniq_field)) {
            show_error(sprintf('Set uniq_field first'));
        }
        if (empty($this->columns)) {
            show_error(sprintf('Add columns first'));
        }

        $step = $this->input->get('step') ? $this->input->get('step') : 'file';
        if (isset($this->steps[$step])) {

            return $this->{$this->steps[$step]}();
        }

        show_error(sprintf('Step "%s" not found', $step));
    }

    protected function upload_file()
    {
        $content = ['error' => ''];

        if ($this->input->post()) {
            $config['upload_path'] = FCPATH . 'application/cache/';
            $config['allowed_types'] = 'xlsx';
            $config['file_name'] = 'import.xlsx';
            $config['overwrite'] = true;

            $this->load->library('upload', $config);

            if (!$this->upload->do_upload()) {
                $content['error'] = $this->upload->display_errors();
            } else {
                redirect($this->uri->uri_string() . '?step=check');
            }
        }

        $this->load->helper('form');

        return $this->parser->parse('import/upload_file', $content, TRUE);
    }

    protected function check()
    {
        $this->load->helper('form');
        $fields = [];
        foreach ($this->columns as $column) {
            $fields[$column] = !empty($this->display_as[$column]) ? $this->display_as[$column] : $column;
        }

        $content = [
            'fields'    => $fields,
            'schedules' => $this->load_file_data(),
        ];

        return $this->parser->parse('import/check', $content, TRUE);
    }

    public function process()
    {
        $this->load->model('import/import_tmodel');
        $this->import_tmodel->set_table($this->table)->set_uniq_field($this->uniq_field);

        $exists = $this->import_tmodel->fetch_all_prepared();
        $mapping = $this->input->post('col');
        $uniq_col_id = array_search($this->uniq_field, $mapping);

        $stat = [
            'skipped' => 0,
            'added'   => 0,
            'updated' => 0,
        ];
        foreach ($this->load_file_data() as $key => $cols) {
            if ($key == 0 || empty($cols[$uniq_col_id])) {
                $stat['skipped']++;
                continue;
            }
            $data = [];
            foreach ($mapping as $map_key => $map_field) {
                $data[$map_field] = !empty($cols[$map_key]) ? $cols[$map_key] : '';
            }
            if (!empty($exists[$cols[$uniq_col_id]])) {
                $stat['updated']++;
                $this->import_tmodel->update($exists[$cols[$uniq_col_id]]['id'], $data);
            } else {
                $stat['added']++;
                $this->import_tmodel->add($data);
            }
        }

        return $this->parser->parse('import/process', ['stat' => $stat], TRUE);
    }

    protected function load_file_data()
    {
        $inputFileName = FCPATH . 'application/cache/import.xlsx';
        $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($inputFileName);
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
        $spreadsheet = $reader->load($inputFileName);
        return $spreadsheet->getActiveSheet()->toArray();
    }

}