<?php

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

class MY_Model extends CI_Model {

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

    // insert new data
    function insert($table_name, $data_array) {
        $this->db->insert($table_name, $data_array);
        return $this->db->insert_id();
    }

    // insert new data

    function insert_batch($table_name, $data_array) {

        $this->db->insert_batch($table_name, $data_array);
        return $this->db->insert_id();
    }

    // update data by index

    function update($table_name, $data_array, $index_array) {

        $this->db->update($table_name, $data_array, $index_array);
        return $this->db->affected_rows();
    }

    // delete data by index

    function delete($table_name, $index_array) {
        $this->db->delete($table_name, $index_array);
        return $this->db->affected_rows();
    }

    public function get_list($table_name, $index_array, $columns = null, $limit = null, $offset = 0, $order_field = null, $order_type = null) {

        if ($columns)
            $this->db->select($columns);

        if ($limit)
            $this->db->limit($limit, $offset);

        if ($order_type) {
            $this->db->order_by($order_field, $order_type);
        } else {
            $this->db->order_by('id', 'DESC');
        }

        return $this->db->get_where($table_name, $index_array)->result();
    }

    // get data list by index order

    function get_list_order($table_name, $index_array, $order_array, $limit = null) {

        if ($limit) {
            $this->db->limit($limit);
        }
        if ($order_array) {
            $this->db->order_by($order_array['by'], $order_array['type']);
        } else {
            $this->db->order_by('created', 'desc');
        }
        return $this->db->get_where($table_name, $index_array)->result();
    }

    // get single data by index

    function get_single($table_name, $index_array, $columns = null) {

        if ($columns)
            $this->db->select($columns);

        $this->db->order_by('id', 'desc');
        $this->db->limit(1);
        $row = $this->db->get_where($table_name, $index_array)->row();
        return $row;
    }

    function get_single_random($table_name, $index_array, $columns = null) {

        if ($columns)
            $this->db->select($columns);

        $this->db->order_by('rand()');
        $this->db->limit(1);
        $row = $this->db->get_where($table_name, $index_array)->row();
        return $row;
    }

    // get number of rows in database

    function count_all($table_name, $index_array = null) {

        if ($index_array) {
            $this->db->where($index_array);
        }
        return $this->db->count_all_results($table_name);
    }

    public function get_table_fields($table) {

        return $this->db->list_fields($table);
    }

    public function create_user() {

        $password = random_string('numeric', 6);

        $data = array();
        $data['role_id'] = $this->input->post('role_id') ?? null;
        $data['device_id'] = $this->input->post('device_id') ?? null;
        $data['sbiz_id'] =  'sbiz' . random_string('numeric', 4);
        $data['username'] = $this->input->post('username') ?? get_custom_id('users', 'p');
        $data['password'] = $this->input->post('password') ? md5($this->input->post('password')) : md5($password);
        $data['temp_password'] = $this->input->post('password') ?  base64_encode($this->input->post('password')) : base64_encode($password);
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['created_by'] = logged_in_user_id();
        $data['status'] = 1; // by default would be able to login
        $this->db->insert('users', $data);
        $user_id = $this->db->insert_id();


        // Process Sending email/ sms with login info
        $data['name']  = $this->input->post('name');
        $data['phone'] = $this->input->post('phone');
        $data['email'] = $this->input->post('email');
        $data['user_id'] = $user_id;

        // $notification = $this->db->get_where('notifications', array('status' => 1, 'type' => 'registration_sms'))->row();
        // if (isset($notification) && $notification->is_email) {
        //     $this->_send_email($data);
        // }

        return $user_id;
    }

