<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

/**
 * Upgrade Product module to version 3.0.0
 *
 * @author CIEXT skeleton
 */
class Product_upgrade_0 extends Abstract_upgrade
{

    protected $ci;
    protected $tables = [
        [
            'table'  => 'product',
            'fields' => ['id_product', 'name', 'short_desc', 'description']
        ],
        [
            'table'  => 'product_attr',
            'fields' => ['id_product_attr', 'name', 'options']
        ],
        [
            'table'  => 'product_manufacturer',
            'fields' => ['id_product_manufacturer', 'name']
        ],
        [
            'table'  => 'product_icon',
            'fields' => ['id_product_icon', 'name']
        ],
    ];

    public function __construct()
    {
        $this->ci = & get_instance();
    }

    public function up()
    {
        if (!$this->is_table_exist('product_translate')) {
            $this->create_tables();
            foreach ($this->tables as $table) {
                $this->copy_data_from_table_to_translate_table($table['table'], implode(', ', $table['fields']));
                foreach ($table['fields'] as $field) {
                    if (strpos($field, 'id') === false) {
                        $this->delete_column($table['table'], $field);
                    }
                }
            }
        }

        return '3.0.0';
    }

    public function down()
    {
        return '0';
    }

    protected function create_tables()
    {
        foreach (explode(';', file_get_contents(dirname(get_instance()->config->item('composer_autoload')) . '/ciext/product/data/migration_0.sql')) as $query) {
            $query = trim($query);
            if (!empty($query)) {
                $this->ci->db->query($query);
            }
        }

        return $this;
    }

    protected function copy_data_from_table_to_translate_table($table = '', $fields = '')
    {
        $res = $this->ci->db->select($fields)
                        ->get($table)->result_array();

        $id_lan = $this->ci->load->library('db_lang_lib')->get_current_lang_id();

        foreach ($res as &$item) {
            $item['id_lan'] = $id_lan;
        }
        unset($item);

        return !empty($res) ? $this->ci->db->insert_batch($table . '_translate', $res) : false;
    }

    protected function delete_column($table = '', $column = '')
    {
        $this->ci->db->query('ALTER TABLE ' . $table .
                ' DROP COLUMN ' . $column . ';');

        return $this;
    }

}
