<?php

class Programs_model extends CI_Model {

    function __construct() {
        // Call the Model constructor
        parent::__construct();
         
    }

    function get_program_by_id($programid){
        
        $this->db->select('*');
        $this->db->join('program_types', 'program_types.id_program_types = programs.program_type_id');
        $this->db->where('id_programs',$programid);
        $query = $this->db->get('programs');

        return $query->result_array();
        
    }
    
    function get_programs_by_type($programtypeid){
        
        $this->db->select('*');
        $this->db->join('program_types', 'program_types.id_program_types = programs.program_type_id');
        $this->db->where('program_type_id',$programtypeid);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('programs');

        return $query->result_array();
        
    }
    
    function get_program_types(){
        $this->db->select('*');
        $query = $this->db->get('program_types');

        return $query->result_array();
        
    }
    function get_program_type($programtypeid){
        
        $this->db->select('*');
        $this->db->where('id_program_types',$programtypeid);
        $query = $this->db->get('program_types');

        return $query->result_array();
        
    }
    
    
    function get_active_programs($programtypeid){
        
        $this->db->select('*');
        $this->db->where('program_active',"Yes");
        if($programtypeid > 0){
            $this->db->where('program_type_id',$programtypeid);
        }
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('programs');
        
        return $query->result_array();
        
    }
    
    
    function get_active_sessions($programid){
        
        $this->db->select('*, date_format(program_session_start,"%d %b %Y") start, date_format(program_session_end,"%d %b %Y") end');
        $this->db->where('program_id',$programid);
       // $this->db->where('program_session_end >', '2018-01-19');
        $query = $this->db->get('program_sessions');

        return $query->result_array();
        
    }
    
     function get_program_sessions($programid){
        
        $this->db->select('*, date_format(program_session_start,"%d %b %Y") start, date_format(program_session_end,"%d %b %Y") end');
        $this->db->join('program_sessions','program_sessions.program_id=programs.id_programs','left');
        $this->db->where('id_programs',$programid);
        $query = $this->db->get('programs');

        return $query->result_array();
    }
    
    function get_program_session_id($programsessionid){
        
        $this->db->select('*');
        $this->db->join('programs','program_sessions.program_id=programs.id_programs');
        $this->db->where('id_program_sessions',$programsessionid);
        $query = $this->db->get('program_sessions');
     
         return $query->result_array();
    }
    
    
    function get_enrollment($programsessionid){
        
        $this->db->select('*');
        $this->db->join('programs','programs.id_programs = program_sessions.id_program_sessions');
        $this->db->join('program_types','program_types.id_program_types = programs.program_type_id');
        $this->db->join('customers','program_sessions.customer_id = customer.id_customers');
        $this->db->where('id_program_sessions',$programsessionid);
        $query = $this->db->get('program_sessions');

        return $query->result_array();
        
        
    }
    
    function get_enrollment_schedule($programentrollmentid){
        
        
        
    }
    
    
    function get_enrollment_details($programentrollmentid){
        
        $this->db->select('*,id_program_enrollment, program, session_name, id_customers, customer_name, customer_cell, customer_email, customer_address, programs.program_price, ifnull(program_enrollment.agreeddiscount,0) as agreeddiscount, '
                . ' education, beautyeducation, beautyexperience, program_enrollment.created_on, ifnull(sum(program_invoices.paid_amount),0) as paid_till_date, '
                . 'date_format(invoice_date, "%d/%m/%Y") f_payment_date, date_format(start_date, "%d-%m-%Y") f_start_date, '
                . 'date_format(program_session_start,"%d-%m-%Y") program_session_start, '
                . 'date_format(program_session_end,"%d-%m-%Y") program_session_end, '
                . 'TIMESTAMPDIFF(month, program_session_start, program_session_end) month_diff, '
                . 'date_format(program_session_start,"%W %D %M") f_program_session_start, '
                . 'date_format(program_session_end,"%W %D %M") f_program_session_end', FALSE);
        $this->db->join('program_sessions','program_enrollment.program_session_id = program_sessions.id_program_sessions');
        $this->db->join('programs','programs.id_programs = program_sessions.program_id');
        $this->db->join('program_types','program_types.id_program_types = programs.program_type_id');
        $this->db->join('customers','program_enrollment.customer_id = customers.id_customers');
        $this->db->join('program_invoices','program_invoices.program_enrollment_id = program_enrollment.id_program_enrollment and program_invoice_status="Active"','left');
        $this->db->where('id_program_enrollment',$programentrollmentid);
        $this->db->group_by('id_program_enrollment');
        $query = $this->db->get('program_enrollment');
        
        return $query->row();
        
    }
            
