<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Customer_Model extends MY_Model {

    function __construct() {
        parent::__construct();
        $this->_order_by = 'name';
        $this->_primary_key = 'id';
        $this->_table_name = 'customer';
    }

    public function getCustomer($id, $name, $phone, $email, $status, $city, $area) {
        $this->db->select('C.*,CA.id,CA.cid,CA.branch,CA.type,CA.building,CA.floor,CA.apartment,CA.sector,CA.street,CA.postcode,CA.area,CA.city,CA.region,CA.country');
        $this->db->from('customer C');
        $this->db->join('customer_address CA', 'CA.cid=C.id', 'left');
        if ($name) {
            $this->db->where('C.name', $name);
        }
        if ($phone) {
            $this->db->where('C.phone', $phone);
        }
        if ($email) {
            $this->db->where('C.email', $email);
        }
        if ($email) {
            $this->db->where('C.status', $status);
        }
        if ($city) {
            $this->db->where('CA.city', $city);
        }
        if ($area) {
            $this->db->where('CA.area', $area);
        }
        //$this->db->where('CA.type', 'primary');
        $this->db->where('C.branch', $this->session->userdata('branch'));
        $this->db->group_by('C.id');
        $this->db->order_by('C.name', 'ASC');
        return $this->db->get('customer');
    }

    public function checkme($column, $value, $update = 'no') {
        if ($update == 'yes') {
            $old = $this->input->post('old');
            if (trim(strtolower($old)) === trim(strtolower($value))) {
                return false;
            } else {
                return $this->doesCustomerExist($this->_table_name, $column, $value);
            }
        } else {
            return $this->doesCustomerExist($this->_table_name, $column, $value);
        }
    }

    private function doesCustomerExist($table, $column, $value) {
        return $this->db->where(array($column => $value, 'branch' => $this->session->userdata('branch')))->count_all_results($table) > 0;
    }

    public function saveCustomer($data, $id = NULL) {
        $this->_table_name = 'customer';
        $this->_primary_key = 'id';
        if ($id !== NULL && $id > 0) {
            $data['updated_by'] = 1;
        } else {
            $data['created_by'] = 1;
        }
        return parent::save($data, $id);
    }

    public function saveCustomerAddress($data, $id = NULL) {
        $this->_table_name = 'customer_address';
        $this->_primary_key = 'id';
        if ($id !== NULL && $id > 0) {
            $data['updated_by'] = 1;
        } else {
            $data['created_by'] = 1;
        }
        return parent::save($data, $id);
    }

}
