<?php

class Currency_model extends CI_Model {
    private $table;
    private $column_order;
    private $column_search;
    private $request;
    private $order;

    public function __construct() {
        parent::__construct();
        $this->load->database();
        $this->table = 'currency';
        $this->column_order = array(null, 'currency', 'rate');
        $this->column_search = array('currency', 'rate');
        $this->order = array('def', 'rate');
        $this->request = $this->input->post(null, true);
    }

    public function __constructTable() {
        $this->db->from($this->table);
        $i = 0;
        foreach ($this->column_search as $column) {
            if(isset($this->request['search']['value'])){
                if($i===0) {
                    $this->db->group_start();
                    $this->db->like($column, $this->request['search']['value']);
                } else {
                    $this->db->or_like($column, $this->request['search']['value']);
                }

                if(count($this->column_search) - 1 == $i) {
                    $this->db->group_end();
                }
            }
            $i++;
        }

        if(isset($this->request['order']) && array_key_exists($this->request['order']['0']['column'], $this->order)) {
            $this->db->order_by($this->order[$this->request['order']['0']['column']], $this->request['order']['0']['dir']);
        } else if(isset($this->order)) {
            $this->db->order_by('id', 'desc');
        }
    }

    public function getTable() {
        $this->__constructTable();
        if(isset($this->request['length']) && $this->request['length'] != -1 )
            $this->db->limit($this->request['length'], $this->request['start']);
        $query = $this->db->get();
        return $query->result();
    }

    public function count_filtered()
    {
        $this->__constructTable();
        $query = $this->db->get();
        return $query->num_rows();
    }

    public function count_all()
    {
        $this->db->from($this->table);
        return $this->db->count_all_results();
    }

    public function exists($currency) {
        if(!empty($currency)){
            $val = $this->db->get_where($this->table, array('currency' => strtolower($currency)), 1, 0);
            return ($val->num_rows()>0);
        }
        return false;
    }

    public function add($currency, $rate){
        if(!empty($currency) && !empty($rate) && $rate>0){
            $data = array(
                'currency' => $currency,
                'rate' => $rate,
            );
            return $this->db->insert($this->table, $data);
        }
        return false;
    }

    public function update($currency, $rate){
        if(!empty($currency) && !empty($rate) && $rate>0){
            $currency = strtolower($currency);
            if($this->exists($currency)){
                $this->db->set('rate', $rate);
                $this->db->where('currency', $currency);
                return $this->db->update($this->table);
            } else return $this->add($currency, $rate);
        }
        return false;
    }

    public function delete($currency){
        if($this->exists($currency)){
            return $this->db->delete($this->table, array('currency' => strtolower($currency)));
        }
        return false;
    }

    public function get($currency) {
        if(!empty($currency)){
            $this->db->where('currency', $currency);
            $val = $this->db->get($this->table, 1, 0);
            return $val->num_rows()>0?$val->row():'';
        }
        return false;
    }

    public function getDefault($last=false) {
        $this->db->where('def', '1');
        $val = $this->db->get($this->table, 1, 0);
        if($val->num_rows()>0) {
            return $val->row();
        } else if($last) {
            $this->db->order_by("id", "desc");
            $val = $this->db->get($this->table, 1, 0);
            if($val->num_rows()>0) {
                return $val->row();
            }
        }
        return false;
    }

    public function makeDefault($currency) {
        if(!empty($currency)){
            $currency = strtolower($currency);
            if($this->exists($currency)){
                $this->db->set('def', '0');
                $this->db->where('def', '1');
                $this->db->update($this->table);
                $this->db->set('def', '1');
                $this->db->where('currency', $currency);
                return $this->db->update($this->table);
            }
        }
        return false;
    }

