<?php

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

class Dashboard extends MY_Controller {

    var $data_day;
    var $user, $noaroom;

    public function __construct() {
        parent::__construct();
        $this->load->model('booking');
        $this->load->helper('download');
        $this->load->library('zip');
        $this->data_day = $this->booking->data_day();
        $this->user = $this->session->userdata('name');
        $this->operator_id = $this->session->userdata('operator_id');
        //if (get_ap('group', $this->operator_id) == 1) {} else {
        //    redirect("", "refresh");
        //}
        $this->noaroom[1] = "واحد سرير مزدوج";
        $this->noaroom[2] = "اثنين  سرير  مزدوج";
        $this->noaroom[3] = " واحد مزدوج واثنين فردي";
        $this->noaroom[4] = "اربعة فردي";
    }

    public function dbexport() {
        $this->booking->dbexport();
    }

    public function index() {
        $this->all();
    }

    function sum_bill($catid) {
        $this->db->select_sum('text1');
        $this->db->where(" catid=$catid ");
        $query = $this->db->get('model_billshawly')->row_array();
        return $query['text1'];
    }

    function all() {
        $data['bills'] = $this->db->get('orders')->num_rows();

        $this->db->select('sum(`discount_remainder`) as total_amount');
        $data['bills_amount'] = $this->db->get('bills_orders')->row();

        $this->db->where('type', 2);
        $data['product'] = $this->db->get('bills_producer')->result();

        $data['expense'] = array();//$this->db->get('expense')->result();

        $this->db->select('SUM(CASE WHEN approve_status = 1 THEN 1 ELSE 0 END) AS active');
        $this->db->select('SUM(CASE WHEN approve_status = 0 THEN 1 ELSE 0 END) AS not_active');
        $this->db->select('SUM(CASE WHEN approve_status = 0 OR approve_status =1 THEN 1 ELSE 0 END) AS all_users');
        $data['user'] = $this->db->get('bills_user')->row();

        $data['title'] = 'الرئيسية';

        //$data['view'] = '../controllers/views/dashboard';

        $this->load->view('site/dashboard', $data);
    }

    public function moveroom($id) {
        $roomnew = $this->input->post('roomnew');
        if (isset($roomnew)) {

            $query = $this->db->get_where('booking', array(
                'id' => $id
            ));
            $data['show'] = $query->row_array();
            $this->db->where('name', $data['show']['room'])->update('booking_rooms', array(
                'conter' => '3'
            ));
            $this->db->where('name', $roomnew)->update('booking_rooms', array(
                'conter' => '2'
            ));

            $this->db->where('id', $data['show']['id'])->update('booking', array(
                'room' => $roomnew,
                'msgmove' => $this->input->post('msgmove'),
                'timemove' => $this->booking->tissme_now(),
                'oldroom' => $data['show']['room']
            ));

            $this->session->set_flashdata('msg', 'تم   عمل نقل الشقة بفضل الله!');
            // /$this->booking->add_rep_user("نقل شقة ".$data['show']['room']);
        }
        redirect(base_url() . 'dashboard');
    }

    public function backroom($id) {
        $roomnew = $this->input->post('roomnew');
        $query = $this->db->get_where('booking', array(
            'id' => $id
        ));
        $data['show'] = $query->row_array();
        $this->db->where('name', $data['show']['room'])->update('booking_rooms', array(
            'conter' => '2'
        ));

        $this->db->where('id', $data['show']['id'])->update('booking', array(
            'counter' => '1',
            'timeend2' => ''
        ));
        $this->booking->add_rep_user(" استرجاع " . $data['show']['room']);
        $this->session->set_flashdata('msg', 'تم  استرجاع  الشقة بفضل الله!');
        redirect(base_url() . 'dashboard');
    }

    public function commentnbeh($id) {
        $commentnbeh = $this->input->post('commentnbeh');

        $this->db->where('id', $id)->update('booking', array(
            'commentnbeh' => $commentnbeh,
            'comment7' => $this->input->post('comment7'),
            'comment8' => $this->input->post('comment8')
        ));

        $this->session->set_flashdata('msg', 'تم   عمل وضع التنبيه بفضل الله!');
        redirect(base_url() . 'dashboard');
    }

