<?php


namespace App\Models;

use CodeIgniter\Model;

class Md_database extends Model {

    public $db;

    public function __construct() {
        parent::__construct();
        $this->db = \Config\Database::connect();
    }

    public function insertData($table, $data) {
       
        $this->db->table($table)->insert($data);
        $result = $this->db->insertID();
        return $result;

    }

    public function deleteData($table, $condition) {
        $this->db->table($table)->update($data, $condition);
        return $this->db->affectedRows();

    }

    public function Inserts($table, $data) {
        $this->db->table($table)->insert($data);
        $result = $this->db->insertID();
        return $result;
    }

//function for  data fetching data from database

        public function getCounts($table,$condition = '')
        {
                $count = $this->db->table($table)
                ->where($condition)
                ->countAllResults();
                return $count;
        }


    public function getData($table, $fields = '', $condition = '', $order_by = '', $limit = '') {
        $department_array = $this->db->table($table)
        ->select("*")
        ->where($condition)
        ->orderBy($order_by)
        ->get()
        ->getResultArray();
           
            return $department_array;

    }

/*code to get data useing common function in object form

    public function getDataObject($table, $fields = '', $condition = '', $order_by = '', $limit = '') {

        $str_sql = '';

        if (is_array($fields)) {

#$fields passed as array

            $str_sql .= implode(",", $fields);

        } elseif ($fields != "") {

#$fields passed as string

            $str_sql .= $fields;

        } else {

            $str_sql .= '*';  #$fields passed blank

        }

        $this->db->select($str_sql);

        if (is_array($condition)) {  #$condition passed as array

            if (count($condition) > 0) {

                foreach ($condition as $field_name => $field_value) {

                    if ($field_name != '' && $field_value != '') {

                        $this->db->where($field_name, $field_value);

                    }

                }

            }

        } else if ($condition != "") { #$condition passed as string

            $this->db->where($condition);

        }

        if ($limit != "")

            $this->db->limit($limit);#limit is not blank



        if (is_array($order_by)) {

            $this->db->order_by($order_by[0], $order_by[1]);  #$order_by is not blank

        } else if ($order_by != "") {

            $this->db->order_by($order_by);  #$order_by is not blank

        }

        $this->db->from($table);  #getting record from table name passed

        $query = $this->db->get();



        return $query->num_rows() ? $query->result() : false;

    }



//end of getDataObject()
*/
//function for updating data into database

    public function updateData($table, $data, $condition) {
        $this->db->table($table)->update($data, $condition);
               return $this->db->affectedRows();
    }



    public function uploadFile($path, $type, $file_name, $error_msg, $new_name) {



        $config['upload_path'] = $path; //'uploads/superadmin/';

        $config['allowed_types'] = $type; //'gif|jpg|png|jpeg';

        $config['max_width'] = 0;

        $config['max_height'] = 0;

        $config['max_size'] = 0;

        $config['encrypt_name'] = false;

        $config['file_name'] = $new_name;

        $config['overwrite'] = true;

        $this->load->library('upload');

        $this->upload->initialize($config);



        if (!$this->upload->do_upload($file_name)) {

            $error = $this->upload->display_errors();

//               $this->session->set_flashdata('error', $error_msg . " : " . $error);

//               redirect($_SERVER['HTTP_REFERER']);

        } else {



            $upload_data = $this->upload->data()['file_name'];

        }



        if (!empty($upload_data)) {

//               chmod($upload_data['full_path'], 0755);

            return $upload_data;

        } else {

            return 0;

        }

    }



    public function multiUploadFile($path, $type, $file_name, $error_msg, $new_name) {



        $upload_data = '';

        $new_name = uniqid();



        foreach ($_FILES[$file_name]['name'] as $key => $img) {



            $_FILES['userfile']['name'] = $_FILES[$file_name]['name'][$key];

            $_FILES['userfile']['type'] = $_FILES[$file_name]['type'][$key];

            $_FILES['userfile']['tmp_name'] = $_FILES[$file_name]['tmp_name'][$key];

            $_FILES['userfile']['error'] = $_FILES[$file_name]['error'][$key];

            $_FILES['userfile']['size'] = $_FILES[$file_name]['size'][$key];



            $config['upload_path'] = $path; //'uploads/superadmin/';

            $config['allowed_types'] = $type; //'gif|jpg|png|jpeg';

            $config['max_width'] = 0;

            $config['max_height'] = 0;

            $config['max_size'] = 0;

            $config['encrypt_name'] = false;

//               $config['file_name'] = $new_name . '_' . $key;

            $config['overwrite'] = false;

            $this->load->library('upload', $config);

            $this->upload->initialize($config);

            if (!$this->upload->do_upload('userfile')) {

                $error = $this->upload->display_errors();

//                    $this->session->set_flashdata('error', $error_msg . " : " . $error);

//                    redirect($_SERVER['HTTP_REFERER']);

            } else {

                $upload_data[] = $this->upload->data()['file_name'];

            }

        }



        if (!empty($upload_data)) {

//               chmod($upload_data['full_path'], 0755);

            return $upload_data;

        } else {

            return 0;

        }

    }



// end of uploadFile()