    function get_enrollment_payments($programentrollmentid){
        
        $this->db->select('*, date_format(invoice_date, "%d/%m/%Y") f_payment_date, date_format(start_date, "%d-%m-%Y") f_start_date, date_format(program_session_start,"%W %D %M") f_program_session_start, date_format(program_session_end,"%W %D %M") f_program_session_end');
        $this->db->join('program_sessions','program_enrollment.program_session_id = program_sessions.id_program_sessions');
        $this->db->join('programs','programs.id_programs = program_sessions.program_id');
        $this->db->join('program_types','program_types.id_program_types = programs.program_type_id');
        $this->db->join('customers','program_enrollment.customer_id = customers.id_customers');
        $this->db->join('program_invoices','program_invoices.program_enrollment_id = program_enrollment.id_program_enrollment and program_invoice_status = "Active"','left');
        $this->db->where('id_program_enrollment',$programentrollmentid);
        $this->db->order_by('id_program_invoices', 'Desc');
        $query = $this->db->get('program_enrollment');
        
        return $query->result_array();
        
        
    }
    
    function addpayment(){
        exit();
        $data = array(
            'program_enrollment_id' =>  $this->input->post('txtenrollmentid'),
            'invoice_date'=>$this->input->post('txtPaymentDate'),
            'paid_amount'=>$this->input->post('txtTotalPayment'),
            'paid_cash'=>$this->input->post('txtPaidCash'),
            'paid_card'=>$this->input->post('txtPaidCard'),
            'paid_check'=>$this->input->post('txtPaidCheck')
            );
        
        
        $this->db->insert('program_invoices', $data);
        return $this->db->insert_id();
        
    }
    