    public function deltnbeh($id) {
        $this->db->where('id', $id)->update('booking', array(
            'commentnbeh' => ''
        ));

        $this->session->set_flashdata('msg', 'تم مسح  التنبيه بفضل الله!');
        redirect(base_url() . 'dashboard');
    }

    public function idend($id) {
        $query = $this->db->get_where('booking', array(
            'id' => $id
        ));
        $data['show'] = $query->row_array();

        $query = $this->db->get_where('booking_rooms', array(
            'name' => $data['show']['room']
        ));
        $data['room'] = $query->row_array();
        $comment = explode("##", $data['room']['comment']);
        $data['all_groups'] = array();
        $nao[1] = "الصالة";
        $nao[2] = " الماستر";
        $nao[3] = " الثانية";
        $nao[4] = " المطبخ";
        $nao[5] = "الحمام";
        $nao[6] = "حمام المساتر";
        $nao[7] = "الثالثة";

        $max = count($comment);
        if ($max > 30)
            $max = 24;
        for ($i = 0; $i < $max; $i ++) {

            $commentsss = explode("|", $comment[$i]);
            if (isset($commentsss[1])) {

                $query = $this->db->get_where('booking_mhtwa', array(
                    'id' => $commentsss[1]
                ));

                // $query = $this->db->get_where('booking_mhtwa', array('id' => $commentsss[1], 'text8' => '1'));

                $row = $query->row_array();
                if (isset($row['text1'])) {
                    $data['all_groups'][$i]['text1'] = $row['text1'];
                    $data['all_groups'][$i]['text2'] = $row['text2'];
                    $data['all_groups'][$i]['text3'] = $row['text3'];
                    $data['all_groups'][$i]['noa'] = '';
                    if ($row['text5'])
                        $data['all_groups'][$i]['noa'] = $nao[$row['text5']];
                    $query = $this->db->get_where('booking_mhtwah', array(
                        'text1' => $data['show']['room'],
                        'text2' => $row['id']
                    ));
                    $mhtwah = $query->row_array();
                    $data['all_groups'][$i]['com'] = '';
                    if (isset($commentsss[1]))
                        $data['all_groups'][$i]['com'] = $mhtwah['text3'];
                }
            }
        }

        if ($data['show']['counter'] == 1)
            $this->db->where('name', $data['show']['room'])->update('booking_rooms', array(
                'conter' => '3'
            ));

        $comment7 = $this->input->post('comment7');

        if ($this->input->post('comment1')) {

            $billback = $this->input->post('comment2');
            $billback2 = $this->input->post('comment22');
            if ($this->input->post('comment2') > 0) {

                $dataadd = array(
                    'catid' => '1',
                    'text3' => '',
                    'text1' => $this->input->post('comment2'),
                    'text2' => " غرامة شقة " . $data['show']['room'] . "بتاريخ    : " . $data['show']['datetext4'] . "رقم التسكين : " . $id,
                    'dateadd' => $this->data_day,
                    'counter' => '1'
                );
                $dataadd = $this->security->xss_clean($dataadd);
                $result = $this->db->insert('model_billshawly', $dataadd);
            }

            if ($billback != $billback2) {

                $this->booking->add_rep_user("  غرامة تاخير لمدة  " . $this->input->post('comment1') . " ساعات مدفع     $billback والمطلوب $billback2 تسكين رقم" . $data['show']['id']);
            }

            $comment7 = '';
            $this->db->where('id', $data['show']['id'])->update('booking', array(
                'comment1' => $this->input->post('comment1'),
                'comment2' => $this->input->post('comment2'),
                'comment3' => $this->input->post('comment7'),
                'comment5' => 'no'
            ));
        }

        if ($data['show']['counter'] == 1) {

            $this->db->where('id', $data['show']['id'])->update('booking', array(
                'counter' => '2',
                'timeend2' => $this->booking->tissme_now(),
                'dataend' => $this->data_day,
                'user2' => $this->session->userdata('name'),
                'comment7' => $comment7
            ));
            $data['show']['timeend'] = $this->booking->tissme_now();
        } else {
            $data['show']['timeend'] = $data['show']['timeend2'];
        }

        $this->session->set_flashdata('msg', 'تم   عمل خروج بفضل الله!');

        $this->load->view('../controllers/bills/views/show/printidout', $data);
        // redirect(base_url() . 'bills/dashboard');
    }

