<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Sms_Model extends MY_Model {

    function __construct() {
        parent::__construct();
    }

    public function get_employee_list() {
        $this->db->select('E.*');
        $this->db->from('employees AS E');
        $this->db->join('users AS U', 'U.id = E.user_id', 'left');
        $this->db->where('E.status', '1');
        if ($this->session->userdata('role_id') == SUPER_ADMIN) {
            $this->db->where_in('U.role_id', array(SUPER_ADMIN, ADMIN, ACCOUNTANT, RECEPTIONIST, MARKETING));
        } else {
            $this->db->where_in('U.role_id', array(ADMIN, ACCOUNTANT, RECEPTIONIST, MARKETING));
        }
        $this->db->order_by('E.id ', 'DESC');
        return $this->db->get()->result();
    }

    public function get_sms_list($keyword, $type, $form_date, $to_date, $role_id, $operator, $created_by) {
        $this->db->select('ML.*, R.name as role, C.name as created_by');
        $this->db->from('text_message_logs AS ML');
        $this->db->join('roles AS R', 'R.id = ML.role_id', 'left');
        $this->db->join('employees AS C', 'C.user_id = ML.created_by', 'left');
        if ($keyword) {
            $this->db->like('ML.sms_text', $keyword, 'both');
            $this->db->or_like('C.name', $keyword, 'both');
        }
        if ($type) {
            $this->db->where('ML.sms_type', $type);
        }
        if ($form_date && $to_date) {
            $this->db->where("DATE(ML.created_at) BETWEEN '$form_date' AND '$to_date'");
        }
        if ($role_id) {
            $this->db->where('ML.role_id', $role_id);
        }
        if ($operator) {
            $this->db->where('ML.operator', $operator);
        }
        if ($created_by) {
            $this->db->where('ML.created_by', $created_by);
        }
        $this->db->order_by('ML.id', 'DESC');
        return $this->db->get()->result();
    }

    public function get_single_sms($id) {
        $this->db->select('TM.*, R.name as role, E.name as created_by');
        $this->db->from('text_message_logs AS TM');
        $this->db->join('roles AS R', 'R.id = TM.role_id', 'left');
        $this->db->join('employees AS E', 'E.user_id = TM.created_by', 'left');
        $this->db->where('TM.id', $id);
        return $this->db->get()->row();
    }
}
