<?php

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

class Pos_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('accounting_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('service_model');
        $this->load->model('sms_model');
        $this->load->model('eyelashes_model');
        $this->load->model('colors_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->session->userdata('businessid') == '') {
            redirect('logout');
        } else {
            
            checkroles(0, 0, 1);

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

            //$data['menu'] = 'hidden';
            
            
            $data['nodatatable']='nodatatable';
            
            if(null!==$this->input->post('id_customer_order')){
                if($this->input->post('id_customer_order')!==''){
                    $data['id_customer_order']=$this->input->post('id_customer_order');
                }               
            }
            
            if(null!==$this->input->post('customerid')){
                if($this->input->post('customerid')!==''){
                    $data['id_customer']=$this->input->post('customerid');
                }
            }
            
            $data['user_role'] = $this->session->userdata('role');
            $data['userid'] = $this->session->userdata('userid');
            $data['username'] = $this->session->userdata('fullname');

            $data['business'] = $this->business_model->getbusinessdetails();
            $data['taxes'] = $this->business_model->getbusinesstaxes('sale');

            $data['staff_list'] = $this->staff_model->business_staff($this->session->userdata('businessid'));
            
            $data['orders'] = $this->order_model->get_open_orders();

            $data['totalinvoices'] = $this->invoice_model->get_day_retail_count();
            
            //echo (TRACK_INVENTORY); exit();
            
            if(TRACK_INVENTORY==TRUE){
                $this->load->view('includes/header', $data);
                $this->load->view('pos_view');
            }else{
                
                $data['products'] = $this->pos_model->get_untracked_products();
                $this->load->view('includes/header', $data);
                $this->load->view('pos_view');
            }
            $this->load->view('includes/footer');
        }
    }

    function search_untracked_products(){
    
        $data = $this->pos_model->search_untracked_products();
        echo json_encode($data);
        
    }
    
    
    function pos_services() {
        //exit();
        if ($this->session->userdata('role') == '' || $this->session->userdata('role')=='Sh-Users' || $this->session->userdata('businessid')== '') {
            redirect('logout');
        } else {
            checkroles(0, 0, 1);

          //  $data['nav'] = 'pos_view';

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

            
            $data['user_role'] = $this->session->userdata('role');
            $data['userid'] = $this->session->userdata('userid');
            $data['username'] = $this->session->userdata('fullname');

            $data['business'] = $this->business_model->getbusinessdetails();
            $data['taxes'] = $this->business_model->getbusinesstaxes('service');

            $data['staff_list'] = $this->scheduler_model->staff_list();

            $data['visits'] = $this->visits_model->open_visit_list();
            $data['inservice'] = $this->visits_model->inservice_visit_list();

            $data['type_list'] = $this->service_model->get_active_types();
            $data['category_list'] = $this->service_model->get_active_categories();
            $data['services_list'] = $this->service_model->get_active_services();

            $data['package_type_list'] = $this->service_model->get_active_package_types();
            $data['package_category_list'] = $this->service_model->get_active_package_categories();
            $data['package_services_list'] = $this->service_model->get_active_package_services();

            $data['totalinvoices'] = $this->invoice_model->get_day_services_count();
            // $data['visit_last_color'] = $this->scheduler_model->getLastVisitColor($start, $end);
            //Adding shifts to scheduler
            if (null !== $data['business'][0]['shifts'] && $data['business'][0]['shifts'] === 'Y') {
                $data['time'] = $this->business_model->get_shift_timing();
            } else {
                $data['time'] = $this->business_model->get_business_timing();
            }
                        
            /////Server side data////
             if(null!==$this->input->post('id_customer_visit') && $this->input->post('id_customer_visit')!==''){
                $data['id_customer_visit']=$this->input->post('id_customer_visit');

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

                $data['openvisit'] = $this->visits_model->getopenvisitbyid($visitid);
                $data['openvisitservices'] = $this->visits_model->getvisitservices($visitid);
                $data['openvisitstaffs'] = $this->visits_model->getvisitstaffs($visitid);
                $data['openvisitadvances'] = $this->visits_model->getopenvisitadvancebyid($visitid);
                $data['openvisitserviceproducts'] = $this->visits_model->getvisitserviceproducts($visitid);

                $data['serviceproducts'] = array();
                foreach ($data['openvisitservices'] as $service) {
                   array_push($data['serviceproducts'], $this->service_model->get_services_products_byid($service['id_business_services']));
                }
            }
            
            if(null!==$this->input->post('customerid')){
                 if($this->input->post('customerid')!==''){
                    $data['id_customer']=$this->input->post('customerid');
                 }
            }
            //////////////
            
            $data['discount_types'] = $this->invoice_model->get_discounttypes();
            $data['color_type_list'] = $this->colors_model->color_type_list();
            $data['color_numbers'] = $this->colors_model->get_all_color_number();
            $data['eyelashtypes'] = $this->eyelashes_model->eyelash_type_list();
            $data['WaterContent'] = $this->colors_model->get_WaterContent();
            
            
            $this->load->view('includes/header', $data);
            $this->load->view('pos_services_view');
            $this->load->view('includes/footer');
        }
    }

    function get_open_visit(){
        if ($this->session->userdata('role') == '') {
            echo json_encode('error','sessionexpired');
        } else {
            $data['visits'] = $this->visits_model->open_visit_list();
            $data['inservice'] = $this->visits_model->inservice_visit_list();
            echo json_encode($data);
        }
    }
    
    function get_customer_visit(){
        
        if ($this->session->userdata('role') == '') {
            echo json_encode('error','sessionexpired');
        } else {
            /////Server side data////
            if(null!==$this->input->post('id_customer_visit')){
               if($this->input->post('id_customer_visit')!==''){
                   $data['id_customer_visit']=$this->input->post('id_customer_visit');
               }
               $visitid = htmlspecialchars($this->input->post('id_customer_visit', TRUE));

               $data['openvisit'] = $this->visits_model->getopenvisitbyid($visitid);
               $data['openvisitservices'] = $this->visits_model->getvisitservices($visitid);
               $data['openvisitstaffs'] = $this->visits_model->getvisitstaffs($visitid);
               $data['openvisitadvances'] = $this->visits_model->getopenvisitadvancebyid($visitid);
               $data['openvisitserviceproducts'] = $this->visits_model->getvisitserviceproducts($visitid);

               $data['serviceproducts'] = array();
               foreach ($data['openvisitservices'] as $service) {
                  array_push($data['serviceproducts'], $this->service_model->get_services_products_byid($service['id_business_services']));
               }
               
               ///
               $data['color_record'] = $this->colors_model->get_color_record($visitid);
                if(count($data['color_record']) > 0){
                    $data['color_record'] = FALSE;
                } else{
                    $data['color_record'] = TRUE;
                }

            }
            echo json_encode($data);
        }
    }
    
    function pos_services_ss() {
        //exit();
        if ($this->session->userdata('role') == '') {
            redirect('logout');
        } else {
            checkroles(0, 0, 1);

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

            $data['menu'] = 'hidden';
            
            if(null!==$this->input->post('id_customer_visit')){
                if($this->input->post('id_customer_visit')!==''){
                    $data['id_customer_visit']=$this->input->post('id_customer_visit');
                }
            }
            
            if(null!==$this->input->post('customerid')){
                 if($this->input->post('customerid')!==''){
                    $data['id_customer']=$this->input->post('customerid');
                 }
            }
            
            $data['user_role'] = $this->session->userdata('role');
            $data['userid'] = $this->session->userdata('userid');
            $data['username'] = $this->session->userdata('fullname');

            $data['business'] = $this->business_model->getbusinessdetails();
            $data['taxes'] = $this->business_model->getbusinesstaxes('service');

            $data['staff_list'] = $this->scheduler_model->staff_list();

            $data['visits'] = $this->visits_model->open_visit_list();
            $data['inservice'] = $this->visits_model->inservice_visit_list();

            $data['type_list'] = $this->service_model->get_active_types();
            $data['category_list'] = $this->service_model->get_active_categories();
            $data['services_list'] = $this->service_model->get_active_services();

            $data['package_type_list'] = $this->service_model->get_active_package_types();
            $data['package_category_list'] = $this->service_model->get_active_package_categories();
            $data['package_services_list'] = $this->service_model->get_active_package_services();

            $data['totalinvoices'] = $this->invoice_model->get_day_services_count();
            // $data['visit_last_color'] = $this->scheduler_model->getLastVisitColor($start, $end);
            //Adding shifts to scheduler
            if (null !== $data['business'][0]['shifts'] && $data['business'][0]['shifts'] === 'Y') {
                $data['time'] = $this->business_model->get_shift_timing();
            } else {
                $data['time'] = $this->business_model->get_business_timing();
            }
            
            
            /////Server side data////
             if(null!==$this->input->post('id_customer_visit')){
                if($this->input->post('id_customer_visit')!==''){
                    $data['id_customer_visit']=$this->input->post('id_customer_visit');
                }
                $visitid = htmlspecialchars($this->input->post('id_customer_visit', TRUE));
                
                $data['openvisit'] = $this->visits_model->getopenvisitbyid($visitid);
                $data['openvisitservices'] = $this->visits_model->getvisitservices($visitid);
                $data['openvisitstaffs'] = $this->visits_model->getvisitstaffs($visitid);
                $data['openvisitadvances'] = $this->visits_model->getopenvisitadvancebyid($visitid);
                $data['openvisitserviceproducts'] = $this->visits_model->getvisitserviceproducts($visitid);

                $data['serviceproducts'] = array();
                foreach ($data['openvisitservices'] as $service) {
                   array_push($data['serviceproducts'], $this->service_model->get_services_products_byid($service['id_business_services']));
                }
                ///
               $data['color_record'] = $this->colors_model->get_color_record($visitid);
                if(count($data['color_record']) > 0){
                    $data['color_record'] = FALSE;
                } else{
                    $data['color_record'] = TRUE;
                }
                $data['facial_record'] = $this->colors_model->get_facial_records($visitid);
                if(count($data['facial_record']) > 0){
                    $data['facial_record'] = FALSE;
                } else{
                    $data['facial_record'] = TRUE;
                }
                $this->load->model('eyelashes_model');
                $data['eyelashes_record'] = $this->eyelashes_model->get_eyelashes_records($visitid);
                if(count($data['eyelashes_record']) > 0){
                    $data['eyelashes_record'] = FALSE;
                } else{
                    $data['eyelashes_record'] = TRUE;
                }
                
            }
            
            if(null!==$this->input->post('customerid')){
                 if($this->input->post('customerid')!==''){
                    $data['id_customer']=$this->input->post('customerid');
                 }
            }
            //////////////
            
            

            $this->load->view('includes/header', $data);
            $this->load->view('pos_services_ss');
            $this->load->view('includes/footer');
        }
    }
    
    function get_customer_details() {
        if ($this->session->userdata('role') == '') {
            echo json_encode('error','sessionexpired');
        } else {
            $customer_id = $this->input->post('customer_id');

            //Get Balance
            $data['balance'] = $this->customer_model->customerbalance($customer_id);
            $data['customer_points'] = $this->customer_model->get_customer_loyalty($customer_id);
            $data['customer_alerts'] = $this->customer_model->get_customer_alerts($customer_id);

            echo json_encode($data);
        }
    }

    function get_color_for_visit() {

        $today = date('Y-m-d\TH:i:s');

        $data['last_color_code'] = $this->pos_model->get_color_for_visit($today);
    }

    public function addvisits() {
        if ($this->session->userdata('role') == '') {
            echo 'sessionexpired';
        } else {
            $visit_id = htmlspecialchars($this->input->post('visit_id', TRUE));
            $customer_id = htmlspecialchars($this->input->post('customer_id', TRUE));
            $customer_name = htmlspecialchars($this->input->post('customer_name', TRUE));
            
            $start = htmlspecialchars($this->input->post('start', TRUE));
            $advance_remarks= htmlspecialchars($this->input->post('advance_remarks', TRUE));

            $services = $this->input->post('services');
            $products = $this->input->post('products');
            $staff = $this->input->post('staff');

            //check if staff is available
            if(AVAILABILITY==TRUE){
                $st = explode("T",$start);
                $start_time = $st[1];
                $start_time = substr($start_time,0,5);
                $newrunningtime = $start_time;
                $x=0;        
                foreach($services as $service){
                    $this_duration = explode(":", $service['service_duration']);
                    $this_hour=$this_duration[0];
                    $this_minutes=$this_duration[1];

                    $this_start_time = $newrunningtime;

                    $running_time = explode(":", $newrunningtime);
                    $running_hour = $running_time[0];
                    $running_minutes= $running_time[1];


                    $h=$running_hour+$this_hour;
                    $m= intval($running_minutes) + intval($this_minutes);
                    $newrunningtime = sprintf('%02d', $h).":".sprintf('%02d',$m);

                    $visit = $this->visits_model->check_staff_availability($staff[$x]['staff_id'], $this_start_time, $newrunningtime, $st[0]);
                    //print_r($visit);
                    if(empty($visit) == false && $visit=='failed'){
                         echo "info|Selected staff is busy in this time slot";
                        exit();
                    }
                    $workstation = $this->visits_model->check_workstation_availability($staff[$x]['staff_id'], $this_start_time, $newrunningtime, $st[0]);
                    //print_r($workstation);
                     if(empty($workstation) == false && $workstation == 'failed'){
                        echo "info|No Workstation is available in this time slot";
                        exit();
                    }
                    $x++;
                }
            }
            //print_r($services); 
            //exit();
            $customer_visit_id = $this->pos_model->add_visit($customer_id, $visit_id, $start, $advance_remarks);

            $result = $this->pos_model->add_visit_services($customer_visit_id, $customer_id, $customer_name, $services, $products, $staff, $start);

            
            //Dispatch Requests
            if(AUTODISPATCH == true){
                $dispatch_requests = $this->dispatch_model->add_dispatch_request($customer_visit_id);
            }
            
            echo "success|" . $customer_visit_id;
        }
    }

    public function updatevisitpos() {
        if ($this->session->userdata('role') == '') {
            echo 'sessionexpired';
        } else {
            $visit_id = htmlspecialchars($this->input->post('visit_id', TRUE));
            $customer_id = htmlspecialchars($this->input->post('customer_id', TRUE));
            $customer_name = htmlspecialchars($this->input->post('customer_name', TRUE));
            
            $start = htmlspecialchars($this->input->post('start', TRUE));
            $advance_remarks= htmlspecialchars($this->input->post('advance_remarks', TRUE));

            $services = $this->input->post('services');
            $products = $this->input->post('products');

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

           // $advances = $this->visits_model->getopenvisitadvancebyid($visit_id);

           // $delete = $this->pos_model->removeVisit($visit_id);


            ///New///
            //update the visit datetime
            $this->db->set('customer_visit_date', $start);
            $this->db->where('id_customer_visits', $visit_id);
            $this->db->update('customer_visits');

            $this->db->set('visit_service_status','InActive');
            $this->db->where('customer_visit_id', $visit_id);
            $this->db->update('visit_services');

            $this->db->set('visit_service_staff_status','InActive');
            $this->db->where('customer_visit_id', $visit_id);
            $this->db->update('visit_service_staffs');

            //cancel request and dispatches if any
            if(AUTODISPATCH == true){
                $dispatch_requests = $this->dispatch_model->cancel_dispatch_request(0, $visit_id);
            }

            $result = $this->pos_model->add_visit_services($visit_id, $customer_id, $customer_name, $services, $products, $staff, $start);
            
            //New Dispatch Requests
            if(AUTODISPATCH == true){
                $dispatch_requests = $this->dispatch_model->add_dispatch_request($visit_id);
            }
                
            echo "success|" . $visit_id;

            ///New End///


            //cancel request and dispatches if any
            // if(AUTODISPATCH == true){
            //     $dispatch_requests = $this->dispatch_model->cancel_dispatch_request(0, $visit_id);
            // }

            // $customer_visit_id = $this->pos_model->add_visit($customer_id, 0, $start, $advance_remarks);
            
            // if($customer_visit_id>0){
            //     $result = $this->pos_model->add_visit_services($customer_visit_id, $customer_id, $customer_name, $services, $products, $staff, $start);
                
            //     //Dispatch Requests
            //     if(AUTODISPATCH == true){
            //         $dispatch_requests = $this->dispatch_model->add_dispatch_request($customer_visit_id);
            //     }
                
            // }
            
            // if(sizeof($advances)>0){
            //     $result = $this->pos_model->move_advance($visit_id, $customer_visit_id);
            // }

            // //move advance voucher
            // $this->db->set('visit_id', $customer_visit_id);
            // $this->db->set('voucher_status', 'Active');
            // $this->db->where('visit_id', $visit_id);
            // $this->db->where("ifnull(visit_advance_id,'')!=", "");
            // $this->db->update('account_vouchers');
            
            
            // echo "success|" . $customer_visit_id;
        }
    }

    function getVisitbyid($anybusiness=false) {
        
        if(null !== $this->input->post('anybusiness', TRUE)){
            $anybusiness = $this->input->post('anybusiness', TRUE);
        }
        
        
        if ($this->session->userdata('role') == '') {
            $data['error']= 'sessionexpired';
            echo json_encode($data);
        } else {
            
            $data['result']='';
            
            if(null !== $this->input->post('id_customer_visit', TRUE) && $this->input->post('id_customer_visit', TRUE)!==''){
                
                $previousopenvisit=[];
                $visitid=$this->input->post('id_customer_visit', TRUE);
                $customer_id=null;
                
            } else if(null !== $this->input->post('customer_id', TRUE) && $this->input->post('customer_id', TRUE)!=='') {
                
                $previousopenvisit = $this->visits_model->getpassedvisitbycid();
                if(sizeof($previousopenvisit)>0){
                    $visitid = $previousopenvisit[0]['id_customer_visits'];
                }else {
                    $visitid = 0;
                }
                $customer_id=$this->input->post('customer_id', TRUE);
                
            } else {
                $data['error']= 'customer id not received';
                echo json_encode($data);
                exit();
            }
            
            
            if(sizeof($previousopenvisit)>0 || $visitid>0){
                $data['result']='found';
                if($visitid>0){
                    //$visitid = htmlspecialchars($this->input->post('id_customer_visit', TRUE));

                    if($anybusiness==false){
                        $data['visits'] = $this->visits_model->getopenvisitbyid($visitid);
                    } else {
                        $data['visits'] = $this->visits_model->getopenvisitbyid($visitid, true);
                    }
                    
                    if(null == $customer_id){
                        $customer_id = $data['visits'][0]['customer_id'];                        
                    }
                    
                    
                    $data['services'] = $this->visits_model->getvisitservices($visitid);
                    $data['staffs'] = $this->visits_model->getvisitstaffs($visitid);
                    $data['advances'] = $this->visits_model->getopenvisitadvancebyid($visitid);
                    $data['visitserviceproducts'] = $this->visits_model->getvisitserviceproducts($visitid);
                    $data['discount_types'] = $this->invoice_model->get_discounttypes();

                    //Get Balance
                    $data['balance'] = $this->customer_model->customerbalance($customer_id);
                    $data['customer_points'] = $this->customer_model->get_customer_loyalty($customer_id);
                    $data['customer_alerts'] = $this->customer_model->get_customer_alerts($customer_id);
                    ///
                    
                    $data['serviceproducts'] = array();
                    foreach ($data['services'] as $service) {
                       array_push($data['serviceproducts'], $this->service_model->get_services_products_byid($service['id_business_services']));
                    }
                      ///
                    $data['color_record'] = $this->colors_model->get_color_record($visitid);
                    if(count($data['color_record']) > 0){
                        $data['color_record'] = FALSE;
                    } else{
                        $data['color_record'] = TRUE;
                    }
                    $data['facial_record'] = $this->colors_model->get_facial_records($visitid);
                    if(count($data['facial_record']) > 0){
                        $data['facial_record'] = FALSE;
                    } else{
                        $data['facial_record'] = TRUE;
                    }
                    $this->load->model('eyelashes_model');
                    $data['eyelashes_record'] = $this->eyelashes_model->get_eyelashes_records($visitid);
                    if(count($data['eyelashes_record']) > 0){
                        $data['eyelashes_record'] = FALSE;
                    } else{
                        $data['eyelashes_record'] = TRUE;
                    }
                }
                
            } else {
                $data['result']='notfound';
            }
            
            

            echo(json_encode($data));
        }
    }

    function createinvoice() {
        //exit();
        if ($this->session->userdata('role') == '') {
            echo 'sessionexpired';
        } else {
            $visitid = $this->input->post('visitid');

            $data['visit']=$this->visits_model->getopenvisitbyid($visitid);
            if(!$data['visit']){

                echo 'error|This visit is alreday Invoiced from another terminal. Refresh Page!';
                exit();

            } 

            $customer_phone = $this->input->post('customercell');

            //verify retained_amount_usage
            $verification = $this->customer_model->get_customer_loyalty($this->input->post('customerid'));


            if(sizeof($verification)>0){

                 if((float)$verification[0]['retained'] <  ((float)$this->input->post('retained_amount_used') + (float)$this->input->post('remaining_retained'))){
                     echo 'error|Another Invoice used the customer advance. Refresh Page!';
                     exit();
                 }

                 if((float)$verification[0]['loyalty_points'] <  (float)$this->input->post('loyaltyused')){
                     echo 'error|Loyalty points already used in some other invoice. Refresh Page!';
                     exit();
                 }   
            }


             $services = $this->input->post('services');
             $staff = $this->input->post('staff');
             //print_r($services); exit();
             $products = $this->input->post('products');
             $taxes = $this->input->post('taxes');
             $visitserviceids = $this->input->post('visit_service_ids');
             //var_dump($visitserviceids ); exit();

             $invoicenumber = $this->input->post('invoicenumber');
             $invoicedate = $this->input->post('invoicedate');

             if(defined('BACKDATEDINVOICE')){
                if(BACKDATEDINVOICE==TRUE){
                    $dt = date_create('now');
                    $vdt = date_create(date('Y-m-d 07:00:00')); // Correct formatting
    
                    if ($dt < $vdt) {
                        date_sub($dt, date_interval_create_from_date_string("1 day"));
                        $invoicedate = date_format($dt, "Y-m-d").' 23:00:00';
                    }
                } else {
                    $invoicedate = date('Y-m-d H:i:s', strtotime($invoicedate));
                }
            } else {
                $invoicedate = date('Y-m-d H:i:s', strtotime($invoicedate));
            }

             $customerid = $this->input->post('customerid');
             $customername = $this->input->post('customername');
             $customercell = $this->input->post('customercell');
             $customeraddress = $this->input->post('customeraddress');
             $customeremail = $this->input->post('customeremail');
             $subtotal = $this->input->post('subtotal');
             $org_subtotal= $this->input->post('org_subtotal');

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

             $roundedadjustment=$this->input->post('roundedadjustment');
             
             $grosstotal = $this->input->post('grosstotal');             
             $gross_wo_tax = $this->input->post('grosstotal');
             
             $paid = $this->input->post('paid');
             $paymentmode = $this->input->post('paymentmode');
             $cashpaid=0;$cardpaid=0;$voucherpaid=0;$checkpaid=0;
             if($paymentmode=="Cash"){$cashpaid=$paid;}
             else if($paymentmode=="Card"){$cardpaid=$paid;}
             else if($paymentmode=="Check"){$checkpaid=$paid;}
             else if($paymentmode=="Voucher"){$voucherpaid=$paid;}
             else if($paymentmode=="Mixed"){
                 $cashpaid=$this->input->post('cashpaid', TRUE);
                 $cardpaid=$this->input->post('cardpaid', TRUE);
             } else {
                echo 'error|0'; exit();
             }
             $grandtotal = $this->input->post('grandtotal');
             $totalpayable = $this->input->post('totalpayable');
            $taxtotal = $this->input->post('taxtotal');
             
             $instrumentnumber = $this->input->post('instrument_number');
             $balance = $this->input->post('balance');

             $uid = $this->input->post('uid');
             $uname = $this->input->post('uname');
             $uusername = $this->input->post('uusername');
             $uemail = $this->input->post('uemail');
             $keepadv = $this->input->post('keepadv');
            
             
             $invoice_discount_type = $this->input->post('invoice_discount_type');
             $discount = $this->input->post('discount');
             $discount_perc = $this->input->post('discount_perc');
             //$discount_type= $this->input->post('discount_type');
             $discountremarks = $this->input->post('discount_remarks');
             $returnamount = $this->input->post('returnamount');
             $advance_amount = $this->input->post('advance_amount');
             $other_charges = $this->input->post('other_charges');
             
             
             $retained_used = $this->input->post('retained_used');
             $retained_amount_used = $this->input->post('retained_amount_used');
             $remaining_retained = $this->input->post('remaining_retained');
             $cctip = $this->input->post('cctip');
             $cc_charge = $this->input->post('cc_charge');
             $remarks = $this->input->post('remarks');
             $visitdate= $this->input->post('visitdate');
             $visittime= $this->input->post('visittime');

             $business = $this->business_model->getbusinessdetails();

             //Loyalty
             $totalpaid= ($advance_amount+$paid)-($cctip+$cc_charge+$taxtotal);
             $paidnow=$paid-($cctip+$cc_charge);
             $loyaltyearned=0;
             if($business[0]['loyalty_enable']=='Y' && $business[0]['s_loyalty']=="Y" && (Float)$totalpaid>0) {
                 $ra=$keepadv==='true' ? $returnamount : 0;
                // echo 'ra'.$ra.'</br>';
                    if($ra>0){
                        $ntotalpaid=(Float)$totalpaid-$ra;
                        if($ntotalpaid<0)($ntotalpaid = $ntotalpaid * -1);
                       // echo 'ntotal paid'.$ntotalpaid.'</br>'; 
                        
                        $loyaltyearned=(Float)$ntotalpaid/(Float)$business[0]['l_point_value'];
                    }else{
                       // echo 'total paid'.$totalpaid.'</br>';
                        $loyaltyearned=(Float)$totalpaid/ (Float)$business[0]['l_point_value'];
                        
                    } 
             } 

            $service_addition=0; 
            foreach($services as $service){
                $tdiscount = (float)$service['discount'];
                $service_addition = $service_addition + floatval($service['service_addition']);
            }
            $tdiscount = $tdiscount + (float)$discount;
            $loyaltyearned = $tdiscount==0 ? (intval($loyaltyused) == 0 ? $loyaltyearned :0) : 0;
           
            // echo 'Loyalty earned'.$loyaltyearned.'</br>';
            if($loyaltyearned < 0){$loyaltyearned=0;}

            
            // print_r($taxtotal); exit();
             ///Create Invoice Record
             //$invoice_number, $invoice_date, $customer_id,$customer_name, $customer_cell, $customeraddress, $customeremail, $subtotal,$paid,$returnamount,$discount,$grosstotal,$balance,$taxtotal,$grandtotal,$visitid,$paymentmode,$instrumentnumber,$remarks,$discountremarks,$loyaltyused, $visittime, $advance_amount, $other_charges, $retained_used, $customer_advance,$cctip,$loyaltyearned,$retained_amount_used,$cashpaid,$cardpaid,$voucherpaid,$checkpaid,$cc_charge,$totalpayable, $remaining_retained
             $invoiceid = $this->pos_model->insert_invoice($invoicenumber, $invoicedate, $customerid, $customername, $customercell, $customeraddress, $customeremail, $subtotal, $paid, $returnamount, $discount, $invoice_discount_type, $grosstotal, $balance, $taxtotal,$grandtotal,$visitid,$paymentmode, $instrumentnumber, $remarks, $discountremarks, $loyaltyused, $visittime, $advance_amount, $other_charges, $retained_used, $keepadv, $cctip, $loyaltyearned, $retained_amount_used, $cashpaid, $cardpaid, $voucherpaid, $checkpaid, $cc_charge, $totalpayable, $remaining_retained, $visitdate, $service_addition);


             ///Make sure invoice number is correct
             $seq = $this->pos_model->updateinvoicenumber($invoiceid, $paymentmode);
             //////////////////


             ///Update Customer Advance
             $a = $this->pos_model->updatecustomeradvance($customerid, $keepadv, $remaining_retained, $returnamount);
             //////////


             //insert invoice taxes
             if(isset($taxes)){
                 foreach($taxes as $tax){
                    $this->pos_model->insert_invoice_taxes($invoiceid,$tax['taxname'], $tax['tax']);
                 }
             }


             $totalservicediscount=0; $totalserviceaddition=0;
             $remainingsub=$subtotal - $discount; $remainingpaid=$paid+$advance_amount; 
             ///Do Services
             foreach ($services as $service) {
                 $staff_count=0;
                 foreach ($staff as $s) {
                     if($s['row_id']==$service['row_id']){
                         $staff_count++;
                     }
                 }
                 
                 
                 ///Just put the paid amount in service (Trying out)
                 $priceafterdiscount=round((floatval($service['originalservicerate']) + $service['service_addition']) - floatval($service['discount']),2);
                 $invoicediscount=$discount/sizeof($services);
                 $finalprice=  $priceafterdiscount - $invoicediscount;
                 $totalservicediscount= round($totalservicediscount+ floatval($service['discount']),2);
                 
                $service_paid=0;
                if($discount>0){$thisinvoicediscount = $discount/sizeof($services);}
                else {$thisinvoicediscount=0;}
                
                $thisservice = round((floatval($service['originalservicerate']) + floatval($service['service_addition'])) - (floatval($service['discount']) + floatval($thisinvoicediscount)),2);


                if($thisservice < $remainingpaid){
                    $service_paid=$thisservice;
                }else{
                    if($remainingpaid>0){
                        $service_paid=$remainingpaid;
                    } else {
                        $service_paid=0;
                    }
                }

                $remainingsub = $remainingsub - $thisservice;
                $remainingpaid = $remainingpaid-$service_paid;

                $commission = ($service_paid * $service['commission']) / 100;
                $commission = round($commission, 2);
                 
                 
                 
                 
                 //get Products
                 //insert products
                 $service_products='';
                 if(isset($products)){
                     foreach($products as $product){
                         if($product['row_id']==$service['row_id']){
                             $this->pos_model->insert_invoice_products($invoiceid, $visitid, $product['service_id'], $product['service_name'], $product['product_id'], $product['product_name'], $product['qty'], $product['unit']);
                             $service_products .= $product['product_name']."|";
                         }
                     }
                 }


                 $invoice_detail_id = $this->pos_model->insert_invoice_details($service['row_id'], $invoiceid, $service_paid, $service['service_type'], $service['service_category'],  $service['service_id'], $service['service_name'], $service['service_duration'], $service['service_flag'], $service['id_service_category'], $service['discount'], $service['discount_type'], $service['unitcost'], $service['originalservicerate'], $service['visit_service_start'],$priceafterdiscount,$discount_perc,$invoicediscount, $service['service_addition'], $finalprice, $service_paid, $service_products, $service['visit_service_id']);


                 foreach ($staff as $s) {
                     if($s['row_id']==$service['row_id']){                                                                                  // $row_id, $invoiceid, $service_type,              $service_category,              $service_name,         $price,                              $discount,             $discounted_price, $requested,       $staff_id,     $staff_name,    $staff_count, $staff_share,      $invoice_detail_id,     $additional_staff, $priceafterdiscount, $discount_perc,   $invoicediscount, $finalprice, $sPercPaidForService, $commission
                         $invoice_staff = $this->pos_model->insert_invoice_staff($s['row_id'], $invoiceid, $service['service_type'], $service['service_category'],  $service['service_name'], $service['originalservicerate'],  $service['discount'], $priceafterdiscount, $s['requested'], $s['staff_id'], $s['staff_name'], $staff_count, $s['staff_share'], $invoice_detail_id, $s['additional_staff'], $priceafterdiscount, $discount_perc, $invoicediscount, $service['service_addition'], $finalprice, $service_paid, $commission, $s['visit_staff_id']);
                         $staff_services = $this->pos_model->insert_invoice_staff_services($s['row_id'], $invoiceid, $invoice_detail_id, $visitid, $s['staff_id'], $s['service_id'], $s['staff_name'], $service['service_type'], $service['service_category'], $service['service_name'], $s['staff_share'], $service['discount'], $service['commission'], $service_paid, $service['service_flag'], $s['requested'], $staff_count, $service['originalservicerate'], $s['staff_share'], $priceafterdiscount);
                     }
                 }
             }

             $this->pos_model->update_visit_status($visitid,$seq);
             $this->session->unset_userdata('discount_session');
             
             ////create sale account voucher
              if($this->session->userdata('auto_voucher')=='Yes'){
                  $account_voucher=$this->pos_model->insert_service_sale_voucher($invoiceid, $customerid, $customername, $totalpayable, $paymentmode, $returnamount, $cashpaid, $cardpaid, $checkpaid, $voucherpaid, $cctip,$balance, $totalservicediscount, $discount, $retained_amount_used, $advance_amount, $org_subtotal, $other_charges, $cc_charge, $keepadv, $taxtotal, $roundedadjustment, $loyaltyused, $loyaltyearned, $invoicedate);                  
              }

             ///Send Loyalty SMS

             $receipts_intsalled = false;
             if(isset($business[0]['receipts_installed'])){ if($business[0]['receipts_installed']=='Yes'){ $receipts_intsalled = true; } }

             if($business[0]['loyalty_sms']=='Yes' && sizeof($verification)>0 && strlen($customer_phone)==11){
                if($receipts_intsalled==FALSE){
                    $this->load->model('scheduled_tasks_model');
                    $loyalty_text = $this->scheduled_tasks_model->get_loyalty_text();

                    $newloyaltypoints = $verification[0]['loyalty_points'];
                    $customername= $verification[0]['customer_name'];

                    // echo (Int)$loyaltyearned ." ". (Int)$invoiceid." ".strlen($customer_phone)." ".$business[0]['show_amount'];

                    $msg='Hi '.$customername.',\nThank you for visiting '.$business[0]['business_name'].'.\n';
                    if($business[0]['loyalty_enable']=='Y'){
                        if((Int)$loyaltyearned>0 && (Int)$invoiceid>0  && $business[0]['show_points']=='Yes'){
                            $newloyaltypoints =  (float)$newloyaltypoints+(float)$loyaltyearned;
                            $msg=$msg.'Points earned today '. round($loyaltyearned) .'.\nTotal Points '.round($newloyaltypoints).'.\n';
                        } 
                        if((Int)$invoiceid>0 && strlen($customer_phone)==11 && $business[0]['show_amount']=='Yes'){

                            $msg=$msg.'Bill '. $totalpayable .'.\n';
                            $msg=$msg.'Paid '. $paid.".\n";
                            if((int)$balance>0){
                                $msg=$msg.'Balance '. $balance .".\n";
                            }
                        }              
                    }
                    if($loyalty_text!==null && $loyalty_text!==''){
                        $msg=$msg.$loyalty_text->msg;
                    }
                    $msg = iconv('ISO-8859-1', 'UTF-8', $msg);
                    $sendsms = $this->sms_model->send_sms(trim($msg), $customer_phone, false, 'LoyaltySMS', false, $business[0]['id_business']); 
                } else {
                    // echo 'Sending Receipt Curl Data';
                    $newloyaltypoints = $verification[0]['loyalty_points'];
                    $customername= $verification[0]['customer_name'];
                    
                    $cn = explode(" ",$customername);
                    
                    $receipturl = $this->sms_model->send_sms($newloyaltypoints, $customer_phone, false, 'ReceiptsSMS', false, $business[0]['id_business'], $invoiceid); 
                    
                    if( substr($receipturl, 0, 5) == 'https'){
                        $msg='Hi '.$cn[0].',\nYour '.$business[0]['business_name'].' receipt\n';
                        $msg.=trim($receipturl);
                        $sendsms = $this->sms_model->send_sms(trim($msg), $customer_phone, false, 'LoyaltySMS', false, $business[0]['id_business'], $invoiceid); 
                    }else{
                        echo $receipturl;
                    }
                }

             }

             if($business[0]['admin_notifications']==='Yes' && (Int)$invoiceid > 0){
                 $admins = $this->business_model->get_business_admins();

                 $thisInvoice = $this->invoice_model->getinvoicebyid($invoiceid);

                 $msg='Invoice#: '.$thisInvoice[0]['id_invoice'].'\n Time: '.$thisInvoice[0]['invoice_date'].'\n Customer: '.$thisInvoice[0]['customer_name'];
                 $msg=$msg.'\n Payable: '.number_format($thisInvoice[0]['net_amount']);
                 if($thisInvoice[0]['payment_mode']=='Cash'){$msg=$msg.'\n Cash: '.number_format($thisInvoice[0]['paid_cash']);}
                 if($thisInvoice[0]['payment_mode']=='Card'){$msg=$msg.'\n Card: '.number_format($thisInvoice[0]['paid_card']);}
                 if($thisInvoice[0]['payment_mode']=='Check'){$msg=$msg.'\n Check: '.number_format($thisInvoice[0]['paid_check']);}
                 if($thisInvoice[0]['payment_mode']=='Vocher'){$msg=$msg.'\n Voucher: '.number_format($thisInvoice[0]['paid_voucher']);}
                 if((int)$thisInvoice[0]['balance']>0){$msg=$msg.'\n Balance: '.number_format($thisInvoice[0]['balance']);}
                 $msg=$msg.'\nLoyaltyUsed: '.number_format($thisInvoice[0]['loyalty_used']);
                 $msg=$msg.'\nTipCharged: '.number_format($thisInvoice[0]['cctip']);
                 foreach ($admins as $admin){
                    if(null != $admin['user_mobile']){
                        if(strlen($admin['user_mobile'])===11){
                            $msg = iconv('ISO-8859-1', 'UTF-8', $msg);
                            $sendsms = $this->sms_model->send_sms(trim($msg), $admin['user_mobile'], false, 'AdminSMS', false); 
                        }
                    }

                 }
             }
             ///////////

             echo "success|".$invoiceid;
        }
    }

    
    function cancelvisit(){
        
        
        $option=  htmlspecialchars($this->input->post('eventid', TRUE));
        
        
        $visitid = htmlspecialchars($this->input->post('visitid', TRUE));
        $cancelled_by = htmlspecialchars($this->input->post('cancelled_by', TRUE));
        $cancelreason=htmlspecialchars($this->input->post('cancelreason', TRUE));
        

        if($option=='retain'){
            $update = $this->pos_model->cancelVisit($visitid, $cancelled_by, $cancelreason, 28);
        } else if($option=='return'){
             $update = $this->pos_model->cancelVisit($visitid, $cancelled_by, $cancelreason, 27);
        } else if($option=='keep'){
             $update = $this->pos_model->cancelVisit($visitid, $cancelled_by, $cancelreason, 29);
        } else {
            $update = $this->pos_model->cancelVisit($visitid, $cancelled_by, $cancelreason, 0);
        }
        
        if($update){
            //cancel request and dispatches if any
            if(AUTODISPATCH == true){
                $dispatch_requests = $this->dispatch_model->cancel_dispatch_request(0, $visitid);
            }
        }
        
        //$update = $this->pos_model->cancelVisit($visitid, $cancelled_by, $cancelreason);

        redirect('pos_services_view');
        
    }
    
   
}