    public function toopen($id) {
        $this->db->where('name', $id)->update('booking_rooms', array(
            'conter' => '1'
        ));
        $this->session->set_flashdata('msg', 'تم    التغير الى متاحة بفضل الله!');

        redirect(base_url() . 'dashboard');
    }

    public function cleanfinsh($id) {
        $query = $this->db->get_where('booking', array(
            'id' => $id
        ));
        $data['show'] = $query->row_array();
        $this->db->where('name', $data['show']['room'])->update('booking_rooms', array(
            'conter' => '1'
        ));
        $this->session->set_flashdata('msg', 'تم    التغير الى متاحة بفضل الله!');

        $this->db->where('id', $data['show']['id'])->update('booking', array(
            'timecleanfinsh' => $this->booking->tissme_now()
        ));
        redirect(base_url() . 'dashboard');
    }

    public function roomtoprom($id) {
        $this->db->where('name', $id)->update('booking_rooms', array(
            'conter' => '4'
        ));
        $this->session->set_flashdata('msg', 'تم    التغير الى صيانة بفضل الله!');

        redirect(base_url() . 'dashboard');
    }

    public function gowait($id) {
        $query = $this->db->get_where('booking', array(
            'id' => $id
        ));
        $data['show'] = $query->row_array();

        $query = $this->db->get_where('booking_rooms', array(
            'name' => $data['show']['room']
        ));
        $data['room'] = $query->row_array();
        $comment = explode("##", $data['room']['comment']);
        $data['all_groups'] = array();
        $nao[1] = "الصالة";
        $nao[2] = " الماستر";
        $nao[3] = " الثانية";
        $nao[4] = " المطبخ";
        $nao[5] = "الحمام";
        $nao[6] = "حمام المساتر";
        $nao[7] = "الثالثة";

        $max = count($comment);
        if ($max > 30)
            $max = 24;
        for ($i = 0; $i < $max; $i ++) {

            $commentsss = explode("|", $comment[$i]);
            if (isset($commentsss[1])) {

                $query = $this->db->get_where('booking_mhtwa', array(
                    'id' => $commentsss[1],
                    'text8' => '1'
                ));

                $row = $query->row_array();
                if (isset($row['text1'])) {
                    $data['all_groups'][$i]['text1'] = $row['text1'];
                    $data['all_groups'][$i]['text2'] = $row['text2'];
                    $data['all_groups'][$i]['text3'] = $row['text3'];
                    $data['all_groups'][$i]['noa'] = '';
                    if ($row['text5'])
                        $data['all_groups'][$i]['noa'] = $nao[$row['text5']];
                    $query = $this->db->get_where('booking_mhtwah', array(
                        'text1' => $data['show']['room'],
                        'text2' => $row['id']
                    ));
                    $mhtwah = $query->row_array();
                    $data['all_groups'][$i]['com'] = '';
                    if (isset($commentsss[1]))
                        $data['all_groups'][$i]['com'] = $mhtwah['text3'];
                }
            }
        }

        $this->db->where('name', $data['show']['room'])->update('booking_rooms', array(
            'conter' => '3'
        ));

        $comment7 = $this->input->post('comment7');

        if ($this->input->post('comment1')) {
            $comment7 = '';
            $this->db->where('id', $data['show']['id'])->update('booking', array(
                'comment1' => $this->input->post('comment1'),
                'comment2' => $this->input->post('comment2'),
                'comment3' => $this->input->post('comment7'),
                'nowait' => $this->input->post('nowait'),
                'comment5' => 'wait'
            ));
            $this->db->where('cid', $data['show']['cid'])->update('booking_clints', array(
                'oky' => 'ok',
                'comment' => "عليه مبلغ " . $this->input->post('comment2') . "  بتاريخ " . $this->data_day
            ));
        }

        $this->db->where('id', $data['show']['id'])->update('booking', array(
            'counter' => '2',
            'timeend2' => $this->booking->tissme_now(),
            'dataend' => $this->data_day,
            'user2' => $this->session->userdata('name'),
            'comment7' => $comment7
        ));

        $data['show']['timeend'] = $this->booking->tissme_now();

        $billback2 = $this->input->post('comment2');
        $billback1 = $this->input->post('comment2old');
        if ($billback1 != $billback2) {

            $this->booking->add_rep_user("  تحويل ايجار لم يتم الاستراد   عليه مبلغ " . $billback1 . "        والمطلوب $billback2 تسكين رقم" . $data['show']['id']);
        }

        $this->session->set_flashdata('msg', 'تم   عمل خروج بفضل الله!');
        $this->load->view('../controllers/bills/views/show/printidout', $data);

        // redirect(base_url() . 'bills/dashboard');
    }

