<?php

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

class Ho_controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // Your own constructor code
        $this->load->model('pos_model');
        $this->load->model('business_model');
        $this->load->model('customer_model');
        $this->load->model('order_model');
        $this->load->model('invoice_model');
        $this->load->model('visits_model');
        $this->load->model('staff_model');
        $this->load->model('scheduler_model');
         $this->load->model('packages_model');
        $this->load->model('service_model');
        $this->load->model('accounting_model');
        $this->load->model('ho_model');
        $this->load->model('dispatch_model');

        if ($this->session->userdata('role') == '') {
            redirect('logout');
        }
    }
    
    public function index() {
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            
            checkroles(0, 0, 1);

            $data['nav'] = 'ho_view';

            //$data['menu'] = 'hidden';
            
            $data['user_role'] = $this->session->userdata('role');
            $data['business'] = $this->business_model->getbusinessdetails();
            
            
            $this->load->view('includes/header', $data);
            $this->load->view('ho/ho_view');
            $this->load->view('includes/footer');
            
        }
    }
    
    public function period_booking_list(){
       // exit();
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {

                //storemanager,hr,reception...user serial
           checkroles(0,0,1);

           $data['nav'] = 'invoice';
           $data['subnav'] = 'bookings';
        
           
           //if($this->input->post('filterbookingdate'))
           
                   
           $data['packagetypes'] = $this->ho_model->get_package_types();
           $data['bookingfor'] = $this->ho_model->get_package_categories();
           //var_dump($data['bookingfor']);exit();
           $data['business'] = $this->business_model->get_all_branches();

           $data['bookings'] = $this->ho_model->getbookings();
           
           
            $data['bookingid'] = $this->input->post('filterbookingid');
            $data['advanceamount'] = $this->input->post('advanceamount');
            $data['customer'] = $this->input->post('filtercustomer');
            $data['customercell'] = $this->input->post('filtercustomercell');
            $data['filterpackagetype'] = $this->input->post('filterpackage');
            $data['filterpackagecategory'] = $this->input->post('filterbookingfor');
           
           
           $data['bookingstartdate']= $this->input->post('bookingstartdate');
           $data['bookingenddate']= $this->input->post('bookingenddate');
           
           $data['visitstartdate']= $this->input->post('visitstartdate');
           $data['visitenddate']= $this->input->post('visitenddate');
           
           $this->load->view('includes/header', $data);
           $this->load->view('ho/period_booking_list');
           $this->load->view('includes/footer');
        }
    }
    
    public function period_booking(){
        
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {

            $data['nav'] = 'scheduler';
            $data['scheduler_style'] = $this->business_model->getbusinessdetails();
            $data['user_role'] = $this->session->userdata('role');
           // $data['staff_list'] = $this->ho_model->staff_list();
            
            //$this->load->model('customer_model');
            $data['city_areas'] = $this->customer_model->get_city_areas(1);
            
            $this->load->view('includes/header', $data);
            $this->load->view('ho/period_booking');
            $this->load->view('includes/footer');    
        }
    }
    
    public function get_active_staff(){
        
        $data = $this->ho_model->get_active_staff();
        echo (json_encode($data));
        die;
        
    }
    
     public function get_package_types(){
        $data = $this->ho_model->get_package_types();
        echo (json_encode($data));
        die;
        
    }
    
    public function get_package_category(){
        
        $ptype = $this->input->post('package_type_id');
        
        $data = $this->ho_model->get_package_category($ptype);
        echo (json_encode($data));
        die;
        
    }
    
    public function create_booking(){

        if(null==$this->input->post('customer_id') || $this->input->post('customer_id')=='' || $this->input->post('customer_id')==0){
            echo ('error|Missing Customer');
        } else {
            $data=$this->ho_model->create_booking();
            
            $d = explode("|", $data);
            $visit_id=$d[2];
            //print_r($d);
            //echo $visit_id;
            //Dispatch Requests
            if(AUTODISPATCH == true){
                $dispatch_requests = $this->dispatch_model->add_dispatch_request($visit_id);
            }
            
            
            echo($data);
        }
        
    }
    
    public function create_dynamic_booking(){

        if(null==$this->input->post('customer_id') || $this->input->post('customer_id')=='' || $this->input->post('customer_id')==0){
            echo ('error|Missing Customer');
        } else {
            $data=$this->ho_model->create_dynamic_booking();
            
            $d = explode("|", $data);
            $visit_id=$d[2];
            //print_r($d);
            //echo $visit_id;
            //Dispatch Requests
            if(AUTODISPATCH == true){
                $dispatch_requests = $this->dispatch_model->add_dispatch_request($visit_id);
            }
            
            
            echo($data);
        }
        
    }
    
    public function print_booking($bookingid){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'invoice';
            //Get Visits
            $data['visits']=$this->ho_model->getavisitsbybookingid($bookingid);
           
            
            $data['business']=$this->business_model->getbusinessdetails();
            $data['category'] = $this->ho_model->get_package_category($data['visits'][0]['id_package_type']);
            
            
            
            if($data['visits']){
                


                $data['menu'] = 'hidden';

                $this->load->view('includes/header', $data);
                $this->load->view('ho/print_booking_view');
                $this->load->view('includes/footer');

            } else{
                echo 'Booking not found!';
            }
        }
        
    }
    
    
    public function list_package_types(){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            //storemanager,hr,reception...user serial
            checkroles(0, 0, 0);

            $data['nav'] = 'my_business';
            $data['subnav'] = 'package_types';
            $data['packages_type'] = $this->ho_model->get_all_package_types();

            $this->load->view('includes/header', $data);
            $this->load->view('ho/settings/packages_type_view');
            $this->load->view('includes/footer');
        }
        
    }
    
    public function list_package_category($package_type_id){
       if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'my_business';
            $data['subnav'] = 'package_types';
            $data['packages_category'] = $this->ho_model->get_package_category($package_type_id);

            $data['businesses'] = $this->business_model->get_all_businesses();
            $data['package_type_id']=$package_type_id;

            $this->load->view('includes/header', $data);
            $this->load->view('ho/settings/packages_category_view');
            $this->load->view('includes/footer');
        }
    }
    
    public function package_category_image() {
        $this->load->model('packages_model');
        if ($this->input->post('id_package_cat_image', TRUE) && $this->input->post('id_package_cat_image', TRUE) != "") {
            $image = "";
            if ($_FILES['package_cat_image']['name'] && $_FILES['package_cat_image']['name'] != "") {
                $image = $this->image_upload('images/category', 'package_cat_image', 'gif|jpg|png');
                if ($image == FALSE) {
                    $this->session->set_flashdata('errorimage', 'The image dimension must be 128 X 128');
                    redirect(base_url('package/category' . '/' . $this->input->post('id_package_type_image')));
                } else {
                    $image = $image;
                }
            } else {
                $image = ($this->input->post('org_image', TRUE) != "" ? $this->input->post('org_image', TRUE) : NULL);
            }

            $result = $this->packages_model->package_category_image($image);
            if ($result) {
                redirect(base_url('ho_list_package_category' . '/' . $this->input->post('id_package_type_image')));
            }
        }
    }
    
    public function add_package_category() {
        $result = $this->ho_model->add_package_category();
        echo('success|' . $result);
    }
    
    public function edit_package_category(){
        $data = $this->ho_model->edit_package_category();
        echo (json_encode($data));
       
    }
    
     public function ho_list_package_services($package_type_id) {
         if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            //storemanager,hr,reception...user serial
            checkroles(0, 0, 0);

             $this->load->model('packages_model');

             

            $data['nav'] = 'my_business';
            $data['subnav'] = 'package_types';
            $data['packages_service'] = $this->packages_model->get_package_service($package_type_id);
            $data['business_service'] = $this->packages_model->get_business_service($data['packages_service'][0]['business_id']);
            $data['package_category'] = $this->packages_model->get_package_list_category();

            $this->load->view('includes/header', $data);
            $this->load->view('setting/packages_service_view');
            $this->load->view('includes/footer');
        }
    }
    
     function image_upload($folder = NULL, $image = NULL, $type = NULL, $width = NULL, $height = NULL, $encrypt = NULL) {
        $config['upload_path'] = 'assets/' . $folder . '/';
        $config['allowed_types'] = $type;
        $config['max_size'] = '2048';

        if ($width != NULL && $height != NULL) {
            $config['max_width'] = $width;
            $config['max_height'] = $height;
        }
        if ($encrypt != NULL) {
            $config['encrypt_name'] = TRUE;
        }

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

        if (!$this->upload->do_upload($image)) {
            return FALSE;
        } else {
            return $this->upload->data('file_name');
        }
    }
    
     public function change_visit_services_date(){
    
        $visit_service_date = $this->input->post('visit_service_date'); 
        $visit_service_ids =  $this->input->post('visit_service_ids'); 
        $customer_visit_id = $this->input->post('customer_visit_id'); 
        
        foreach($visit_service_ids as $visit_service_id){
            
            $result = $this->ho_model->change_date($visit_service_date, $visit_service_id, $customer_visit_id);
            
        }
        echo "success|";
        exit;
    }
    
    function cancelBooking() {

        $bookingid = htmlspecialchars($this->input->post('bookingid', TRUE));

        $update = $this->ho_model->cancelBooking($bookingid);

        echo $update;
    }
    
    function period_booking_report($start=null, $end=null, $staff=null){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {

            if($start==null){
                $start=$this->input->post('start');
                $end=$this->input->post('end');
                $staff=$this->input->post('staff');
            }
           //storemanager,hr,reception...user serial
           checkroles(0,0,1);

           $data['nav'] = 'invoice';
           $data['subnav'] = 'agentbookings';

           
           if(null !==$this->input->post('staff', TRUE)){
                $data['selecteduser'] = $this->input->post('staff', TRUE);
            } else {
                $data['selecteduser'] = "All";
            }
            
           $this->load->model('user_model');
           $data['users'] = $this->user_model->get_visible_users();
           $data['bookings'] = $this->ho_model->booking_report($start,$end,$staff);
           $data['start']=$start;
           $data['end']=$end;
           $this->load->view('includes/header', $data);
           $this->load->view('ho/period_booking_report');
           $this->load->view('includes/footer');
        }
    }

    public function ho_dashboard(){
    
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {

            if($this->input->post('start') != null){
                $start=$this->input->post('start');
                $end=$this->input->post('end');                
            }else{
                $end=date('Y-m-d');
                $start=date('Y-m-d', strtotime('-30 days',strtotime($end)));
            }
           //storemanager,hr,reception...user serial
           checkroles(0,0,1);

           $data['nav'] = 'reports';
           $data['subnav'] = 'ho_dashboard';
    
           $data['start']=$start;
           $data['end']=$end;

            $sql="SELECT id_business, business_name, 
            ROUND(sum(ServiceSale),2) as 'Service Sale Income',
            ROUND(sum(RetailSale),2) as 'Retail Sale Income',
            ROUND(sum(TrainingSale),2) as 'Training Sale Income',
            ROUND(sum(ServiceSale) + sum(RetailSale) + sum(TrainingSale)) as 'Gross Income',
            ROUND(sum(Discount),2) as 'Discount', 
            ROUND(sum(RoundAdj),2) as 'Rounding Adjustment',
            ROUND(sum(ServiceSale) + sum(RetailSale) + sum(TrainingSale)) - ROUND(sum(Discount),2) + ROUND(sum(RoundAdj),2) as 'Net Income',
            ROUND(sum(Cash),2) as Cash, 
            ROUND(sum(Card),2) as Card, 
            ROUND(sum(Bank),2) as 'Check',
            ROUND(sum(Voucher),2) as 'Voucher Used',
            ROUND(SUM(AdvAdj),2) as 'Advance Adjusted',
            ROUND(SUM(Advance),2) as 'Advance Collected',
            ROUND(sum(balance),2) as 'Receivable',
            ROUND(sum(sales_tax),2) as 'Sales Tax Collected',
            ROUND(sum(cc_fee),2) as 'CC Fee',
            ROUND(sum(retained),2) as 'Retained',
            ROUND(sum(retained_used),2) as 'Retained Used',
            (sum(ServiceSale)+sum(RetailSale)+SUM(TrainingSale)+sum(sales_tax)+sum(cc_fee))-sum(Discount) as collectable,
            (sum(Cash)+sum(Card)+sum(Bank)+sum(balance))-sum(AdvAdj) as collected
            FROM 
            (
                SELECT id_business, business_name,
                CASE WHEN entity_name = 'paid_cash' THEN debit ELSE 0 END as 'Cash',
                CASE WHEN entity_name = 'paid_card' THEN debit ELSE 0 END as 'Card',
                IF(entity_name = 'paid_check', debit, 0) as 'Bank',
                IF(entity_name = 'paid_voucher', debit, 0) as 'Voucher',	
                IF(entity_name = 'balance', balance, 0) as 'balance',
                IF(entity_name = 'advance_adjusted' || entity_name = 'retained_amount_used', debit, 0) as 'AdvAdj',
                IF(entity_name = 'advance_amount', credit, 0) as 'Advance',    
                IF(entity_name = 'grosstotal_service', balance * -1, 0) as 'ServiceSale',
                IF(entity_name = 'grosstotal_retail', balance * -1, 0) as 'RetailSale',
                IF(entity_name = 'grosstotal_training', balance * -1, 0) as 'TrainingSale',
                IF(entity_name = 'rounded_adjustment', balance * -1, 0) as 'RoundAdj',
                IF(entity_name = 'sale_discount_service' || entity_name = 'sale_discount_retail', balance, 0) as 'Discount',
                IF(entity_name = 'sales_tax', balance*-1, 0) as 'sales_tax',
                IF(entity_name = 'cc_fee', balance*-1, 0) as 'cc_fee',
                IF(entity_name = 'retained_amount', balance*-1, 0) as 'retained',
                IF(entity_name = 'retained_amount_used', balance*-1, 0) as 'retained_used'
                FROM
                (
                        SELECT id_business, business_name, 
                            account_voucher_detail.account_head_id,
                            account_heads.account_head, 
                            account_event_mapping.entity_name,
                            ROUND(SUM(debit),2) as debit, 
                            ROUND(SUM(credit),2) as credit,
                            ROUND(SUM(debit),2) - ROUND(SUM(credit),2) as balance
                        FROM account_vouchers 
                        JOIN account_voucher_detail on account_vouchers.id_account_vouchers = account_voucher_detail.account_voucher_id
                        JOIN business on account_vouchers.business_id = business.id_business and business.common_products='Yes'
                        JOIN account_heads on id_account_heads=account_voucher_detail.account_head_id
                        JOIN (
                            select business_id, account_head_id, entity_name
                                from account_event_mapping where account_event_id in (1, 2)
                                group by entity_name, business_id
                                ) as account_event_mapping 
                                on account_event_mapping.business_id = account_vouchers.business_id 
                                and  account_heads.id_account_heads = account_event_mapping.account_head_id         
                            WHERE voucher_status = 'Active'
                            AND date(voucher_date)>='".$start."'
                            AND date(voucher_date)<='".$end."'
                        GROUP BY account_vouchers.business_id, account_head_id, entity_name
                ) as A
            ) as B
            GROUP BY id_business";
            $query= $this->db->query($sql);
            $data['details']=$query->result_array();

           $this->load->view('includes/header', $data);
           $this->load->view('ho/reports/ho_dashboard');
           $this->load->view('includes/footer');
        }


    }


}