    public function currencyLib($decode=false,$val='') {
       $lib = json_decode('{
            "AED": "United Arab Emirates dirham",
            "AFN": "Afghan afghani",
            "ALL": "Albanian lek",
            "AMD": "Armenian dram",
            "ANG": "Netherlands Antillean guilder",
            "AOA": "Angolan kwanza",
            "ARS": "Argentine peso",
            "AUD": "Australian dollar",
            "AWG": "Aruban florin",
            "AZN": "Azerbaijani manat",
            "BAM": "Bosnia and Herzegovina convertible mark",
            "BBD": "Barbados dollar",
            "BDT": "Bangladeshi taka",
            "BGN": "Bulgarian lev",
            "BHD": "Bahraini dinar",
            "BIF": "Burundian franc",
            "BMD": "Bermudian dollar",
            "BND": "Brunei dollar",
            "BOB": "Boliviano",
            "BRL": "Brazilian real",
            "BSD": "Bahamian dollar",
            "BTN": "Bhutanese ngultrum",
            "BWP": "Botswana pula",
            "BYN": "New Belarusian ruble",
            "BYR": "Belarusian ruble",
            "BZD": "Belize dollar",
            "CAD": "Canadian dollar",
            "CDF": "Congolese franc",
            "CHF": "Swiss franc",
            "CLF": "Unidad de Fomento",
            "CLP": "Chilean peso",
            "CNY": "Renminbi|Chinese yuan",
            "COP": "Colombian peso",
            "CRC": "Costa Rican colon",
            "CUC": "Cuban convertible peso",
            "CUP": "Cuban peso",
            "CVE": "Cape Verde escudo",
            "CZK": "Czech koruna",
            "DJF": "Djiboutian franc",
            "DKK": "Danish krone",
            "DOP": "Dominican peso",
            "DZD": "Algerian dinar",
            "EGP": "Egyptian pound",
            "ERN": "Eritrean nakfa",
            "ETB": "Ethiopian birr",
            "EUR": "Euro",
            "FJD": "Fiji dollar",
            "FKP": "Falkland Islands pound",
            "GBP": "Pound sterling",
            "GEL": "Georgian lari",
            "GHS": "Ghanaian cedi",
            "GIP": "Gibraltar pound",
            "GMD": "Gambian dalasi",
            "GNF": "Guinean franc",
            "GTQ": "Guatemalan quetzal",
            "GYD": "Guyanese dollar",
            "HKD": "Hong Kong dollar",
            "HNL": "Honduran lempira",
            "HRK": "Croatian kuna",
            "HTG": "Haitian gourde",
            "HUF": "Hungarian forint",
            "IDR": "Indonesian rupiah",
            "ILS": "Israeli new shekel",
            "INR": "Indian rupee",
            "IQD": "Iraqi dinar",
            "IRR": "Iranian rial",
            "ISK": "Icelandic króna",
            "JMD": "Jamaican dollar",
            "JOD": "Jordanian dinar",
            "JPY": "Japanese yen",
            "KES": "Kenyan shilling",
            "KGS": "Kyrgyzstani som",
            "KHR": "Cambodian riel",
            "KMF": "Comoro franc",
            "KPW": "North Korean won",
            "KRW": "South Korean won",
            "KWD": "Kuwaiti dinar",
            "KYD": "Cayman Islands dollar",
            "KZT": "Kazakhstani tenge",
            "LAK": "Lao kip",
            "LBP": "Lebanese pound",
            "LKR": "Sri Lankan rupee",
            "LRD": "Liberian dollar",
            "LSL": "Lesotho loti",
            "LYD": "Libyan dinar",
            "MAD": "Moroccan dirham",
            "MDL": "Moldovan leu",
            "MGA": "Malagasy ariary",
            "MKD": "Macedonian denar",
            "MMK": "Myanmar kyat",
            "MNT": "Mongolian tögrög",
            "MOP": "Macanese pataca",
            "MRO": "Mauritanian ouguiya",
            "MUR": "Mauritian rupee",
            "MVR": "Maldivian rufiyaa",
            "MWK": "Malawian kwacha",
            "MXN": "Mexican peso",
            "MXV": "Mexican Unidad de Inversion",
            "MYR": "Malaysian ringgit",
            "MZN": "Mozambican metical",
            "NAD": "Namibian dollar",
            "NGN": "Nigerian naira",
            "NIO": "Nicaraguan córdoba",
            "NOK": "Norwegian krone",
            "NPR": "Nepalese rupee",
            "NZD": "New Zealand dollar",
            "OMR": "Omani rial",
            "PAB": "Panamanian balboa",
            "PEN": "Peruvian Sol",
            "PGK": "Papua New Guinean kina",
            "PHP": "Philippine peso",
            "PKR": "Pakistani rupee",
            "PLN": "Polish złoty",
            "PYG": "Paraguayan guaraní",
            "QAR": "Qatari riyal",
            "RON": "Romanian leu",
            "RSD": "Serbian dinar",
            "RUB": "Russian ruble",
            "RWF": "Rwandan franc",
            "SAR": "Saudi riyal",
            "SBD": "Solomon Islands dollar",
            "SCR": "Seychelles rupee",
            "SDG": "Sudanese pound",
            "SEK": "Swedish krona",
            "SGD": "Singapore dollar",
            "SHP": "Saint Helena pound",
            "SLL": "Sierra Leonean leone",
            "SOS": "Somali shilling",
            "SRD": "Surinamese dollar",
            "SSP": "South Sudanese pound",
            "STD": "São Tomé and Príncipe dobra",
            "SVC": "Salvadoran colón",
            "SYP": "Syrian pound",
            "SZL": "Swazi lilangeni",
            "THB": "Thai baht",
            "TJS": "Tajikistani somoni",
            "TMT": "Turkmenistani manat",
            "TND": "Tunisian dinar",
            "TOP": "Tongan paʻanga",
            "TRY": "Turkish lira",
            "TTD": "Trinidad and Tobago dollar",
            "TWD": "New Taiwan dollar",
            "TZS": "Tanzanian shilling",
            "UAH": "Ukrainian hryvnia",
            "UGX": "Ugandan shilling",
            "USD": "United States dollar",
            "UYI": "Uruguay Peso en Unidades Indexadas",
            "UYU": "Uruguayan peso",
            "UZS": "Uzbekistan som",
            "VEF": "Venezuelan bolívar",
            "VND": "Vietnamese đồng",
            "VUV": "Vanuatu vatu",
            "WST": "Samoan tala",
            "XAF": "Central African CFA franc",
            "XCD": "East Caribbean dollar",
            "XOF": "West African CFA franc",
            "XPF": "CFP franc",
            "XXX": "No currency",
            "YER": "Yemeni rial",
            "ZAR": "South African rand",
            "ZMW": "Zambian kwacha",
            "ZWL": "Zimbabwean dollar"
        }', true);
       $val = strtoupper($val);
       return $decode ? (array_key_exists($val, $lib) ? $lib[$val] : '' ) : $lib;
    }

}