    public function idrenew($id) {
        $query = $this->db->get_where('booking', array(
            'id' => $id
        ));
        $data['show'] = $query->row_array();
        $this->db->where('id', $data['show']['id'])->update('booking', array(
            'counter' => '2'
        ));

        $data = array(
            'name' => $data['show']['name'],
            'datetext4' => $this->data_day,
            'mobile' => $data['show']['mobile'],
            'cid' => $data['show']['cid'],
            'room' => $data['show']['room'],
            'day' => $this->input->post('day'),
            'billexport' => '',
            'bill' => ($this->input->post('bill') + $this->input->post('knet')),
            'timeenter' => $data['show']['timeenter'],
            'timeend' => ($data['show']['timeend'] + (24 * 60 * 60 * $this->input->post('day'))),
            'billprint' => $this->input->post('billprint'),
            'counter' => '1',
            'knet' => $this->input->post('knet'),
            'comment8' => $this->input->post('comment8'),
            'noa' => $data['show']['noa'],
            '3gd' => $data['show']['3gd'],
            'comment' => $data['show']['comment'],
            'commentnbeh' => $data['show']['commentnbeh'],
            'bookingid' => $data['show']['bookingid'],
            'timerenew' => $this->booking->tissme_now(),
            'user' => $this->user
        );
        // / print_r($data);exit;
        $data = $this->security->xss_clean($data);
        $result = $this->db->insert('booking', $data);

        $this->session->set_flashdata('msg', 'تم عمل التمديد بفضل الله');
        redirect(base_url() . 'dashboard');
    }

    public function blacklist($id) {
        $query = $this->db->get_where('booking_clints', array(
            'id' => $id
        ));
        $data['show'] = $query->row_array();

        $edit_data = array(
            'oky' => ''
        );
        $edit_data = $this->security->xss_clean($edit_data);
        $result = $this->db->where('id', $id)->update('booking_clints', $edit_data);

        $this->booking->add_rep_user(" تم ازالة البلاك لست  عن  الرقم المدني  " . $data['show']['cid'] . "    والسبب  كان " . $data['show']['comment']);

        $this->session->set_flashdata('msg', 'تم عمل ازالة البلاك لست بفضل الله');
        redirect(base_url() . 'dashboard');
    }

    public function editcomment($id) {
        $query = $this->db->get_where('booking', array(
            'id' => $id
        ));
        $data['show'] = $query->row_array();

        $mname = $this->input->post('mname');
        if (isset($mname)) {

            $comment = $data['show']['comment'];

            $comment .= $_POST["mname"] . "**" . $_POST["mcid"] . "**" . $_POST["mmobile"] . "**" . $_POST["mcountry"] . "|||";
            $dataedit = array(
                'comment' => $comment
            );
            // / print_r($data);exit;
            $dataedit = $this->security->xss_clean($dataedit);
            $this->db->where('id', $id)->update('booking', $dataedit);

            $this->session->set_flashdata('msg', 'تم عمل اضافة المرافق بفضل الله');
            redirect(base_url() . 'dashboard');
        }
    }

