<?php
defined('BASEPATH') or exit('No direct script access allowed');

class language_model extends MY_Model
{

    protected $tb_main;
    protected $filter_accepted;
    protected $field_search_accepted;

    public function __construct()
    {
        parent::__construct();
        $this->tb_main = LANGUAGE_LIST;

        $this->filter_accepted = array_keys(app_config('template')['status']);
        unset($this->filter_accepted['3']);
        $this->field_search_accepted = app_config('config')['search']['default'];
    }

    public function list_items($params = null, $option = null)
    {
        $result = null;

        if ($option['task'] == 'list-items') {
            $this->db->select('id, code, country_code, is_default, status, created');
            $this->db->from($this->tb_main);

            // filter
            if ($params['filter']['status'] != 3 && in_array($params['filter']['status'], $this->filter_accepted)) {
                $this->db->where('status', $params['filter']['status']);
            }
            //Search
            if ($params['search']['field'] === 'all') {
                $i = 1;
                foreach ($this->field_search_accepted as $column) {
                    if ($column != 'all') {
                        if ($i == 1) {
                            $this->db->like($column, $params['search']['query']);
                        } elseif ($i > 1) {
                            $this->db->or_like($column, $params['search']['query']);
                        }
                        $i++;
                    }
                }
            } elseif (in_array($params['search']['field'], $this->field_search_accepted) && $params['search']['query'] != "") {
                $this->db->like($params['search']['field'], $params['search']['query']);
            }

            $this->db->order_by('id', 'DESC');
            if ($params['pagination']['limit'] != "" && $params['pagination']['start'] >= 0) {
                $this->db->limit($params['pagination']['limit'], $params['pagination']['start']);
            }
            $query = $this->db->get();
            $result = $query->result_array();
        }
        // list-items-by-params
        if ($option['task'] == 'list-items-by-params') {
            $this->db->select('id, code, country_code, is_default, status, created');
            $this->db->from($this->tb_main);
            $this->db->where($params);
            $this->db->order_by('is_default', 'DESC');
            $query = $this->db->get();
            $result = $query->result_array();
        }

        return $result;
    }

    public function get_item($params = null, $option = null)
    {
        $result = null;
        if ($option['task'] == 'get-item') {
            $result = $this->get("id, code, country_code, is_default, status, created", $this->tb_main, ['id' => $params['id']], '', '', true);
        }
        if ($option['task'] == 'get-item-by-params') {
            $result = $this->get("id, code, country_code, is_default, status, created", $this->tb_main, $params, '', '', true);
        }
        return $result;
    }

    public function count_items($params = null, $option = null)
    {
        $result = null;
        if ($option['task'] == 'count-items-group-by-status') {
            $this->db->select('count(id) as count, status');
            $this->db->from($this->tb_main);
            //Search
            if ($params['search']['field'] === 'all') {
                $i = 1;
                foreach ($this->field_search_accepted as $column) {
                    if ($column != 'all') {
                        if ($i == 1) {
                            $this->db->like($column, $params['search']['query']);
                        } elseif ($i > 1) {
                            $this->db->or_like($column, $params['search']['query']);
                        }
                        $i++;
                    }
                }
            } elseif (in_array($params['search']['field'], $this->field_search_accepted) && $params['search']['query'] != "") {
                $this->db->like($params['search']['field'], $params['search']['query']);
            }

            $this->db->order_by('status', 'DESC');
            $this->db->group_by('status');
            $query = $this->db->get();
            $result = $query->result_array();
        }

        if ($option['task'] == 'count-items-by-status') {
            $this->db->select('id');
            $this->db->from($this->tb_main);
            if ($params['filter']['status'] != 3 && in_array($params['filter']['status'], $this->filter_accepted)) {
                $this->db->where('status', $params['filter']['status']);
            }
            //Search
            if ($params['search']['field'] === 'all') {
                $i = 1;
                foreach ($this->field_search_accepted as $column) {
                    if ($column != 'all') {
                        if ($i == 1) {
                            $this->db->like($column, $params['search']['query']);
                        } elseif ($i > 1) {
                            $this->db->or_like($column, $params['search']['query']);
                        }
                        $i++;
                    }
                }
            } elseif (in_array($params['search']['field'], $this->field_search_accepted) && $params['search']['query'] != "") {
                $this->db->like($params['search']['field'], $params['search']['query']);
            }
            $query = $this->db->get();
            $result = $query->num_rows();
        }
        return $result;
    }