    function add_invoice_payment(){
        
        $paidcash=0; $paidcard=0; $paidcheck=0;
        if($this->input->post('paymentmode')=='cash'){
            $paidcash=$this->input->post('payingnow');            
        } else if($this->input->post('paymentmode')=='card'){
            $paidcard=$this->input->post('payingnow');            
        } else if($this->input->post('paymentmode')=='check'){
            $paidcheck=$this->input->post('payingnow');            
        }
        
        $data = array(
            'program_enrollment_id' =>  $this->input->post('enrollment_id'),
            'payment_mode' => $this->input->post('paymentmode'),
            'for_the_month' => $this->input->post('frommonth'),
            'from_month' => $this->input->post('frommonth'),
            'to_month' => $this->input->post('tomonth'),
            'invoice_date'=> $this->input->post('invoicedate'),
            'paid_amount'=> $this->input->post('payingnow'),
            'paid_cash'=> $paidcash,
            'paid_card'=> $paidcard,
            'paid_check'=> $paidcheck,
            'program_invoice_remarks'=> $this->input->post('remarks'),
            'program_invoice_status'=> 'Active',
            'created_by' => $this->session->userdata('username'),
            'business_id' =>$this->session->userdata('businessid')
            );
        
        
        $this->db->insert('program_invoices', $data);
        
        $invoiceid= $this->db->insert_id();
        
        
        ////create the account voucher for the payment
        //get customer
        $this->db->select('*');
        $this->db->join('customers','customers.id_customers = program_enrollment.customer_id');
        $this->db->join('program_sessions',  'id_program_sessions = program_session_id');
        $this->db->join('programs', 'id_programs = program_id');
        $this->db->join('program_types', 'programs.program_type_id = program_types.id_program_types');
        $this->db->where('id_program_enrollment', $this->input->post('enrollment_id'));
        $query = $this->db->get('program_enrollment');
        
        $customer= $query->row();
        
        if($this->session->userdata('auto_voucher')=='Yes'){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(1);
            //var_dump ($account_heads); exit();
            foreach($account_heads as $ah){
                if($ah['transaction_type']=='debit'){
                   array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                } else {
                    array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                }
            }
            
            $bank_name='';
            
            $saletype=$customer->id_program_types;
                        
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => $customer->program_type.' Fee Receive Voucher for '.$customer->program.', against invoice ' . $invoiceid . ' on '. date('d-m-Y').', from '.$customer->customer_name.' customer ID : '. $customer->id_customers,
                'voucher_date' => $this->input->post('invoicedate'),
                'voucher_amount' => $this->input->post('payingnow'),
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 1,
                'business_partner_id'=>$customer->id_customers,
                'business_partner_name'=>$customer->customer_name,
                'voucher_type'=>2,
                'payment_mode'=>$this->input->post('paymentmode'),
                'bank_name'=>$bank_name,
                'program_invoice_id'=>$invoiceid,
                'auto_voucher'=>'Yes',
                'sale_type'=>$saletype
            );

            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();
            
            //enter debit entries
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                if($debit[2]=="paid_cash" && $paidcash > 0){$debitamount= $paidcash;}
                if($debit[2]=="paid_card" && $paidcard > 0){$debitamount= $paidcard;}
                if($debit[2]=="paid_check" && $paidcheck > 0){$debitamount= $paidcheck;}
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'debit' => round($debitamount,2),
                    'credit' => 0
                );
                //insert debit detail
                if($debitamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
                
                $this->db->select('*');
                $this->db->where('id_program_types',$saletype);
                $q = $this->db->get('program_types');
                
                $progtype = $q->row(); 
                
                if($progtype->program_type=='Courses'){
                    if($credit[2]=="grosstotal_training"){$creditamount= $this->input->post('payingnow');}
                } else if($progtype->program_type=='Gym') {
                    if($credit[2]=="grosstotal_gym"){$creditamount= $this->input->post('payingnow');}                                
                } else if($progtype->program_type=='Recurring') {
                    if($credit[2]=="grosstotal_recurring"){$creditamount= $this->input->post('payingnow');}                                
                } else {
                    if($credit[2]=="grosstotal_service"){$creditamount= $this->input->post('payingnow');}     
                }
                 
                if($credit[2]=="sales_tax"){$creditamount= $this->input->post('salestax');}
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $credit[0],
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
        }
        