    public function editbooking($id) {
        $query = $this->db->get_where('booking', array(
            'id' => $id
        ));
        $data['show'] = $query->row_array();

        $dataedit = array(
            'bill' => ($this->input->post('bill') + $this->input->post('knet')),
            'billprint' => $this->input->post('billprint'),
            'knet' => $this->input->post('knet'),
            'bookingnew' => $this->input->post('bookingnew')
        );
        // / print_r($data);exit;
        $dataedit = $this->security->xss_clean($dataedit);
        $this->db->where('id', $id)->update('booking', $dataedit);

        $billback = $this->input->post('bill') + $this->input->post('knet');
        $billback2 = $this->input->post('billold');

        if ($billback != $billback2) {
            $this->booking->add_rep_user("  تعديل  مبلغ الى      $billback  من  $billback2 تسكين رقم" . $data['show']['id']);
        }

        $billback = $this->input->post('knet');
        $billback2 = $data['show']['knet'];

        if ($billback != $billback2) {
            $this->booking->add_rep_user("  تعديل  مبلغ الى   كي نت    $billback  من  $billback2 تسكين رقم" . $data['show']['id']);
        }

        $this->session->set_flashdata('msg', 'تم عمل التعديل بفضل الله');
        redirect(base_url() . 'dashboard');
    }

    public function editwait($id) {
        $query = $this->db->get_where('booking', array(
            'id' => $id
        ));
        $data['show'] = $query->row_array();

        $this->db->where('cid', $data['show']['cid'])->update('booking_clints', array(
            'oky' => 'ok',
            'comment' => "عليه مبلغ  " . $this->input->post('comment2')
        ));

        $comment5 = 'wait';
        if ($this->input->post('comment2') == 0) {
            $comment5 = 'okwait';

            $this->db->where('cid', $data['show']['cid'])->update('booking_clints', array(
                'oky' => '',
                'comment' => ""
            ));
        }

        $dataedit = array(
            'comment5' => $comment5,
            'comment2' => $this->input->post('comment2'),
            'comment3' => $this->input->post('comment3'),
            'nowait' => $this->input->post('nowait')
        );
        // / print_r($data);exit;
        $dataedit = $this->security->xss_clean($dataedit);
        $this->db->where('id', $id)->update('booking', $dataedit);
        $this->session->set_flashdata('msg', 'تم  تحويل المبلغ الى سلفه بفضل الله');
        redirect(base_url() . 'dashboard');
    }

    public function idbackwait($id) {
        $query = $this->db->get_where('booking', array(
            'id' => $id
        ));
        $data['show'] = $query->row_array();

        $billback = $this->input->post('billback');
        $billback2 = $this->input->post('billbackold');
        if ($billback > 0) {

            $dataadd = array(
                'catid' => '1',
                'text3' => '',
                'text1' => $billback,
                'text2' => " استرجاع شقة " . $data['show']['room'] . "بتاريخ    : " . $data['show']['datetext4'] . "رقم التسكين : " . $id,
                'dateadd' => $this->data_day,
                'counter' => '1'
            );
            $dataadd = $this->security->xss_clean($dataadd);
            $result = $this->db->insert('model_billshawly', $dataadd);
        }
        if ($billback != $billback2) {

            $this->booking->add_rep_user("  استراد مبلغ      $billback والمطلوب $billback2 تسكين رقم" . $data['show']['id']);
        }

        $this->db->where('cid', $data['show']['cid'])->update('booking_clints', array(
            'oky' => '',
            'comment' => ""
        ));

        $this->db->where('id', $data['show']['id'])->update('booking', array(
            'comment5' => 'okwait'
        ));

        $this->session->set_flashdata('msg', 'تم   استرجاع المبلغ ورفع البلاك لست  بفضل الله!');

        // /$this->load->view('../controllers/bills/views/show/printidout', $data);
        redirect(base_url() . 'dashboard');
    }

    public function outsite($id, $outsite) {
        $query = $this->db->get_where('booking', array(
            'id' => $id
        ));
        $data['show'] = $query->row_array();

        $this->db->where('id', $data['show']['id'])->update('booking', array(
            'outsite' => $outsite
        ));

        if ($outsite == 'ok')
            $this->db->where('id', $data['show']['id'])->update('booking', array(
                'timeoutsite' => $this->booking->tissme_now()
            ));
        else
            $this->db->where('id', $data['show']['id'])->update('booking', array(
                'timeoutsite' => ''
            ));

        $this->session->set_flashdata('msg', 'تم          التحديث بفضل الله !');
        // /$this->load->view('../controllers/bills/views/show/printidout', $data);
        redirect(base_url() . 'dashboard');
    }

