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

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

    public function selectall()
    {
        $this->db->select('product_master.id, product_master.product_code, product_master.product_name,
                           product_master.purchase_rate, product_master.sale_rate,
                           product_master.gst_percent, product_master.current_stock, product_master.status,
                           category_master.category_name, unit_master.unit_name');
        $this->db->join('category_master', 'category_master.id = product_master.category_id', 'left outer');
        $this->db->join('unit_master', 'unit_master.id = product_master.unit_id', 'left outer');
        $this->db->where('product_master.is_deleted', 0);
        $this->db->order_by('product_master.id', 'DESC');
        return $this->db->get('product_master')->result();
    }

    public function getbyid($id)
    {
        $this->db->select('product_master.*, category_master.category_name, unit_master.unit_name');
        $this->db->where('product_master.id', $id);
        $this->db->join('category_master', 'category_master.id = product_master.category_id', 'left outer');
        $this->db->join('unit_master', 'unit_master.id = product_master.unit_id', 'left outer');
        return $this->db->get('product_master')->result();
    }

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

    public function delete($id)
    {
        // Hard delete. product FK वर ON DELETE CASCADE नाही,
        // म्हणून हा record कुठे वापरला असेल (purchase/sale items) तर DB exception टाकेल.
        $this->db->where('id', $id);
        $this->db->delete('product_master');
        return $this->db->affected_rows() > 0;
    }

    public function getActive()
    {
        $this->db->select('product_master.*, unit_master.unit_name');
        $this->db->join('unit_master', 'unit_master.id = product_master.unit_id', 'left outer');
        $this->db->where(['product_master.status' => 1, 'product_master.is_deleted' => 0]);
        return $this->db->get('product_master')->result();
    }

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