    function NewMailSend($to, $from, $subject, $message) {



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

        $this->email->set_newline("\r\n");

        $this->email->from(stripslashes($from['email']), $from['name']);

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

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

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

        $result = $this->email->send();

        return $result;

    }



    public function uploadProfileFile($path, $type, $file_name, $error_msg, $new_name) {



        $config['upload_path'] = $path; //'uploads/superadmin/';

        $config['allowed_types'] = $type; //'gif|jpg|png|jpeg';

        $config['max_width'] = 0;

        $config['max_height'] = 0;

        $config['max_size'] = 0;

        $config['encrypt_name'] = false;

        $config['file_name'] = $new_name;

        $config['overwrite'] = true;

        $this->load->library('upload');

        $this->upload->initialize($config);



        if (!$this->upload->do_upload($file_name)) {

            $error = array('error' => $this->upload->display_errors());

            $this->session->set_flashdata('error', $error['error']);

            //$this->load->view('envelop/pages/user master/create_user');

            redirect(base_url() . 'envelop/faculty');

            //echo $error;

//               $this->session->set_flashdata('error', $error_msg . " : " . $error);

//               redirect($_SERVER['HTTP_REFERER']);

        } else {



            $upload_data = $this->upload->data()['file_name'];

        }



        if (!empty($upload_data)) {

//               chmod($upload_data['full_path'], 0755);

            return $upload_data;

        } else {

            return 0;

        }

    }



    public function sendEmail($recipeinets, $from, $subject, $message) {

        $config['protocol'] = 'mail';

        $config['wordwrap'] = FALSE;

        $config['mailtype'] = 'html';

        $config['charset'] = 'utf-8';

        $config['crlf'] = "\r\n";

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

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

        $this->email->initialize($config);



// set the from address

        $this->email->from(stripslashes($from['email']), $from['name']);

// set the subject

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

// set recipeinets

        $this->email->to($recipeinets);



// set mail message

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



// return boolean value for email send

        return $this->email->send();

    }



    public function getEmailInfo($email_title, $reserved_words) {



        // gather information for database table

        $email_data = $this->getData('email_format', '*', array("email_title" => $email_title));

        $content['content'] = $email_data[0]['email_content'];

        $content['subject'] = $email_data[0]['email_subject'];

        // replace reserved words if any

        foreach ($reserved_words as $k => $v) {

            $content = str_replace($k, $v, $content);

        }

//	echo '<pre>';

//	print_r($content);

//	die;

        return $content;

    }



    public function getBrowser() {
        $ub = "Inernet Explorar";
        $u_agent = $_SERVER['HTTP_USER_AGENT'];
        $bname = 'Unknown';
        $platform = 'Unknown';

        $version = "";
        //First get the platform?

        if (preg_match('/linux/i', $u_agent)) {

            $platform = 'linux';

        } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {

            $platform = 'mac';

        } elseif (preg_match('/windows|win32/i', $u_agent)) {

            $platform = 'windows';

        }



        // Next get the name of the useragent yes seperately and for good reason

        if (preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent)) {

            $bname = 'Internet Explorer';

            $ub = "MSIE";

        } elseif (preg_match('/Firefox/i', $u_agent)) {

            $bname = 'Mozilla Firefox';

            $ub = "Firefox";

        } elseif (preg_match('/Chrome/i', $u_agent)) {

            $bname = 'Google Chrome';

            $ub = "Chrome";

        } elseif (preg_match('/Safari/i', $u_agent)) {

            $bname = 'Apple Safari';

            $ub = "Safari";

        } elseif (preg_match('/Opera/i', $u_agent)) {

            $bname = 'Opera';

            $ub = "Opera";

        } elseif (preg_match('/Netscape/i', $u_agent)) {

            $bname = 'Netscape';

            $ub = "Netscape";

        }



        // finally get the correct version number

        $known = array('Version', $ub, 'other');

        $pattern = '#(?<browser>' . join('|', $known) .

                ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';

        if (!preg_match_all($pattern, $u_agent, $matches)) {

            // we have no matching number just continue

        }



        // see how many we have

        $i = count($matches['browser']);

        if ($i != 1) {

            //we will have two since we are not using 'other' argument yet

            //see if version is before or after the name

            if (strripos($u_agent, "Version") < strripos($u_agent, $ub)) {

                $version = (!empty($matches['version'][0]) ? $matches['version'][0] : $ub);

            } else {

                $version = (!empty($matches['version'][1]) ? $matches['version'][1] : $ub);

            }
        } else {
            $version = (!empty($matches['version'][0]) ? $matches['version'][0] : $ub);
        }

        // check if we have a number
        if ($version == null || $version == "") {
            $version = "?";
        }

        return array(
            'userAgent' => $u_agent,
            'name' => $bname,
            'version' => $version,
            'platform' => $platform,
            'pattern' => $pattern
        );
    }
}

?>