    public function upload_file($id) {
        $query = $this->db->get_where('booking', array(
            'id' => $id
        ));
        $data['show'] = $query->row_array();

        $query = $this->db->get_where('booking_clints', array(
            'cid' => $data['show']['cid']
        ));
        $clints = $query->row_array();
        $this->load->library('upload');
        $file1 = $clints['file1'];
        $fieldname = 'file1';
        if ($_FILES[$fieldname]['name'] != "") {
            if ($clints['file1'])
                unlink($file1);
            $upload_data = $this->booking->upload_many_photos($fieldname, $clints['cid'] . '1');
            $file1 = "upload/" . $upload_data["file_name"];
        }
        // sleep(31);
        $file2 = $clints['file2'];
        $fieldname2 = 'file2';
        if ($_FILES[$fieldname2]['name'] != "") {
            if ($clints['file2'])
                unlink($file2);
            $upload_data = $this->booking->upload_many_photos($fieldname2, $clints['cid'] . '2');
            $file2 = "upload/" . $upload_data["file_name"];
        }

        $edit_data = array(
            'file1' => $file1,
            'file2' => $file2
        );
        $edit_data = $this->security->xss_clean($edit_data);
        $result = $this->db->where('id', $clints['id'])->update('booking_clints', $edit_data);

        $this->session->set_flashdata('msg', 'تم   رفع الاثبات  بفضل الله!');

        redirect(base_url() . 'dashboard');
    }

    // =====================================================
    function setting() {
        // echo date('Y-m-d H:i:s');die;
        if (empty($this->session->userdata("is_admin_login"))) {
            redirect("auth/login", "refresh");
        }
        if (!get_ap('setting', $this->operator_id) == 1) {
            redirect("", "refresh");
        }
        //$email = $this->session->userdata("admin")['email'];
        if ($this->input->server("REQUEST_METHOD") == "POST") {
            $datas = $this->input->post();
            $company_title = $this->input->post('company_title');
            $company_address = $this->input->post('company_address');
            $company_mobile = $this->input->post('company_mobile');
            $company_email = $this->input->post('company_email');
            $currency = $this->input->post('currency');
            $meta_title = $this->input->post('meta_title');
            $meta_description = $this->input->post('meta_description');
            $meta_keyword = $this->input->post('meta_keyword');
            $datas['update_on'] = date('Y-m-d h:m:sa');
            $sett = $this->db->get('setting')->row();
            if ($sett && $sett->tab_logo) {
                $tab_logo = $sett->tab_logo;
                $invoice_logo = $sett->invoice_logo;
            }

            $this->load->library('upload');
            $dataInfo = array();
            $files = $_FILES;
            if ($_FILES['profile']['name']) {
                $_FILES['userfile']['name'] = $files['profile']['name'];
                $_FILES['userfile']['type'] = $files['profile']['type'];
                $_FILES['userfile']['tmp_name'] = $files['profile']['tmp_name'];
                $_FILES['userfile']['error'] = $files['profile']['error'];
                $_FILES['userfile']['size'] = $files['profile']['size'];
                $this->upload->initialize($this->set_upload_options());
                $this->upload->do_upload();
                $dataInfo = $this->upload->data();
                $datas['tab_logo'] = $dataInfo['file_name'];
                $tab_logo = $dataInfo['file_name'];
            }

            if (isset($datas['tab_logo'])) {

                if ($sett && $sett->tab_logo) {
                    @unlink('./public/upload/userimage/' . $sett->tab_logo);
                }
            }

            /// ========== Company LOGO ==========================
            if ($_FILES['logo']['name']) {
                $_FILES['userfile']['name'] = $files['logo']['name'];
                $_FILES['userfile']['type'] = $files['logo']['type'];
                $_FILES['userfile']['tmp_name'] = $files['logo']['tmp_name'];
                $_FILES['userfile']['error'] = $files['logo']['error'];
                $_FILES['userfile']['size'] = $files['logo']['size'];
                $this->upload->initialize($this->set_upload_options());
                $this->upload->do_upload();
                $dataInfo = $this->upload->data();
                $datas['invoice_logo'] = $dataInfo['file_name'];
                $invoice_logo = $dataInfo['file_name'];
            }


            if (isset($datas['invoice_logo'])) {

                if ($sett && $sett->invoice_logo) {
                    @unlink('./public/upload/userimage/' . $sett->invoice_logo);
                }
            }


            $res = $this->db->get('setting')->result();
            if (empty($res)) {
                $d = $this->db->insert('setting', $datas);
            } else {
                $this->db->where('setting_id', 1);
                $d = $this->db->update('setting', $datas);
            }

            $data = '<?php defined("BASEPATH") OR exit("Can we together ?");
$config["company_title"] ="' . $company_title . '";
$config["company_fav"] = "' . @$company_fav . '";
$config["company_address"] = "' . $company_address . '";
$config["company_mobile"] = "' . $company_mobile . '";
$config["company_email"] = "' . $company_email . '";
$config["currency"] = "' . $currency . '";
$config["meta_title"] = "' . $meta_title . '";
$config["meta_description"] = "' . $meta_description . '";
$config["meta_keyword"] = "' . $meta_keyword . '";
$config["tab_logo"] = "' . $tab_logo . '";
$config["invoice_logo"] = "' . $invoice_logo . '";';
            file_put_contents("application/config/custom.php", $data);
            $this->session->set_flashdata('message', 'Successfully Updated');
            redirect('dashboard/setting', 'refresh');
        }
        $data['title'] = $this->lang->line('setting');
        $data['sett'] = $this->db->get('setting')->row();
        // $data['view'] = '../controllers/bills/views/setting/setting';
        $data['thispage'] = 'dashboard';
        $this->load->view('site/setting/setting', $data);
    }