    public function _send_email($data = null) {

        if ($data['email']) {
            $email_setting = $this->db->get_where('email_settings', array('status' => 1))->row();
            $frontend_settings = $this->db->get_where('frontend_settings', array('status' => 1))->row();
            if (!empty($email_setting) && $email_setting->mail_protocol == 'smtp') {
                $config['protocol']     = 'smtp';
                $config['smtp_host']    = $email_setting->smtp_host;
                $config['smtp_port']    = $email_setting->smtp_port;
                $config['smtp_timeout'] = $email_setting->smtp_timeout ? $email_setting->smtp_timeout  : 5;
                $config['smtp_user']    = $email_setting->smtp_user;
                $config['smtp_pass']    = $email_setting->smtp_pass;
                $config['smtp_crypto']  = $email_setting->smtp_crypto ? $email_setting->smtp_crypto  : 'tls';
                $config['mailtype'] = $email_setting->mail_type ? $email_setting->mail_type  : 'html';
                $config['charset']  = $email_setting->char_set ? $email_setting->char_set  : 'iso-8859-1';
                $config['priority']  = $email_setting->priority ? $email_setting->priority  : '3';
            } elseif (!empty($email_setting) && $email_setting->mail_protocol != 'smtp') {
                $config['protocol'] = $email_setting->mail_protocol;
                $config['mailpath'] = '/usr/sbin/' . $email_setting->mail_protocol;
                $config['mailtype'] = $email_setting->mail_type ? $email_setting->mail_type  : 'html';
                $config['charset']  = $email_setting->char_set ? $email_setting->char_set  : 'iso-8859-1';
                $config['priority']  = $email_setting->priority ? $email_setting->priority  : '3';
            } else { // default
                $config['protocol'] = 'sendmail';
                $config['mailpath'] = '/usr/sbin/sendmail';
            }

            $config['wordwrap'] = TRUE;
            $config['newline']  = "\r\n";

            $this->load->library('email');
            $this->email->initialize($config);

            $from_email = FROM_EMAIL;
            $from_name  = FROM_NAME;

            $to         = $data['email'];
            $username   = $data['username'];
            $password   = $data['password'];

            if (!empty($email_setting)) {
                $from_email = $email_setting->from_address;
                $from_name  = $email_setting->from_name;
            } elseif (!empty($frontend_settings)) {
                $from_email = $frontend_settings->email;
                $from_name  = $this->global_setting->brand_title;
            }

            $this->email->from($from_email, $from_name);
            $this->email->to($to);
            $subject = 'Your login credentials on ' . $this->global_setting->brand_title;
            $this->email->subject($subject);

            $message = 'Hi ' . $data['name'];
            $message .= '<br/><br/>';
            $message .= 'Following is your ' . $this->global_setting->brand_title . ' Web Application login credentials.<br/>';
            $message .= '<br/><br/>';
            $message .= 'Your username : ' . $username;
            $message .= '<br/>';
            $message .= 'Your Password : ' . $password;
            $message .= '<br/>';
            $message .= 'Login url : <a href="' . site_url('admin') . '"> Login Here </a>';
            $message .= '<br/><br/>';

            $message .= 'If you are not right person, Plesae ignore this email.<br/><br/>';
            $message .= 'Thank you<br/>';
            $message .= $from_name;

            $this->email->message($message);

            if (!empty($email_setting) && $email_setting->mail_protocol == 'smtp') {
                $this->email->send();
            } else {
                $headers = "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                $headers .= "From:  $from_name < $from_email >\r\n";
                $headers .= "Reply-To:  $from_name < $from_email >\r\n";
                mail($to, $subject, $message, $headers);
            }
        }
    }


    public function get_custom_id($table, $prefix) {
        $max_id = '';
        $this->db->select_max('id');
        $max_id = $this->db->get($table)->row()->id;

        if (isset($max_id) && $max_id > 0) {
            $max_id = $max_id + 1;
        } else {
            $max_id = 1;
        }

        if (!$max_id) {
            $max_id = '0000' . $max_id;
        } elseif ($max_id > 0 && $max_id < 10) {
            $max_id = '0000' . $max_id;
        } elseif ($max_id >= 10 && $max_id < 100) {
            $max_id = '000' . $max_id;
        } elseif ($max_id >= 100 && $max_id < 1000) {
            $max_id = '00' . $max_id;
        } elseif ($max_id >= 1000 && $max_id < 10000) {
            $max_id = '0' . $max_id;
        } else {
            $max_id = $max_id;
        }
        return $prefix . $max_id;
    }
}