        /////Account voucher end
        return $invoiceid;
        
    }
    
    
    function cancel_invoice($invoiceid){
     
        $this->db->where('id_program_invoices', $invoiceid);
        $this->db->set('program_invoice_status', 'InActive');
        $this->db->set('canceled_by', $this->session->userdata('username'));
        $this->db->set('canceled_on', date('Y-m-d H:i:s'));
        
        $this->db->update('program_invoices');
        
        
        //change account voucher status
        $this->db->where('program_invoice_id', $invoiceid);
        $this->db->update('account_vouchers', array('voucher_status' => 'cancelled', 'cancelled_by' => $this->session->userdata('username'), 'cancelled_on' => date('Y-m-d H:i:s')));

        
    }
    
    function get_program_members($program_type="All"){
        
        $this->db->select('*');
        $this->db->join('program_types','program_types.id_program_types = programs.program_type_id');
        $this->db->join('program_sessions','program_sessions.program_id = programs.id_programs');
        $this->db->join('program_enrollment','program_enrollment.program_session_id = program_sessions.id_program_sessions');
        $this->db->join('customers','program_enrollment.customer_id = customers.id_customers');
        
        if($program_type!=="All"){
            $this->db->where('id_program_types',$program_type);
        }
        $this->db->where('program_active','Yes');
        $this->db->where('programs.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('programs');
     
        return $query->result_array();
        
    }
    
    
    
    
    function insert_program(){
        
         $data = array(
                
                'program' => $this->input->post('program_name'),
                'program_duration' => $this->input->post('program_duration'),
                'program_price' => $this->input->post('program_price'),
                'program_type_id' => $this->input->post('program_type_id'),
                'business_id' => $this->session->userdata('businessid'),
                'program_active' => $this->input->post('program_active')
            );
            
         $this->db->insert('programs', $data);
         return $this->db->insert_id();
        
    }
    function update_program(){
        $data = array(                
                'program' => $this->input->post('program_name'),
                'program_duration' => $this->input->post('program_duration'),
                'program_price' => $this->input->post('program_price'),
                'program_type_id' => $this->input->post('program_type_id'),
                'business_id' => $this->session->userdata('businessid'),
                'program_active' => $this->input->post('program_active')
            );
         $this->db->where('id_programs',$this->input->post('id_programs')) ;  
         $this->db->update('programs', $data);
         return $this->db->affected_rows();
    }
    function insert_program_session(){
        
         $data = array(
                'program_id' => $this->input->post('program_id'),
                'session_name' => $this->input->post('session_name'),
                'program_session_start' => $this->input->post('program_session_start'),
                'program_session_end' => $this->input->post('program_session_end')
               
            );
            
         $this->db->insert('program_sessions', $data);
         return $this->db->insert_id();
        
    }
    
    function update_program_session(){
        $data = array(                
                'session_name' => $this->input->post('session_name'),
                'program_session_start' => $this->input->post('program_session_start'),
                'program_session_end' => $this->input->post('program_session_end')
            );
         $this->db->where('id_program_sessions',$this->input->post('id_program_sessions')) ;  
         $this->db->update('program_sessions', $data);
         return $this->db->affected_rows();
    }
    
    function get_program_session_classes($programsessionid){
        
        $this->db->select('*, date_format(class_start,"%H:%s") start, date_format(class_end,"%H:%s") end');
        $this->db->join('program_sessions','program_sessions.id_program_sessions = program_session_classes.program_session_id');
        $this->db->join('programs','programs.id_programs = program_sessions.program_id');
        $this->db->join('staff','program_session_classes.instructor = staff.id_staff');
        $this->db->where('program_session_id',$programsessionid);
        $query = $this->db->get('program_session_classes');
        
        return $query->result_array();
        
    }
    
    function get_program_session_services($programsessionid){
        
        $this->db->select('*');
        $this->db->join('program_sessions','program_sessions.id_program_sessions = program_session_services.program_session_id');
        $this->db->join('programs', 'programs.id_programs = program_sessions.program_id');
        $this->db->where('program_session_id', $programsessionid);
        
        $query = $this->db->get('program_session_services');
        
        return $query->result_array();
    }
    
    function insert_program_session_class(){
        
        $data = array(
                'program_session_id' => $this->input->post('program_session_id'),
                'weekdays' => $this->input->post('weekday'),
                'class_start' => $this->input->post('class_start'),
                'class_end' => $this->input->post('class_end'),
                'instructor' => $this->input->post('instructor'),
                'classroom' => $this->input->post('classroom'),
            );
         
         $this->db->insert('program_session_classes', $data);
         return $this->db->insert_id();
    }
    
    function insert_program_session_service(){
                
        $this->db->select('*');
        $this->db->join('service_category','service_category.id_service_category = business_services.service_category_id');
        $this->db->where('id_business_services', $this->input->post('service'));
        $query = $this->db->get('business_services');
        $service = $query->row();
        
        $data = array(
                'program_session_id' => $this->input->post('program_session_id'),
                'service_id' => $this->input->post('service'),
                'service_category' => $service->service_category,
                'service_name' => $service->service_name,
                'per_month' => $this->input->post('per_month'),
                'per_session' => $this->input->post('per_session')
            );
         
         $this->db->insert('program_session_services', $data);
         return $this->db->insert_id();
    }
    
    
    function update_program_session_class(){
        
        $data = array(
            'program_session_id' => $this->input->post('program_session_id'),
            'weekdays' => $this->input->post('weekday'),
            'class_start' => $this->input->post('class_start'),
            'class_end' => $this->input->post('class_end'),
            'instructor' => $this->input->post('instructor'),
            'classroom' => $this->input->post('classroom'),
        );
        
        $this->db->where('id_program_session_classes', $this->input->post('program_session_class_id'));
        
        $this->db->update('program_session_classes', $data);
        
        return $this->db->affected_rows();
    }
    
    function update_program_session_service(){
               
        $this->db->select('*');
        $this->db->join('service_category','service_category.id_service_category = business_services.service_category_id');
        $this->db->where('id_business_services', $this->input->post('service'));
        $query = $this->db->get('business_services');
        $service = $query->row();
        
        $data = array(
                'program_session_id' => $this->input->post('program_session_id'),
                'service_id' => $this->input->post('service'),
                'service_category' => $service->service_category,
                'service_name' => $service->service_name,
                'per_month' => $this->input->post('per_month'),
                'per_session' => $this->input->post('per_session'),
                'service_status' => $this->input->post('service_status')
            );
         $this->db->where('id_program_session_services', $this->input->post('id_program_session_services'));
         $this->db->update('program_session_services', $data);
         
         return $this->db->affected_rows();
    }
    
    function getdaytraininginvocies($startdate){
        
        $this->db->select('*, program_invoices.business_id as business_id, program_invoices.created_by as created_by, business_services.service_name as program_name', false);
        $this->db->join('program_enrollment', 'id_program_enrollment = program_enrollment_id');
        $this->db->join('customers', 'customers.id_customers = program_enrollment.customer_id');       
        $this->db->join('program_enrolled_services', 'program_enrollment.id_program_enrollment = program_enrolled_services.program_enrollment_id');
        $this->db->join('business_services', 'id_business_services = program_enrolled_services.service_id');
        $this->db->where('program_invoices.business_id', $this->session->userdata('businessid'));
        $this->db->where('program_invoice_status', 'Active');
        $this->db->where('date(payment_date)=', '"'.$startdate.'"', false);
        $query1 = $this->db->get('program_invoices');
        //echo $query1;
        $result1=$query1->result_array();
        
        //print_r($result1);
        //exit();
        
        $this->db->select('*, program_invoices.business_id as business_id, program_invoices.created_by as created_by, concat(program," | ", for_the_month) as program_name', false);
        $this->db->join('program_enrollment', 'id_program_enrollment = program_enrollment_id');
        $this->db->join('customers', 'customers.id_customers = program_enrollment.customer_id');
        $this->db->join('program_sessions', 'id_program_sessions = program_enrollment.program_session_id');
        $this->db->join('programs', 'programs.id_programs = program_sessions.program_id');
        $this->db->where('program_invoices.business_id', $this->session->userdata('businessid'));
        $this->db->where('program_invoice_status', 'Active');
        $this->db->where('date_format(invoice_date, "%Y-%m-%d")=', '"'.$startdate.'"', false);
        $query2 = $this->db->get('program_invoices');
        
        $result2=$query2->result_array();
        
//        print_r($result2);
//        exit();
        
        $result = array_merge($result1, $result2);
        
        return $result;
        
    }
    
    function get_program_session_class($classid){
        $this->db->select('*');
        $this->db->where('id_program_session_classes', $classid);
        $query = $this->db->get('program_session_classes');
        
        return $query->row();
        
    }
    
    function get_program_session_service($serviecid){
        $this->db->select('*');
        $this->db->where('id_program_session_services', $serviecid);
        $query = $this->db->get('program_session_services');
        
        return $query->row();
        
    }
    
    function get_enrollment_services($enrollment_id){
        $sql = "select id_customers from customers join program_enrollment on program_enrollment.customer_id = customers.id_customers
                where program_enrollment.id_program_enrollment = ".$enrollment_id."; ";
        
        $query1 = $this->db->query($sql);
        $customer = $query1->row();
        
        $customer_id = $customer->id_customers;
        
        $sql = " select * from customers 
                left join (
                SELECT customer_id, date_format(program_session_start,'%d-%m-%Y') as start_date,  date_format(program_session_start,'%d-%m-%Y') as program_session_start, date_format(program_session_end,'%d-%m-%Y') as program_session_end, 
                    case when program_session_start <= now() AND program_session_end >= now() then 'Valid'
                    else 'Expired' End as validity,
                id_business_services, business_services.service_name, business_services.service_rate, service_category, id_program_enrollment, id_program_sessions, id_programs, program,
                per_month, per_session
                FROM program_enrollment
                join program_sessions on program_sessions.id_program_sessions = program_enrollment.program_session_id
                join program_session_services on program_session_services.program_session_id = program_sessions.id_program_sessions
                join programs on programs.id_programs = program_sessions.program_id
                join business_services on business_services.id_business_services = program_session_services.service_id
                where id_program_enrollment=".$enrollment_id." and program_type_id=3
                and service_status = 'Active' 
                and program_session_start <= now()
                and program_session_end >= now()) as a
                on a.customer_id = customers.id_customers
                where customer_id = ".$customer_id."

            ";
        
        $query = $this->db->query($sql);
        return $query->result_array();
        
    }
    
    public function get_monthly_payments(){
        
        $this->db->select('*');
        $this->db->join('program_enrollment');
        
        
    }
    
    public function get_availed_services($customerid, $services, $year){
        
        $sql = "SELECT *, service_id, detail_visit_date, concat(substring(date_format(detail_visit_date, '%M'),1,3),' ', date_format(detail_visit_date, '%Y')) as availedmonth
                FROM invoice
                join invoice_details on invoice_details.invoice_id = invoice.id_invoice
                where customer_id = ".$customerid."
                and year(detail_visit_date)='".$year."'
                and service_id in (".$services.")
                and invoice.invoice_status='valid'
                and membership = 'Yes';";
        
        $query = $this->db->query($sql);
        return $query->result_array();
        
    }

    public function create_visit(){
        
         if($this->input->post('customer_id')==0){ return 0; exit();}
         $enrollment_id = $this->input->post('enrollment_id');
         //check if visit alrady exists
         foreach($this->input->post('service_id') as $serviceid){
            if($serviceid!==''){
                $this->db->select('*');
                $this->db->join('program_sessions', 'id_program_sessions = program_enrollment.program_session_id');
                $this->db->where('id_program_enrollment', $enrollment_id);
                $query3 = $this->db->get('program_enrollment');

                $result3 = $query3->row();

                $session_start = $result3->program_session_start;
                $session_end = $result3->program_session_end;

                $this->db->select('service_id, count(id_visit_services) as count');
                $this->db->join('customer_visits', 'id_customer_visits = customer_visit_id');
                $this->db->join('visit_service_staffs', 'id_visit_services = visit_service_id');
                $this->db->where('membership','Yes');
                $this->db->where('service_id',$serviceid);
                $this->db->where('customer_id',$this->input->post('customer_id'));
                $this->db->where('visit_status !=','canceled');
                $this->db->where('visit_service_status','Active');
                $this->db->where('month(visit_service_start)',date('m'));
                $this->db->where('year(visit_service_start)',date('Y'));
                $this->db->group_by('service_id');
                $query = $this->db->get('visit_services');            
               
                $result = $query->row();

                if($result){$countmonth=$result->count;} else { $countmonth=0;}

                $this->db->select('service_id, count(id_visit_services) as countsession');
                $this->db->join('customer_visits', 'id_customer_visits = customer_visit_id');
                $this->db->join('visit_service_staffs', 'id_visit_services = visit_service_id');
                $this->db->where('membership','Yes');
                $this->db->where('service_id',$serviceid);
                $this->db->where('customer_id',$this->input->post('customer_id'));
                $this->db->where('visit_status !=','canceled');
                $this->db->where('visit_service_status','Active');
                $this->db->where('visit_service_start >=', $session_start);
                $this->db->where('visit_service_end <=', $session_end);
                $this->db->group_by('service_id');
                $query2 = $this->db->get('visit_services');     
               
                $result2 = $query2->row();

                if($result2){$countsession=$result2->countsession;} else { $countsession=0;}


                $this->db->select('service_id, service_name, per_month, per_session');
                $this->db->where('service_id', $serviceid);
                $query1 = $this->db->get('program_session_services');
                
                $result1 = $query1->row();

                $allowedmonth = $result1->per_month;
                $allowedsession = $result1->per_session;
                
                if($countmonth >= $allowedmonth){     
                    $this->session->set_flashdata('Error', 'Already Booked '.$countmonth.' of '.$allowedmonth.' '.$result1->service_name.' this month');
                    return 0; exit();                
                }
               
                if($countsession >= $allowedsession){   
                    $this->session->set_flashdata('Error', 'Already Received '.$countsession.' of '.$allowedsession.' '.$result1->service_name.' this session');
                    return 0; exit();                
                }
            }
         }
         
         
         //add new customer_visit
        $visit = array(
            'business_id' => $this->session->userdata('businessid'),
            'customer_id' => $this->input->post('customer_id'),
            'customer_visit_date' => date('Y-m-d H:i:s'),
            'visit_color' => '#FFD700',
            'visit_color_type' => 'light',
            'customer_visit_date'=>date('Y-m-d H:i:s'),
            'created_by'=>$this->session->userdata('username')
            
        );
        $this->db->insert('customer_visits', $visit);
        $visit_id = $this->db->insert_id();
        
               
        $data = [];
        //process the table data
        foreach($this->input->post('service_id') as $serviceid){
        if(null !== $serviceid && $serviceid!==''){
            $this->db->select('*');
            $this->db->where('service_active', "Yes");
            $this->db->where('business_id', $this->session->userdata('businessid'));
            $this->db->where('id_business_services', $serviceid);
            $visit_services=$this->db->get('business_services');
            
            
            
            $service_flag="servicetype";
            $start = date('Y-m-d\TH:i:s', strtotime($this->input->post('ondate').' '.$this->input->post('ontime')));
            
            $i = 0; $lastduration=0; $newtime='';
            foreach($visit_services->result() as $vs){
                //get service start time
                if($i>0){ 
                    
                    $durCal =  explode(':',$lastduration);
                    $HoursInMin=0;
                    if(intval($durCal[0]) > 0){$HoursInMin = intval($durCal[0])*60;}
                    $newduration = $HoursInMin + $durCal[1]; 
                    $newduration = date_interval_create_from_date_string($newduration.' minutes');
                    $newstart=date_create($newtime);
                    $newtime=date_add($newstart, $newduration);
                    $newtime=date_format($newtime,"c");
                    $d=  explode('+', (string)$newtime);
                    $newtime=$d[0];
                    $lastduration=$vs->service_duration;
                } else {
                   $newtime=$start;
                   $lastduration=$vs->service_duration;
                }
                
                
                //create endtime
                $HoursInMin=0; $newendtime='';
                $durCal =  explode(':',$lastduration);
                if(intval($durCal[0]) > 0){$HoursInMin = intval($durCal[0])*60; }
                $newduration = $HoursInMin + $durCal[1];
                $newduration = date_interval_create_from_date_string($newduration.' minutes');
                $newendtime=date_create($newendtime);
                $newendtime = date_add(date_create($newtime), $newduration);
                $newendtime=date_format($newendtime,"c");
                $d=  explode('+', (string)$newendtime);
                $newendtime=$d[0];
                //
                
               //print_r($newtime);echo('<br>');
               // service start time in $newtime
               
               $data = array(
                    'business_id' => $this->session->userdata('businessid'),
                    'customer_visit_id' => $visit_id,
                    'service_id' => $vs->id_business_services,
                    'service_name' => $vs->service_name,
                    'service_flag' => $service_flag,
                    'id_service_category' => $vs->service_category_id,
                    'visit_service_start' => $newtime, //$start
                   'visit_service_end' => $newendtime, //end
                    'update_date' => date('Y-m-d H:i:s'),
                   'membership' => 'Yes'
                );
               
                $this->db->insert('visit_services', $data);
                $id_visit_services = $this->db->insert_id();
               
                //check shared staff
                $block_other='No';
                    
                $this->db->select('id_staff, staff_fullname, staff_shared');
                $this->db->where('id_staff=', $this->input->post('staffid'));
                $query = $this->db->get('staff');
                $staff = $query->row();

                if (isset($blockstaff))
                { $block_other =  $staff->staff_shared; }
                
                
                //insert service staff 
                $staff = array(
                    'business_id' => $this->session->userdata('businessid'),
                    'customer_visit_id' => $visit_id,
                    'visit_service_id' => $id_visit_services,
                    'staff_id' => $staff->id_staff,
                    'staff_name' => $staff->staff_fullname,
                    'block_other' => $block_other
                );
                $this->db->insert('visit_service_staffs', $staff);
               
               //insert service products
                
                $this->db->select('*');
                $this->db->join('business_products', 'business_products.id_business_products = services_products.business_product_id');
                $this->db->where('business_service_id', $vs->id_business_services);
                $this->db->where('business_id', $this->session->userdata('businessid'));
                $service_products=$this->db->get('services_products');
                
                foreach($service_products->result() as $sp){
                    $products = array(
                        'business_id' => $this->session->userdata('businessid'),
                        'customer_visit_id' => $visit_id,
                        'visit_service_id' => $vs->service_id,
                        'product_id' => $sp->business_product_id,
                        'product_name' => $sp->product,
                        'product_qty' => $sp->usage_qty,
                        'product_unit' => $sp->measure_unit
                     );
                     $this->db->insert('visit_service_products', $products);
                   // print_r($products);echo('<br>');
                }
                $i++;
            }
        }
        }
        
        
        
        return $visit_id;
        
    }
    
    
    public function services_booked($customer_id, $service_ids){
        
        $sql = "SELECT id_customers, customers.customer_name, visit_services.service_id, visit_services.service_name,
            concat(substring(date_format(visit_service_start, '%M'),1,3),' ', date_format(visit_service_start, '%Y')) as visit_month, visit_status, program_id, id_program_sessions
            FROM `visit_services` 
            JOIN `customer_visits` ON `id_customer_visits` = `customer_visit_id` 
            JOIN customers on customers.id_customers = customer_visits.customer_id
            Join program_enrollment on program_enrollment.customer_id = customers.id_customers
            Join program_sessions on program_sessions.id_program_sessions = program_enrollment.program_session_id
            WHERE  `service_id` in (".$service_ids.") 
            AND `id_customers` = ".$customer_id." 
            AND visit_services.membership = 'Yes'
            AND `visit_status` != 'canceled' 
            AND visit_service_status='Active' 
            AND program_session_start <= now() 
            AND program_session_end >= now()";
       
        $query = $this->db->query($sql);
        return $query->result_array();
    }
    
    function get_services() {

        $this->db->select('id_business_services, id_service_category, service_category, service_name, service_desc, service_rate, service_color, service_duration, business_services.order_id, "servicetype" flag');
        $this->db->join('service_category', 'service_category.id_service_category =  business_services.service_category_id');
        $this->db->join('service_type', 'service_type.id_service_types =  service_category.service_type_id');
        $this->db->where('business_services.business_id', $this->session->userdata('businessid'));
        $this->db->where('business_services.service_active=', 'Yes');
        $this->db->where('service_category.service_category_active=', 'Yes');
        $this->db->where('service_type.service_type_active=', 'Yes');
        $this->db->order_by('order_id','asc');
        $query = $this->db->get('business_services');
        
        return $query->result_array();
    }
    
    function staff_list($off_set=0, $limit=0) {
        $where="(business_id = ".$this->session->userdata('businessid')." OR staff.staff_shared = 'Yes')";
        
        $this->db->select('*');
        $this->db->where($where);
        $this->db->where('staff_active', 'Y');
        $this->db->where('staff_scheduler', 'On');
        $this->db->order_by('staff_order', 'ASC');
        $this->db->offset($off_set);
        if($limit>0){
            $this->db->limit($limit);
        }
        $query = $this->db->get('staff');
       // echo $query; exit();
        return $query->result();
    }
}