    function invoice_footer() {
        if (empty($this->session->userdata("is_admin_login"))) {
            redirect("auth/login", "refresh");
        }
        if (!get_ap('setting', $this->operator_id) == 1) {
            redirect("", "refresh");
        }
        //$email = $this->session->userdata("admin")['email'];
        if ($this->input->server("REQUEST_METHOD") == "POST") {
            $datas = $this->input->post();

            $res = $this->db->get('setting')->result();
            if (empty($res)) {
                $d = $this->db->insert('setting', $datas);
            } else {
                $this->db->where('setting_id', 1);
                $d = $this->db->update('setting', $datas);
            }

            $this->session->set_flashdata('message', 'Successfully Updated');
            redirect('dashboard/invoice_footer', 'refresh');
        }
        $data['title'] = $this->lang->line('setting');
        $data['sett'] = $this->db->get('setting')->row();
        // $data['view'] = '../controllers/bills/views/setting/setting';
        $data['thispage'] = 'dashboard';
        $this->load->view('site/setting/invoice_footer_settings', $data);
    }

    function social_links() {
        if (empty($this->session->userdata("is_admin_login"))) {
            redirect("auth/login", "refresh");
        }
        if (!get_ap('setting', $this->operator_id) == 1) {
            redirect("", "refresh");
        }
        //$email = $this->session->userdata("admin")['email'];
        if ($this->input->server("REQUEST_METHOD") == "POST") {
            $datas = $this->input->post();

            $res = $this->db->get('setting')->result();
            if (empty($res)) {
                $d = $this->db->insert('setting', $datas);
            } else {
                $this->db->where('setting_id', 1);
                $d = $this->db->update('setting', $datas);
            }

            $this->session->set_flashdata('message', 'Successfully Updated');
            redirect('dashboard/social_links', 'refresh');
        }
        $data['title'] = $this->lang->line('setting');
        $data['sett'] = $this->db->get('setting')->row();
        // $data['view'] = '../controllers/bills/views/setting/setting';
        $data['thispage'] = 'dashboard';
        $this->load->view('site/setting/social_links', $data);
    }

    function update() {
        if (empty($this->session->userdata("is_admin_login"))) {
            redirect("auth/login", "refresh");
        }
        if (!get_ap('setting', $this->operator_id) == 1) {
            redirect("", "refresh");
        }

        $data['title'] = $this->lang->line('setting');
        $data['sett'] = $this->db->get('setting')->row();
        // $data['view'] = '../controllers/bills/views/setting/setting';
        $data['thispage'] = 'dashboard';
        $this->load->view('site/setting/update', $data);
    }

