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

class Customer_model extends CI_Model
{
    public function insert($model)
    {
        $this->db->insert('customer_master', $model);
        return $this->db->insert_id();
    }

    public function selectall()
    {
        $this->db->select('id, customer_name, mobile, email, gst_no, address, status');
        $this->db->where('is_deleted', 0);
        $this->db->order_by('id', 'DESC');
        return $this->db->get('customer_master')->result();
    }

    public function getbyid($id)
    {
        $this->db->where('id', $id);
        return $this->db->get('customer_master')->result();
    }

    // Same name + same mobile chi duplicate active entry aahe ka te check karte (edit chya vela current id sodun)
    public function checkDuplicate($customer_name, $mobile, $exclude_id = NULL)
    {
        $this->db->where('is_deleted', 0);
        $this->db->where('TRIM(LOWER(customer_name))', trim(strtolower($customer_name)));
        $this->db->where('mobile', trim($mobile));
        if (!empty($exclude_id)) {
            $this->db->where('id !=', $exclude_id);
        }
        return $this->db->get('customer_master')->num_rows();
    }

    public function update($id, $data)
    {
        return $this->db->update('customer_master', $data, ['id' => $id]);
    }

    public function delete($id)
    {
        return $this->db->where('id', $id)
                        ->update('customer_master', ['is_deleted' => 1]);
    }

    public function getActive()
    {
        $this->db->where(['status' => 1, 'is_deleted' => 0]);
        return $this->db->get('customer_master')->result();
    }

    public function count($where = []) {
        if (!empty($where)) $this->db->where($where);
        return $this->db->count_all_results('customer_master');
    }
}
