<?php

class Gateway_model extends CI_Model {
    private $table;

    public function __construct() {
        parent::__construct();
        $this->load->database();
        $this->table = 'gateways';
    }

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

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

    public function add($data){
        if(!empty($data) && isset($data['slug'])){
            $data = array_merge(array(
                'name' => '',
                'slug' => '',
                'resellbizkey' => '',
                'charge' => '0.00',
                'fields' => '{}',
                'fields_sort' => '',
                'instruction' => '',
                'modified' => date('Y-m-d H:i:s'),
                'created' => date('Y-m-d H:i:s')
            ), $data);
            return $this->db->insert($this->table, $data);
        }
        return false;
    }

    public function update($slug, $data){
        if(!empty($slug) && !empty($data) && !isset($data['slug'])){
            if(isset($data['created'])) unset($data['created']);
            if($this->exists($slug) && !empty($data)){
                foreach ($data as $key => $val) {
                    $this->db->set($key, $val);
                }
                $this->db->where('slug', $slug);
                return $this->db->update($this->table);
            } else {
                $data['slug'] = $slug;
                return $this->add($data);
            }
        }
        return false;
    }

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