    function sms_settings() {
        if (empty($this->session->userdata("is_admin_login"))) {
            redirect("auth/login", "refresh");
        }
        if (!get_ap('setting', $this->operator_id) == 1) {
            redirect("", "refresh");
        }
        if ($this->input->post()) {
            $this->form_validation->set_rules('sms_token', 'Token', 'trim|required|callback_check_token');
            if ($this->form_validation->run() !== FALSE) {
                $datas = $this->input->post();

                $res = $this->db->get('setting')->result();
                if (empty($res)) {
                    $d = $this->db->insert('setting', $datas);
                } else {
                    $this->db->where('setting_id', 1);
                    $d = $this->db->update('setting', $datas);
                }

                $this->session->set_flashdata('message', 'Successfully Updated');
                redirect('dashboard/sms_settings', 'refresh');
            }
        }

        $data['title'] = $this->lang->line('setting');
        $data['sett'] = $this->db->get('setting')->row();
        if ($data['sett']->sms_token) {
            $data['client_data'] = $this->get_token_data($data['sett']->sms_token);
        }
        // $data['view'] = '../controllers/bills/views/setting/setting';
        $data['thispage'] = 'dashboard';
        $this->load->view('site/setting/sms_settings', $data);
    }

    function save_send_sms_settings() {
        $datas = $this->input->post();

        $new_order = $in_delivery = $order_canceled = $order_preparing = $order_delivered = $payment_msg = $pay_orders = 0;

        if (isset($datas['sms_on_new_order'])) {
            $new_order = 1;
        }
        if (isset($datas['sms_on_in_delivery'])) {
            $in_delivery = 1;
        }
        if (isset($datas['sms_on_order_canceled'])) {
            $order_canceled = 1;
        }
        if (isset($datas['sms_on_preparing'])) {
            $order_preparing = 1;
        }
        if (isset($datas['sms_on_delivered'])) {
            $order_delivered = 1;
        }
        if (isset($datas['sms_on_payment_msg'])) {
            $payment_msg = 1;
        }
        if (isset($datas['sms_on_pay_orders'])) {
            $pay_orders = 1;
        }
        $inserted = array('sms_on_new_order' => $new_order, 'sms_on_in_delivery' => $in_delivery, 'sms_on_order_canceled' => $order_canceled,
            'sms_on_preparing' => $order_preparing, 'sms_on_delivered' => $order_delivered,
            'sms_on_payment_msg' => $payment_msg, 'sms_on_pay_orders' => $pay_orders);

        $res = $this->db->get('setting')->result();
        if (empty($res)) {
            $d = $this->db->insert('setting', $inserted);
        } else {
            $this->db->where('setting_id', 1);
            $d = $this->db->update('setting', $inserted);
        }

        $this->session->set_flashdata('message', 'Successfully Updated');

        redirect('dashboard/sms_settings', 'refresh');
    }

    function save_sms_template() {
        $inserted = array($this->input->post('type') . '_sms_content' => trim(str_replace(PHP_EOL, '%0a', $this->input->post('msg_content'))));
        $res = $this->db->get('setting')->result();
        if (empty($res)) {
            $d = $this->db->insert('setting', $inserted);
        } else {
            $this->db->where('setting_id', 1);
            $d = $this->db->update('setting', $inserted);
        }

        $this->session->set_flashdata('message', 'Successfully Updated');
        redirect('dashboard/sms_settings', 'refresh');
    }

    function check_token($token) {
        if (!$this->config->item('sms_system_url')) {
            $this->form_validation->set_message('check_token', 'Your system is not configured, please contact the vendor');
            return FALSE;
        }
        $response = send_request($this->config->item('sms_system_url') . '/api/main/checkToken', array('token' => $token), 'post');
        if ($response) {
            return TRUE;
        }
        $this->form_validation->set_message('check_token', $this->lang->line('wrong_token'));
        return FALSE;
    }

    function get_token_data($token) {
        $response = send_request($this->config->item('sms_system_url') . '/api/main/checkToken', array('token' => $token), 'post');
        if ($response) {
            return $response;
        }
        return FALSE;
    }

    private function set_upload_options() {
        // upload an image options
        $config = array();
        $config['upload_path'] = './public/upload/userimage/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '0';
        $config['overwrite'] = FALSE;
        return $config;
    }

}

?>