    public function delete_item($params = null, $option = null)
    {
        $result = [];
        if ($option['task'] == 'delete-item') {
            $item = $this->get("id, ids", $this->tb_main, ['id' => $params['id']]);
            if ($item) {
                $this->db->delete($this->tb_main, ["id" => $params['id']]);
                $result = [
                    'status' => 'success',
                    'message' => 'Deleted successfully',
                    "ids" => $item->ids,
                ];
            } else {
                $result = [
                    'status' => 'error',
                    'message' => 'There was an error processing your request. Please try again later',
                ];
            }
        }
        return $result;
    }

    public function save_item($params = null, $option = null)
    {
        switch ($option['task']) {
            case 'add-item':
                $data = array(
                    "code" => post('language_code'),
                    "country_code" => post('country_code'),
                    "status" => (int) post("status"),
                    "is_default" => (int) post("default"),
                    "ids" => ids(),
                    "created" => NOW,
                );
                $this->db->insert($this->tb_main, $data);
                $this->create_php_lang_file(post('language_code'), $_POST['lang']);
                return ["status" => "success", "message" => 'Add successfully'];
                break;

            case 'edit-item':
                $data = array(
                    "code" => post('language_code'),
                    "country_code" => post('country_code'),
                    "status" => (int) post("status"),
                    "is_default" => (int) post("default"),
                );
                if (post("default")) {
                    if (!post("status")) {
                        return ["status" => "error", "message" => 'Invalid Status'];
                    }
                    $this->db->update($this->tb_main, ['is_default' => 0], ["id !=" => post('id')]);
                }
                $this->db->update($this->tb_main, $data, ["id" => post('id')]);
                $this->create_php_lang_file(post('language_code'), $_POST['lang']);
                return ["status" => "success", "message" => 'Update successfully'];
                break;

            case 'change-status':
                $this->db->update($this->tb_main, ['status' => $params['status'], 'changed' => NOW], ["id" => $params['id']]);
                return ["status" => "success", "message" => 'Update successfully'];
                break;

            case 'bulk-action':
                if (in_array($params['type'], ['delete', 'deactive', 'active']) && empty($params['ids'])) {
                    return ["status" => "error", "message" => 'Please choose at least one item'];
                }
                $arr_ids = convert_str_number_list_to_array($params['ids']);
                switch ($params['type']) {
                    case 'delete':
                        $this->db->where_in('id', $arr_ids);
                        $this->db->delete($this->tb_main);
                        return ["status" => "success", "message" => 'Update successfully'];
                        break;
                    case 'deactive':
                        $this->db->where_in('id', $arr_ids);
                        $this->db->update($this->tb_main, ['status' => 0]);
                        return ["status" => "success", "message" => 'Update successfully'];
                        break;
                    case 'active':
                        $this->db->where_in('id', $arr_ids);
                        $this->db->update($this->tb_main, ['status' => 1]);
                        return ["status" => "success", "message" => 'Update successfully'];
                        break;
                }
                break;
        }
    }

    private function create_php_lang_file($lang_code, $data_lang)
    {
        if (is_array($data_lang) && !empty($data_lang)) {
            $lang_path = FCPATH . "app/language/data/" . $lang_code . "_lang.php";
            create_lang_file($lang_path, $data_lang);
        }
        //Delete Old lang ver3.2
        $old_path = FCPATH . "app/language/tmp/lang_" . $lang_code . ".txt";
        if (file_exists($old_path)) {
            @unlink($old_path);
        }
    }
}
