<?php

class Coaching_model extends CI_Model {

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

    function get_coaching_members($service_id=0, $status='All'){ 
        //echo $serivce_id; exit();
        $sql = "SELECT * , ifnull(sessions.scheduled,0) as scheduled , program_group_members.program_group_id
                FROM program_enrolled_services
                JOIN program_enrollment on program_enrollment.id_program_enrollment = program_enrolled_services.program_enrollment_id
                JOIN program_types on program_types.id_program_types = program_enrollment.program_type_id 
                JOIN customers on customers.id_customers = program_enrollment.customer_id 
                left join program_group_members on  program_group_members.program_enrollment_id = program_enrollment.id_program_enrollment 
                
                LEFT JOIN(
                     select program_enrolled_service_id, ifnull(count(*),0) as scheduled from customer_visits
                    where customer_visits.visit_status in('open', 'invoiced')    
                    and program_enrolled_service_id > 0
                     group by program_enrolled_service_id
                ) as sessions on sessions.program_enrolled_service_id = program_enrolled_services.id_program_enrolled_services
                WHERE 1=1 ";
         if($status=="Active"){
            $sql .= " AND (scheduled is null OR sessions.scheduled < program_enrolled_services.total_sessions) ";
         }else if($status=="Completed"){
             $sql .= " AND sessions.scheduled >= program_enrolled_services.total_sessions ";
         }
         $sql .= " AND program_enrollment.business_id = ". $this->session->userdata('businessid')." ";
         if($service_id !== 0){
            $sql .= " AND program_enrolled_services.service_id = ".$service_id ." ";
         }
         $sql .= " AND program_enrolled_services.service_status = 'Active' GROUP by program_enrolled_services.id_program_enrolled_services";
         $query = $this->db->query($sql);
        //echo $sql; exit();
        return $query->result_array();
      } 

     public function getting_coaching_members_for_pos($service_id=0, $status='All'){  
           //echo $serivce_id; exit();
                $sql = "SELECT * , ifnull(sessions.scheduled,0) as scheduled
                FROM program_enrolled_services
                JOIN program_enrollment on program_enrollment.id_program_enrollment = program_enrolled_services.program_enrollment_id
                JOIN program_types on program_types.id_program_types = program_enrollment.program_type_id 
                JOIN customers on customers.id_customers = program_enrollment.customer_id

                LEFT JOIN(
                        select program_enrolled_service_id, ifnull(count(*),0) as scheduled from customer_visits
                    where customer_visits.visit_status in('open', 'invoiced')    
                    and program_enrolled_service_id > 0
                        group by program_enrolled_service_id
                ) as sessions on sessions.program_enrolled_service_id = program_enrolled_services.id_program_enrolled_services
                WHERE 1=1 ";
         $sql .= " AND program_enrollment.business_id = ". $this->session->userdata('businessid')." ";
         if($service_id !== 0){
            $sql .= " AND program_enrolled_services.service_id = ".$service_id ." ";
         }
        $sql .= " AND program_enrolled_services.service_status = 'Active'";
        $query = $this->db->query($sql);
        //echo $sql; exit();
        return $query->result_array();
     } 

       
    public function get_prospect_students($customers_ids) {
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where_not_in('id_customers', $customers_ids);
        $this->db->order_by('id_customers', 'ASC'); 
        $query = $this->db->get('customers'); 
        return $query->result_array();
    }
    
    
    function get_enrollment($enrollment_id){
        
        $this->db->select('*');        
        $this->db->join('customers', 'customers.id_customers = program_enrollment.customer_id');        
        $this->db->where('id_program_enrollment', $enrollment_id);
        $query = $this->db->get('program_enrollment');

        return $query->row();
        
        
    }
    
   function get_enrolled_services($enrollment_id){
       
    //    $this->db->select('*');        
    //     $this->db->where('program_enrollment_id', $enrollment_id);
    //     $this->db->where('service_status', 'Active');
    //     $query = $this->db->get('program_enrolled_services'); 

        // $this->db->select('
        //     program_enrolled_services.*, 
        //     program_invoices.invoice_discount, 
        //     program_invoices.salestax, 
        //     program_invoices.id_program_invoices
        // ');
        // $this->db->from('program_enrolled_services');
        // $this->db->join(
        //     'program_invoices', 
        //     'program_enrolled_services.id_program_enrolled_services = program_invoices.program_enrolled_service_id', 
        //     'left'
        // );
        // $this->db->join(
        //     'account_vouchers', 
        //     'program_enrolled_services.id_program_enrolled_services = account_vouchers.program_enrolled_service_id', 
        //     'left'
        // );
        // $this->db->where('program_enrolled_services.program_enrollment_id', $enrollment_id);
        // $this->db->where('program_enrolled_services.service_status', 'Active');
        // $this->db->group_by('program_enrolled_services.id_program_enrolled_services');

        // $query = $this->db->get();
        // return $query->result_array(); 

        $status ='';
        

        $sql="SELECT account_head_id, account_head FROM account_event_mapping
        join account_heads on id_account_heads = account_event_mapping.account_head_id
            where account_event_id = 1 and entity_name = 'balance'
             and account_event_mapping.business_id=".$this->session->userdata('businessid').";";
            $query=$this->db->query($sql);
            $ahdata = $query->row();
           $ah = $ahdata->account_head_id;   
           
        
        $this->db->select("program_enrolled_services.*,id_program_invoices, id_program_enrollment, invoice_number, number_of_sessions,  invoiced_amount,  payment_mode,
        IFNULL(program_invoices.invoice_other_charges,0) as invoice_other_charges, IFNULL(program_invoices.invoice_discount,0) as invoice_discount, salestax, IFNULL(program_invoice_payment.payment_paid_amount,0) as paid_amount, advance_used, IFNULL(program_invoice_payment.payment_cc_charge,0) as cc_charge , rounding_adjustment, return_amount,
        IFNULL(program_invoice_payment.payment_paid_cash,0) as  paid_cash, IFNULL(program_invoice_payment.payment_paid_card,0) as  paid_card, IFNULL(program_invoice_payment.payment_paid_check,0) as  paid_check, payment_mode, 
                        vouchers.paid,
                        vouchers.receivable,
                        vouchers.balance,
                        program_invoice_status as invoice_status, 
                        program_invoices.created_on, date_format(invoice_date,'%d-%m-%Y'),
                        program_invoice_remarks as remarks, program_invoice_remarks as program_invoice_remarks, 
                        program_invoices.canceled_by, program_invoices.canceled_on, program_invoices.business_id,  
                        program_invoices.created_by, payment_date, payment_received_by,
                        id_program_enrollment, service_id, service_name, per_session_rate as per_session, 
                        total_sessions, 
                        invoiced_amount-paid_amount as invoice_balance,
                        id_customers as customer_id, customers.customer_name, customers.customer_cell, customer_address, customer_email, invoice_remarks", false);        
        $this->db->join("program_enrollment", "program_enrollment_id = id_program_enrollment");
        $this->db->join("customers", "customers.id_customers = program_enrollment.customer_id");
        $this->db->join("program_enrolled_services", "program_enrolled_services.id_program_enrolled_services = program_invoices.program_enrolled_service_id", "left");       
        $sql = "(SELECT program_invoice_id,
                sum(debit) as receivable, 
                sum(credit) as paid, 
                round(sum(debit)-sum(credit),2) as balance
                FROM account_vouchers 
                join account_voucher_detail on account_voucher_detail.account_voucher_id=account_vouchers.id_account_vouchers
                and account_head_id=".$ah." where account_vouchers.voucher_status !='Cancelled'  group by program_invoice_id) as vouchers";
            // SQL query to calculate the sum of various payment methods for each program invoice
        $this->db->join($sql, 'vouchers.program_invoice_id = program_invoices.id_program_invoices');   
            // Subquery for program invoice payments
            $sql_payments = "(SELECT 
            program_invoice_payments.program_invoice_id, 
            IFNULL(SUM(program_invoice_payments.paid_amount), 0) AS payment_paid_amount,
            IFNULL(SUM(program_invoice_payments.paid_cash), 0) AS payment_paid_cash,
            IFNULL(SUM(program_invoice_payments.paid_card), 0) AS payment_paid_card,
            IFNULL(SUM(program_invoice_payments.paid_check), 0) AS payment_paid_check,
            IFNULL(SUM(program_invoice_payments.paid_online), 0) AS payment_paid_online,
            IFNULL(SUM(program_invoice_payments.paid_other), 0) AS payment_paid_other,
            IFNULL(SUM(program_invoice_payments.cc_charge), 0) AS payment_cc_charge,
            IFNULL(SUM(program_invoice_payments.other_charges), 0) AS payment_other_charges,
            IFNULL(SUM(program_invoice_payments.payment_discount), 0) AS payment_discount
            FROM program_invoice_payments  
            JOIN program_invoices ON program_invoice_payments.program_invoice_id = program_invoices.id_program_invoices
            WHERE program_invoice_payments.payment_status != 'Cancelled'
            GROUP BY program_invoice_payments.program_invoice_id) as program_invoice_payment";
            $this->db->join($sql_payments, 'program_invoice_payment.program_invoice_id = program_invoices.id_program_invoices' , "left");
                    $this->db->where('program_enrollment.id_program_enrollment', $enrollment_id);        
                    $this->db->where('program_invoices.program_invoice_status ', 'Active'); 
                    $this->db->where('program_enrolled_services.service_status', 'Active');
                    if(null != $status){
                        $this->db->where('program_invoices.payment_mode', $status);
                    }
                    $query = $this->db->get("program_invoices");
                    //echo $query; exit();
                    return $query->result_array(); 
             
   }
   
    public function get_registration_fee_status($id_program_enrollment){
        
        $this->db->select('program_enrollment_id, program_invoice_remarks, sum(salestax) as salestax, sum(invoiced_amount) as invoiced_amount, sum(paid_amount) as paid_amount, sum(cc_charge) as cc_charge');
        $this->db->where('program_enrollment_id', $id_program_enrollment);
        $this->db->where('program_enrolled_service_id', 0);
        $this->db->group_by('program_enrollment_id');
        $query = $this->db->get('program_invoices');
        
        return $query->row();
        
    }
    
    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.invoiced_amount),0) as paid_till_date, '
                . 'date_format(invoice_date, "%d/%m/%Y") f_payment_date, '
                . 'date_format(program_enrollment.created_on, "%d-%m-%Y") enrollment_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', FALSE);
        $this->db->join('program_sessions','program_enrollment.program_type_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_scheduling_details($id_program_enrollment, $id_enrolled_services){
        
        $sql ="SELECT program_enrollment_id, id_program_enrolled_services, program_enrolled_services.total_sessions,
                program_enrollment.customer_id, customer_name, customer_cell,
                father_name, father_cell,
                mother_name, mother_cell, 
                id_customer_visits, id_visit_services, visit_status,
                date_format(visit_service_start, '%d-%m%-%Y') as scheduled_date, 
                date_format(visit_service_start, '%H:%i') as scheduled_time,
                date_format(visit_service_end, '%H:%i') as end_time,
                visit_service_start,
                program_enrolled_services.service_name, staff_name, staff_id,
                program_enrolled_services.service_id
                FROM program_enrolled_services
                JOIN program_enrollment on program_enrollment.id_program_enrollment = program_enrolled_services.program_enrollment_id
                JOIN customers on customers.id_customers = program_enrollment.customer_id
                LEFT JOIN (
                   SELECT id_customer_visits, id_visit_services, program_enrolled_service_id, 
                   customer_visits.customer_id, visit_service_start, visit_service_end, staff_name, staff_id, visit_status
                   FROM customer_visits
                   join visit_services on visit_services.customer_visit_id=customer_visits.id_customer_visits
                   join visit_service_staffs on visit_services.customer_visit_id = visit_service_staffs.customer_visit_id
                   and visit_service_staffs.visit_service_id = visit_services.id_visit_services
                   WHERE 
                   (customer_visits.visit_status = 'open' or customer_visits.visit_status = 'invoiced')";
            if($id_enrolled_services>0){
                $sql .= " AND customer_visits.program_enrolled_service_id  = ".$id_enrolled_services." ";
            }
            $sql .= " ) as visits on visits.program_enrolled_service_id = program_enrolled_services.id_program_enrolled_services
               where program_enrollment_id=".$id_program_enrollment." ";
        if($id_enrolled_services>0){    
            $sql .= " and program_enrolled_services.id_program_enrolled_services=".$id_enrolled_services." ";
        }
        $sql .= " order by date(visit_service_start);";
        
        //echo $sql; exit();
               $query = $this->db->query($sql);
        
        //echo $query; exit();
        
        return $query->result_array();
        
    }
    
    function get_calendar_visits($id_enrolled_services, $type='array'){

        $sql="select id_customers from program_enrollment 
            join program_enrolled_services on program_enrollment_id = id_program_enrollment 
            join customers on program_enrollment.customer_id = customers.id_customers 
            where program_enrolled_services.id_program_enrolled_services = ".$id_enrolled_services.";
            ";
        $result = $this->db->query($sql);
        $customer = $result->row();
        $customerid=$customer->id_customers;
        
        
        $this->db->select('id_customer_visits as id, id_visit_services, visit_service_staffs.id_visit_service_staffs, 
                visit_service_start start,  visit_service_end end, visit_service_staffs.staff_id resourceId,
                concat(business_services.service_name," - With ",visit_service_staffs.staff_name," - Booked: ", customer_visits.created_by, " - At: ", date_format(visit_service_start,"%H:%i:%s")) as title, 
                "#fff" as textColor, "Session" as event_type,
                visit_status,
                CASE WHEN customer_visits.visit_status = "invoiced" 
                THEN false
                ELSE true
                END as editable,
                CASE WHEN customer_visits.visit_status = "invoiced" THEN "#c7c7c7"
                ELSE service_color                 
                END as backgroundColor,
                service_color as borderColor,
                CASE WHEN customer_visits.inservice="Yes" THEN "check" ELSE "" END as inservice,
                customer_visits.created_by as created_by
                
                ', false);
        $this->db->join('customer_visits','id_customer_visits = customer_visit_id');
        $this->db->join('visit_service_staffs','visit_service_staffs.visit_service_id = visit_services.id_visit_services');
        $this->db->join('business_services','business_services.id_business_services = visit_services.service_id');
//        if(null!= $id_enrolled_services){ 
//            $this->db->where('program_enrolled_service_id', $id_enrolled_services);
//        }
        $this->db->where('customer_visits.customer_id',$customerid);
        $this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $this->db->where_in('visit_status', ['open', 'invoiced']);
        
        $query = $this->db->get('visit_services');
        
        //echo $query; exit();
        if(null==$type || $type != 'array'){
            return $query->result();
        }else {
            return $query->result_array();
        }
    }
    
    function updateVisit($visit_service_id, $staff_id, $old_staff_id, $staffData, $serviceData) {
//        print_r($serviceData);
//        exit();
        if($staff_id !== $old_staff_id){
            $where = array(
                'business_id' => $this->session->userdata('businessid'),
                'visit_service_id' => $visit_service_id,
                'staff_id' => $old_staff_id
            );

            $this->db->where($where);
            $query = $this->db->update('visit_service_staffs', $staffData);
        }
        
        $where = array(
            'business_id' => $this->session->userdata('businessid'),
            'id_visit_services' => $visit_service_id
        );

        $this->db->where($where);
        $query = $this->db->update('visit_services', $serviceData);

        return $query;
    }

    function get_staff_schedule($staff_id, $day){
        //print_r($day); exit();
        //$this->db->select('id_customer_visits as id,  visit_service_staffs.staff_id, visit_service_staffs.staff_name, visit_service_start start,  visit_service_end end, service_name as title, visit_color_type as className, "#fff"  bg-color, "#fff" bgColor, "yellow" border, "Red" textColor, "font-size:10px; color:#000;" as style, "Session" as event_type' );
        
        $this->db->select('id_customer_visits as id, id_visit_services, visit_service_staffs.id_visit_service_staffs, 
                visit_service_start start,  visit_service_end end, visit_service_staffs.staff_id resourceId,
                concat(business_services.service_name," ", customers.customer_name ," - With ",visit_service_staffs.staff_name," - Booked: ", customer_visits.created_by, " - At: ", date_format(visit_service_start,"%H:%i:%s")) as title, 
                "#fff" as textColor, "Session" as event_type,
                visit_status,
                CASE WHEN customer_visits.visit_status = "invoiced" 
                THEN false
                ELSE true
                END as editable,
                CASE WHEN customer_visits.visit_status = "invoiced" THEN "#c7c7c7"
                ELSE service_color                 
                END as backgroundColor,
                service_color as borderColor,
                CASE WHEN customer_visits.inservice="Yes" THEN "check" ELSE "" END as inservice
                
                ', false);
        
        $this->db->join('customer_visits','customer_visits.id_customer_visits = visit_service_staffs.customer_visit_id');
        $this->db->join('customers', 'customers.id_customers = customer_visits.customer_id');
        $this->db->join('visit_services', 'visit_service_staffs.visit_service_id = visit_services.id_visit_services');
        $this->db->join('business_services','id_business_services = visit_services.service_id');
        $this->db->join('service_category','business_services.service_category_id = service_category.id_service_category');
        $this->db->join('service_type','service_category.service_type_id = service_type.id_service_types');
        //$this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $this->db->where('visit_service_staffs.staff_id', $staff_id);
        //$this->db->where('date(visit_services.visit_service_start)', $day);
        $this->db->where('year(visit_services.visit_service_start)', date('Y'));
        $monthearlier= date_format(date_create($day), 'm')-1;
        $monthlater= date_format(date_create($day), 'm')+1;
        //echo $monthearlier; exit();
        $this->db->where('month(visit_services.visit_service_start) <= ',$monthlater );
        $this->db->where('month(visit_services.visit_service_start) >= ', $monthearlier);
        //$this->db->where_in('service_type.service_type', 'Programs, Gym');
        $this->db->where_in('visit_status', ['open', 'invoiced']);        
        $query = $this->db->get('visit_service_staffs');
        //echo $query; exit();
        
        return $query->result();
    }
    
    
    function get_enrollment_services($programentrollmentid){
        
        $this->db->select("program_enrollment.id_program_enrollment, program_enrollment.program_type_id, program_enrollment.customer_id, 
                            id_customers, customers.customer_name, customers.customer_cell, customers.customer_address, customers.customer_gender, customers.father_name, 
                            customers.father_cell, customers.mother_name, customers.mother_cell, customers.father_profession, 
                            customers.mother_profession,    
                            id_program_enrolled_services, service_id, service_name, service_category, total_sessions, per_session_rate ,                                             
                            DATE_FORMAT(program_enrollment.created_on, '%d/%m/%Y') enrollment_date
                            ");
        $this->db->join('program_enrolled_services','program_enrolled_services.program_enrollment_id = program_enrollment.id_program_enrollment');
        $this->db->join('customers','program_enrollment.customer_id = customers.id_customers');        
        $this->db->where('id_program_enrollment',$programentrollmentid);
        $this->db->where('program_enrolled_services.service_status', 'Active');
        $this->db->order_by('id_program_enrolled_services');
        
        $query = $this->db->get('program_enrollment');
        
        //echo $query; exit();
        return $query->result_array();
        
    }
    
     function get_booked_sessions($enrolled_service_id){
        
       $sql="select program_enrolled_service_id, count(id_customer_visits) 'appointments'
            from customer_visits
            join program_enrolled_services on program_enrolled_services.id_program_enrolled_services = customer_visits.program_enrolled_service_id
            where program_enrolled_services.id_program_enrolled_services = ".$enrolled_service_id."
            and customer_visits.visit_status != 'cancelled' 
            and customer_visits.visit_status != 'canceled'
            group by program_enrolled_service_id";
       
       $query = $this->db->query($sql);
       
       return $query->result_array();
        
    }
    
    function get_enrollment_invoices($enrolled_service_id, $enrolled_id=0){
        
        $this->db->select('*, date_format(invoice_date, "%d-%m-%Y") as invoice_date' );
        $this->db->where('program_invoices.business_id', $this->session->userdata('businessid'));
        $this->db->where('program_invoice_status', 'Active');
        $this->db->where('program_enrolled_service_id', $enrolled_service_id);
        if($enrolled_id>0){
            $this->db->where('program_enrollment_id', $enrolled_id);
        }
        $query = $this->db->get('program_invoices');
        return $query->result_array();
    }
    
     function get_invoiced_session_count($enrolled_service_id){
        
       $sql="select program_enrolled_service_id, ifnull(sum(number_of_sessions),0) 'invoiced_sessions'
            from program_invoices
            where program_invoices.program_enrolled_service_id = ".$enrolled_service_id."
            and program_invoices.program_invoice_status='Active'
            group by program_enrolled_service_id";
       
       $query = $this->db->query($sql);
       
       if($query->num_rows() > 0){
          
           return $query->row();
       } else {
           
           $result=(object)[
               'program_enrolled_service_id' => $enrolled_service_id,  
               'invoiced_sessions'=>0
           ];
          
           return $result;
       }
        
    }
    function get_enrollment_with_balance($programentrollmentid){
        $this->db->select('*, program_enrollment.created_by as created_by, (program_enrolled_services.total_sessions * program_enrolled_services.per_session_rate) as total, sum(invoiced_amount) as invoiced_amount, sum(invoice_other_charges) as other_charges, sum(invoice_discount) as discount, sum(paid_amount-cc_charge) as paid, (total_sessions*per_session_rate) - ifnull(sum(invoiced_amount),0) as balance, date_format(invoice_date, "%d/%m/%Y") f_payment_date, date_format(program_enrollment.created_on,"%D %M %Y") created_on, sum(salestax) as salestax', false);
        $this->db->join('program_types','program_types.id_program_types = program_enrollment.program_type_id');
        $this->db->join('customers','program_enrollment.customer_id = customers.id_customers');
        $this->db->join('program_enrolled_services','program_enrollment.id_program_enrollment = program_enrolled_services.program_enrollment_id');
        $this->db->join('program_invoices','program_invoices.program_enrollment_id = program_enrollment.id_program_enrollment and program_enrolled_services.id_program_enrolled_services = program_invoices.program_enrolled_service_id and program_invoice_status = "Active"','left');
        $this->db->where('id_program_enrollment',$programentrollmentid);
        $this->db->where('program_enrolled_services.service_status','Active');        
        $this->db->group_by('id_program_enrollment');
        $this->db->group_by('id_program_enrolled_services');
        
        $query = $this->db->get('program_enrollment');
        
        //echo $query; exit();
        
        return $query->result_array();
        
        
    }
    
    function add_program_advance($adv_data, $enrollment_id){
        
        $this->db->insert('program_advance_note', $adv_data);
        $insert_id = $this->db->insert_id();
        
        
        //create account voucher
        $this->db->select('*');        
        $this->db->join('customers', 'customers.id_customers = program_enrollment.customer_id');        
        $this->db->where('id_program_enrollment', $enrollment_id);
        $query = $this->db->get('program_enrollment');

        $enrollment =  $query->row();
        $debit_accounts=[];
        $credit_accounts=[];

        $account_heads = $this->accounting_model->get_mapped_accounts(2);
        //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='';
        $customer_name= $enrollment->customer_name;
        $customer_id = $enrollment->id_customers;
        
        //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
        $data = array( 
            'business_id' => $this->session->userdata('businessid'),
            'description' => 'Advance Received for Enrollment ID ' . $enrollment_id . ', customer '. $customer_name. ', id '.$customer_id.' on '. $adv_data['advance_date'],
            'voucher_date' => $adv_data['advance_date'],
            'voucher_amount' => $adv_data['advance_amount'],
            '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,
            'business_partner_name'=>$customer_name,
            'voucher_type'=> 2,
            'payment_mode'=> $adv_data['advance_mode'],
            'bank_name' => $bank_name,
            'program_enrollment_id' => $enrollment_id,            
            'auto_voucher'=>'Yes',
            'sale_type'=>'Coaching',
            'visit_advance_id'=>$insert_id
        );

        $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" && $adv_data['advance_mode']=='cash'){ $debitamount = $adv_data['advance_amount'] + $adv_data['advance_cccharge'];}
            if($debit[2]=="paid_card" && $adv_data['advance_mode']=='card'){$debitamount = $adv_data['advance_amount'] + $adv_data['advance_cccharge'];}
            if($debit[2]=="paid_check" && $adv_data['advance_mode']=='check'){$debitamount = $adv_data['advance_amount'] + $adv_data['advance_cccharge'];}
            
            
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $debit[0],
                'instrument_number' => $adv_data['advance_inst'],
                '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
            if($credit[2]=="advance_amount"){$creditamount = $adv_data['advance_amount'] ;}   
            if($credit[2]=="cc_fee"){$creditamount = $adv_data['advance_cccharge'] ;}   
            
            
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $credit[0],
                'instrument_number' => $adv_data['advance_inst'],
                'debit' => 0,
                'credit' => round($creditamount,2)
            );
            //insert credit detail
            if($creditamount>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }
        }
        
        
        
        
        echo $insert_id;
        
    }
    
    function get_remaining_advance($programentrollmentid){
        
        $this->db->select('program_enrollment_id, sum(advance_amount) - sum(advance_used) as advance');
        $this->db->where('program_enrollment_id',$programentrollmentid);
        $this->db->where('advance_status','Active');
        $this->db->group_by('program_enrollment_id');
        $query = $this->db->get('program_advance_note');
        return $query->row();
    }
    
    function get_enrollment_advance($programentrollmentid){
        
        $this->db->select('*, date_format(advance_date, "%d-%m-%Y") as advance_date');
        $this->db->where('program_enrollment_id',$programentrollmentid);
        $this->db->where('advance_status','Active');     
        $this->db->where('advance_amount >',0);     
        $query = $this->db->get('program_advance_note');
        return $query->result_array();
    }
    
    function get_enrollment_session_serivce($id_program_enrolled_services){
        
        $this->db->select('*');
       
        $this->db->where('id_program_enrolled_services',$id_program_enrolled_services);
        $this->db->order_by('id_program_enrolled_services', 'Desc');
        $query = $this->db->get('program_enrolled_services');
        
        return $query->result_array();
        
    }
 
    
    function add_coaching_invoice(){
        //exit();
        $receivable = $this->input->post("txtTotalReceivable");
        $actualInvoice = $this->input->post("txtActualRate");
        $discount = $this->input->post("txtDiscount");
        
        $data = array(
            "program_enrollment_id" => $this->input->post("program_enrollment_id"),
            "program_enrolled_service_id" => $this->input->post("program_enrolled_services_id"),
            "number_of_sessions" => $this->input->post("uninvoiced_sessions"),
            "invoice_number" => $this->input->post(""),
            "invoice_date" => $this->input->post("txtInvoiceDate"),
            "program_invoice_status" => "Active",
            "payment_mode" => "Receivable",
            "program_invoice_remarks" => $this->input->post("remarks"),
            "business_id" => $this->session->userdata("businessid"),
            "invoiced_amount" => $this->input->post("txtTotalReceivable"),
            "invoice_discount" => $this->input->post("txtDiscount"),
            "created_by" => $this->session->userdata("username"),
            "invoice_remarks" => $this->input->post("txt_invoice_remark")            
        );
        
        $this->db->insert('program_invoices', $data);
        $invoice_id = $this->db->insert_id();
       
        $this->db->select("id_customer_visits");
        $this->db->where("program_enrolled_service_id", $this->input->post("program_enrolled_services_id"));
        $this->db->where("visit_status", 'open');
        $this->db->limit($this->input->post("uninvoiced_sessions"));
        $query = $this->db->get("customer_visits");
        
        $visits = $query->result();
        
        foreach($visits as $visit){
            $this->db->where("program_enrolled_service_id", $this->input->post("program_enrolled_services_id"));
            $this->db->where("id_customer_visits", $visit->id_customer_visits);
            $this->db->set("visit_status", "invoiced");
            $this->db->update("customer_visits");
        }
        ///create receivable voucher//////////////////////////////////////////////////////////////////
        $debit_accounts=[];
        $credit_accounts=[];

        $account_heads = $this->accounting_model->get_mapped_accounts(41);
        //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='';
        $customer_name= $this->input->post('customer_name');
        $customer_id = $this->input->post('customer_id');
        
        //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
        $data = array( 
            'business_id' => $this->session->userdata('businessid'),
            'description' => 'Service Sale Receivable Voucher for Enrollment ID ' . $this->input->post("program_enrollment_id") . ', service '. $this->input->post('program_enrolled_services_name') . ' on '. $this->input->post('txtInvoiceDate').', for '.$customer_name,
            'voucher_date' => date('Y-m-d H:i:s'),
            'voucher_amount' => $receivable,
            '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,
            'business_partner_name'=>$customer_name,
            'voucher_type'=> 3,
            'payment_mode'=> '',
            'bank_name' => $bank_name,
            'program_invoice_id' => $invoice_id,            
            'auto_voucher'=>'Yes',
            'sale_type'=>'Coaching',
            'program_enrolled_service_id' => $this->input->post("program_enrolled_services_id")
        );

        $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]=="receivable_amount"){ $debitamount = $receivable;}
            if($debit[2]=="sale_discount"){$debitamount = $this->input->post('txtDiscount');}
            
            $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
            if($credit[2]=="sale_income"){$creditamount = $actualInvoice ;}            
            
            $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);
            }
        }
        
        return $invoice_id;
        
    }
    
     
    function cancel_invoice($invoiceid){
     
        //print_r($this->input->post("program_enrolled_services_id"));exit();
        
        $this->db->select('*');
        $this->db->where('id_program_invoices', $invoiceid);
        $query =$this->db->get('program_invoices');
        $invoice=$query->row();
        
        
        $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'));
        
        $a = $this->db->update('program_invoices');
                 
        
        for($x=1; $x<=$invoice->number_of_sessions; $x++){
            $this->db->where("program_enrolled_service_id", $invoice->program_enrolled_service_id);
            $this->db->where("visit_status !=", 'canceled');
            $this->db->set("visit_status", "open");
            $b = $this->db->update("customer_visits");
        }
        //print_r($this->input->post("program_enrolled_services_id"));exit();
        
        //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')));

        
        ///cancel advance notes
        if(null != $invoiceid){
            $this->db->where('advance_inst', $invoiceid);
            $this->db->where('advance_used >', 0);
            $this->db->set('advance_status','InActive');
            $this->db->update("program_advance_note");
        }
        
        return $this->db->affected_rows();
    }
    
    function getinvocietaxes($invoice_id){
        
        $this->db->select("*");
        $this->db->where('program_invoice_id', $invoice_id);
        $query = $this->db->get("program_invoice_taxes");
        
        return $query->result_array();
        
    }
    
    function get_coaching_invoice($invoice_id){
        $this->db->select("id_program_invoices, invoice_number, number_of_sessions, invoiced_amount, 
            invoice_other_charges, invoice_discount, salestax, paid_amount, advance_used, cc_charge, rounding_adjustment, return_amount,
                        paid_cash, paid_card, paid_check, payment_mode, program_invoice_status as invoice_status, 
                        program_invoices.created_on, date_format(invoice_date,'%d-%m-%Y'),
                        program_invoice_remarks as remarks, program_invoice_remarks as cancelreason, 
                        program_invoices.canceled_by, program_invoices.canceled_on, program_invoices.business_id,  
                        program_invoices.created_by, payment_date, payment_received_by,
                        id_program_enrollment, service_id, service_name, per_session_rate as per_session, total_sessions, 
                        id_customers as customer_id, customers.customer_name, customers.customer_cell, customer_address, customer_email");        
        $this->db->join("program_enrollment", "program_enrollment_id = id_program_enrollment");
        $this->db->join("customers", "customers.id_customers = program_enrollment.customer_id");
        $this->db->join("program_enrolled_services", "program_enrolled_services.id_program_enrolled_services = program_invoices.program_enrolled_service_id");
        $this->db->where('id_program_invoices', $invoice_id);
        $query = $this->db->get("program_invoices");
        $invoice = $query->result_array();
               
        if(sizeof($invoice) == 0){
            $query=null;
            $this->db->select("id_program_invoices, invoice_number, number_of_sessions, invoiced_amount, 
            invoice_other_charges, invoice_discount, salestax, paid_amount, advance_used, cc_charge, 
            rounding_adjustment, return_amount, paid_cash, paid_card, paid_check, payment_mode, 
            program_invoice_status as invoice_status, 
            program_invoices.created_on, date_format(invoice_date,'%d-%m-%Y'),
            program_invoice_remarks as remarks, program_invoice_remarks as cancelreason, 
            program_invoices.canceled_by, program_invoices.canceled_on, program_invoices.business_id,  
            program_invoices.created_by, payment_date, payment_received_by,
            id_program_enrollment, 0 as service_id, program_invoice_remarks as service_name, 
            invoiced_amount as per_session, 0 as total_sessions, 
            id_customers as customer_id, customers.customer_name, customers.customer_cell, customer_address, customer_email");        
            $this->db->join("program_enrollment", "program_enrollment_id = id_program_enrollment");
            $this->db->join("customers", "customers.id_customers = program_enrollment.customer_id");            
            $this->db->where('id_program_invoices', $invoice_id);
            $query = $this->db->get("program_invoices");            
            $invoice = $query->result_array();
        }
        
        //echo $query; exit();
        return $invoice;
    }
    
    function getenrollmentinvocietaxes($enrollment_id, $status=null){
        
        $sql="SELECT invoice_tax_name, sum(invoice_tax) invoice_tax 
        FROM program_invoice_taxes
        join program_invoices on program_invoices.id_program_invoices = program_invoice_taxes.id_program_invoice_taxes
        where program_invoices.program_enrollment_id = ".$enrollment_id." 
        and program_invoices.program_invoice_status = 'Active' ";
        if($status != null){
            $sql .=" and program_invoices.payment_mode = '".$status."' ";
        }
        $sql .=" group by invoice_tax_name";
        //echo $sql; exit();
        $query = $this->db->query($sql);
        return $query->result_array();
    }
    function get_all_enrollment_invoices($enrollment_id, $status=null){

        $sql="SELECT account_head_id, account_head FROM account_event_mapping
        join account_heads on id_account_heads = account_event_mapping.account_head_id
            where account_event_id = 1 and entity_name = 'balance'
             and account_event_mapping.business_id=".$this->session->userdata('businessid').";";
            $query=$this->db->query($sql);
            $ahdata = $query->row();
           $ah = $ahdata->account_head_id;   
           
        
        $this->db->select("id_program_invoices, id_program_enrollment, invoice_number, number_of_sessions,  invoiced_amount,  payment_mode,
        IFNULL(program_invoices.invoice_other_charges,0) as invoice_other_charges, IFNULL(program_invoices.invoice_discount,0) as invoice_discount, salestax, IFNULL(program_invoice_payment.payment_paid_amount,0) as paid_amount, advance_used, IFNULL(program_invoice_payment.payment_cc_charge,0) as cc_charge , rounding_adjustment, return_amount,
        IFNULL(program_invoice_payment.payment_paid_cash,0) as  paid_cash, IFNULL(program_invoice_payment.payment_paid_card,0) as  paid_card, IFNULL(program_invoice_payment.payment_paid_check,0) as  paid_check, payment_mode, 
                        vouchers.paid,
                        vouchers.receivable,
                        vouchers.balance,
                        program_invoice_status as invoice_status, 
                        program_invoices.created_on, date_format(invoice_date,'%d-%m-%Y'),
                        program_invoice_remarks as remarks, program_invoice_remarks as program_invoice_remarks, 
                        program_invoices.canceled_by, program_invoices.canceled_on, program_invoices.business_id,  
                        program_invoices.created_by, payment_date, payment_received_by,
                        id_program_enrollment, service_id, service_name, per_session_rate as per_session, 
                        total_sessions, 
                        invoiced_amount-paid_amount as invoice_balance,
                        id_customers as customer_id, customers.customer_name, customers.customer_cell, customer_address, customer_email, invoice_remarks", false);        
        $this->db->join("program_enrollment", "program_enrollment_id = id_program_enrollment");
        $this->db->join("customers", "customers.id_customers = program_enrollment.customer_id");
        $this->db->join("program_enrolled_services", "program_enrolled_services.id_program_enrolled_services = program_invoices.program_enrolled_service_id", "left");       
        $sql = "(SELECT program_invoice_id,
                sum(debit) as receivable, 
                sum(credit) as paid, 
                round(sum(debit)-sum(credit),2) as balance
                FROM account_vouchers 
                join account_voucher_detail on account_voucher_detail.account_voucher_id=account_vouchers.id_account_vouchers
                and account_head_id=".$ah." where account_vouchers.voucher_status !='Cancelled'  group by program_invoice_id) as vouchers";
            // SQL query to calculate the sum of various payment methods for each program invoice
        $this->db->join($sql, 'vouchers.program_invoice_id = program_invoices.id_program_invoices');   

            // Subquery for program invoice payments
            $sql_payments = "(SELECT 
            program_invoice_payments.program_invoice_id, 
            IFNULL(SUM(program_invoice_payments.paid_amount), 0) AS payment_paid_amount,
            IFNULL(SUM(program_invoice_payments.paid_cash), 0) AS payment_paid_cash,
            IFNULL(SUM(program_invoice_payments.paid_card), 0) AS payment_paid_card,
            IFNULL(SUM(program_invoice_payments.paid_check), 0) AS payment_paid_check,
            IFNULL(SUM(program_invoice_payments.paid_online), 0) AS payment_paid_online,
            IFNULL(SUM(program_invoice_payments.paid_other), 0) AS payment_paid_other,
            IFNULL(SUM(program_invoice_payments.cc_charge), 0) AS payment_cc_charge,
            IFNULL(SUM(program_invoice_payments.other_charges), 0) AS payment_other_charges,
            IFNULL(SUM(program_invoice_payments.payment_discount), 0) AS payment_discount
            FROM program_invoice_payments  
            JOIN program_invoices ON program_invoice_payments.program_invoice_id = program_invoices.id_program_invoices
            WHERE program_invoice_payments.payment_status != 'Cancelled'
            GROUP BY program_invoice_payments.program_invoice_id) as program_invoice_payment";
            $this->db->join($sql_payments, 'program_invoice_payment.program_invoice_id = program_invoices.id_program_invoices' , "left");
                    $this->db->where('program_enrollment.id_program_enrollment', $enrollment_id);        
                    $this->db->where('program_invoices.program_invoice_status ', 'Active'); 
                    if(null != $status){
                        $this->db->where('program_invoices.payment_mode', $status);
                    }
                    $query = $this->db->get("program_invoices");
                    //echo $query; exit();
                    return $query->result_array();
   } 
   function get_session_payments($program_session_service_id){
        
        $this->db->select('*, program_invoices.created_by created_by, date_format(program_enrollment.created_on, "%d/%m/%Y") enrollment_date, date_format(invoice_date, "%d/%m/%Y") invoice_date');
        $this->db->join('program_types','program_types.id_program_types = program_enrollment.program_type_id');
        $this->db->join('program_enrolled_services','program_enrolled_services.program_enrollment_id = program_enrollment.id_program_enrollment');
        $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_enrolled_services.id_program_enrolled_services = program_invoices.program_enrolled_service_id  and program_invoice_status = "Active"','left');
        $this->db->where('program_invoices.program_enrolled_service_id',$program_session_service_id);
        
        $this->db->order_by('id_program_invoices', 'Desc');
        $query = $this->db->get('program_enrollment');
        
        //  echo $query; exit();
        
        return $query->result_array();
        
    }
    
    function get_session_paid_amount($program_session_service_id){
        $this->db->select('sum(program_invoices.invoiced_amount) as paid_amount');
        $this->db->where('program_invoices.program_invoice_status','Active');
        $this->db->where('program_invoices.program_enrolled_service_id',$program_session_service_id);
        $query = $this->db->get('program_invoices');
        
        return $query->row();
    }
    
    function add_invoice_payment(){
      // exit();
        $invoice_id = $this->input->post('txtinvoiceid'); 
        
        if($invoice_id == null || $invoice_id < 1){            
            $this->session->set_flashdata('Error', 'Invoice ID is missing, Payment was not entered!');           
            return -1;
        }
        
        if($this->input->post("txtTotalPayment")==0){
            $this->session->set_flashdata('Error', 'Your Payment Amount is 0, Payment was not entered!');           
            return -1;
            
        }
        
        if($this->input->post("txtTotalPayment") > $this->input->post("grandtotal")){
            $this->session->set_flashdata('Error', 'Your Payment Amount is More then the Total RECEIVABLE, Payment was not entered!');           
            return -1;
            
        }
        
        if($this->input->post("txtTotalPayment") !== $this->input->post("grandtotal")){
            $this->session->set_flashdata('Error', 'Your Payment Amount is different from the Total RECEIVABLE, Payment was not entered!');           
            return -1;
            
        }
        
        
        $enrollment_id = $this->input->post('txtpaymentenrollmentid');
        $paidcash = $this->input->post('cashpaid'); 
        $paidcard = $this->input->post('cardpaid'); 
        $paidcheck = $this->input->post('checkpaid'); 
        $paid_amount = $this->input->post('txtTotalPayment');
        $txtreceivedpreviously = $this->input->post('txtreceivedpreviously')==null ? 0 :  $this->input->post('txtreceivedpreviously');
        $advance_used = $this->input->post('advance');
        $invoice_remarks = $this->input->post('txtinvoicecomments');
        
        $salestax = $this->input->post('sales_tax');
        $tax_name= $this->input->post('tax_name');     
        $totaltax=0;
        
       // print_r($tax_name); exit();
        foreach($salestax as $tax){
            
            $totaltax = $totaltax + $tax;
        }
        
        $paymentdate = $this->input->post('txtPaymentDate'); 
        $roundedadjustment = $this->input->post('txtroundadj');
        $cc_charge=$this->input->post('txtcc_charge');
        $other_charges =$this->input->post('txtothercharges');         
        $returnamount=$this->input->post('returnamount');         
        $paymentmode="Mixed";
        if($paidcash > 0 && $paidcard == 0 && $paidcheck == 0){$paymentmode='Cash';}
        if($paidcash == 0 && $paidcard > 0 && $paidcheck == 0){$paymentmode='Card';}
        if($paidcash == 0 && $paidcard == 0 && $paidcheck > 0){$paymentmode='Check';}
        if($advance_used>0){$paymentmode='AdvanceUsed';}
        
         //get invoice
            $this->db->select("customer_name, customer_id, id_program_invoices, program_enrolled_service_id, id_program_enrollment,
                    paid_amount, paid_cash, paid_card, paid_check, 
                    rounding_adjustment, cc_charge, return_amount, invoice_other_charges");            
            $this->db->join("program_enrollment", "program_enrollment.id_program_enrollment = program_invoices.program_enrollment_id");
            $this->db->join("customers", "program_enrollment.customer_id = customers.id_customers");
            $this->db->join("program_enrolled_services", "program_enrolled_services.id_program_enrolled_services = program_invoices.program_enrolled_service_id", 'Left');
            $this->db->where("id_program_invoices", $invoice_id);
            $query =$this->db->get("program_invoices");
            
            $invoice_data = $query->row();
        // $data = array(
        //     'payment_date'=> $paymentdate,
        //     'paid_amount'=> $paid_amount + $txtreceivedpreviously,
        //     'advance_used'=> $advance_used,
        //     'paid_cash'=> $invoice_data->paid_cash + $paidcash,
        //     'paid_card'=> $invoice_data->paid_card + $paidcard,
        //     'paid_check'=> $invoice_data->paid_check + $paidcheck,     
        //     'payment_mode'=> $paymentmode, 
        //     'salestax'=> $totaltax, 
        //     'invoice_other_charges'=> $other_charges,//$invoice_data->paid_amount > 0 ? $other_charges : $invoice_data->invoice_other_charges, 
        //     'cc_charge'=> $invoice_data->cc_charge + $cc_charge,  
        //     'rounding_adjustment'=> $invoice_data->rounding_adjustment + $roundedadjustment, 
        //     'return_amount' => $invoice_data->return_amount + $returnamount,
        //     'payment_received_by' => $this->session->userdata('username') ,
        //     'invoice_remarks' => $invoice_remarks,
        //     'invoice_balance' => 0
            
        //     ); 
        
        // $this->db->where("id_program_invoices", $invoice_id);
        // $this->db->update('program_invoices', $data);    
        
         $data = array(     
            'program_invoice_id' => $invoice_id,
            'cc_charge' => $cc_charge,
            'paid_cash'=>$paidcash,
            'paid_card'=>$paidcard,
            'paid_check'=>$paidcheck,    
            'paid_amount'=> $paid_amount,                      
            'payment_mode' =>  $paymentmode,
            'payment_date'  => $paymentdate,
            'payment_received_by'  => $this->session->userdata('username'),                        
            'other_charges'  => $other_charges,
            'payment_status'=>'Paid',
            'created_by'=> $this->session->userdata('username')                       
           );
              // Insert the payment data into the table
            $this->db->insert('program_invoice_payments', $data);
            $program_invoice_payments_id= $this->db->insert_id();
    
                
        if($this->db->affected_rows() > 0){
            //////insert advance note///////
            $advance_note_id=0;
            if($advance_used>0){
                $adv_data= array(            
                    'program_enrollment_id' => $enrollment_id,
                    'advance_amount' => 0,                
                    'advance_inst' => $invoice_id,                
                    'advance_remarks' => 'Advance used for payment of invoice '.$invoice_id,
                    'advance_date' => $paymentdate,
                    'advance_used' => $advance_used
                );

                $this->db->insert('program_advance_note', $adv_data);
                $advance_note_id = $this->db->insert_id();
            }
            
            //////insert invoice taxes//////
            if(isset($salestax)){                
                $x=0;
                foreach($salestax as $tax){
                    $data=array(
                        'program_invoice_id'=>$invoice_id,
                        'business_id'=>$this->session->userdata('businessid'),
                        'invoice_tax_name'=>$tax_name[$x],
                        'invoice_tax'=>$tax
                    );
                    $this->db->insert('program_invoice_taxes', $data);
                    $x++;
                }
            }            
           
            //////create the account voucher for the payment////////
            if($this->session->userdata('auto_voucher')=='Yes'){
                $debit_accounts=[];
                $credit_accounts=[];

                $account_heads = $this->accounting_model->get_mapped_accounts(30);
                //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='Coaching';

                $data = array( 
                    'business_id' => $this->session->userdata('businessid'),
                    'description' => 'Invoice Clearence Receiving Voucher against invoice ' . $invoice_id . ' on '. $paymentdate.', from '.$invoice_data->customer_name.' customer ID : '. $invoice_data->customer_id,
                    'voucher_date' => $paymentdate,
                    'voucher_amount' => $paid_amount,
                    'voucher_status' => 'Active',
                    'created_by' => $this->session->userdata('username'),
                    'cost_center'=> '1',
                    'cost_center_name'=> 'Front Desk',
                    'business_partner'=> 1,
                    'business_partner_id'=>$invoice_data->customer_id,
                    'business_partner_name'=>$invoice_data->customer_name,
                    'voucher_type'=>2,
                    'payment_mode'=>$paymentmode,
                    'bank_name'=>$bank_name,
                    'program_invoice_id'=>$invoice_id,
                    'auto_voucher'=>'Yes',
                    'sale_type'=>$saletype,
                    'program_enrolled_service_id'=>$invoice_data->program_enrolled_service_id,
                    'program_enrollment_id'=> $invoice_data->id_program_enrollment,
                    'visit_advance_id'=>$advance_note_id,
                    'program_invoice_payment_id'=>$program_invoice_payments_id,
                );

                $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;}
                    if($debit[2]=="advance_used" && $advance_used > 0){$debitamount= $advance_used;}
                    
                   // if($debit[2]=="rounded_adjustment" && $this->input->post('txtroundadj') > 0){$debitamount= $this->input->post('txtroundadj');}
                    if($debit[2]=="rounded_adjustment"){ 
                        if($roundedadjustment < 0){

                            $debitamount=$roundedadjustment*-1;
                        }

                    }
                    
                    
                    $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

                    if($credit[2]=="balance"){$creditamount= $this->input->post('txtinvoicereceivable');}
                    if($credit[2]=="sales_tax"){$creditamount= $totaltax;}
                    if($credit[2]=="other_charges"){$creditamount= $this->input->post('txtothercharges');}                    
                    if($credit[2]=="cc_fee"){$creditamount= $this->input->post('txtcc_charge');}                    
                    if($credit[2]=="return_cash"){$creditamount= $this->input->post('returnamount');}
                    //if($credit[2]=="rounded_adj"){$creditamount= $this->input->post('txtroundadj');}                       
                    if($credit[2]=="rounded_adjustment"){ 
                        if($roundedadjustment > 0){
                            $creditamount=$roundedadjustment; 
                        }

                    }
                    $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);
                    }
                }
            }
             return $invoice_id;
             /////Account voucher end
        } else {
            return -1;
        }
    }
    
    
    function get_program_enrolled_services($program_enrollment_id){
        
        $this->db->select('*');
        $this->db->where('program_session_id', $program_enrollment_id);
        
        $query = $this->db->get('program_enrolled_services');
        
        return $query->result_array();
    }
    
    
    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,
                'total_sessions' => $this->input->post('total_sessions'),
                'per_session_rate' => $this->input->post('per_session_rate')
            );
         
         $this->db->insert('program_enrolled_services', $data);
         return $this->db->insert_id();
    }
    
    
    
    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,
                'total_sessions' => $this->input->post('total_sessions'),
                'per_session_rate' => $this->input->post('per_session_rate'),
                'service_status' => $this->input->post('service_status')
            );
         $this->db->where('id_program_enrolled_services', $this->input->post('id_program_enrolled_services'));
         $this->db->update('program_enrolled_services', $data);
         
         return $this->db->affected_rows();
    }
    
    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_enrolled_services', $serviecid);
        $query = $this->db->get('program_enrolled_services');
        
        return $query->row();
        
    }
    
  
    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_type_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('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_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, total_sessions, per_session_rate');
                $this->db->where('service_id', $serviceid);
                $query1 = $this->db->get('program_enrolled_services');
                
                $result1 = $query1->row();

                $allowedmonth = $result1->total_sessions;
                $allowedsession = $result1->per_session_rate;
                
                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_type_id
            WHERE  `service_id` in (".$service_ids.") 
            AND `id_customers` = ".$customer_id." 
            AND visit_services.membership = 'Yes'
            AND `visit_status` != 'canceled' 
            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();
    }
    
    
    function get_groups($status=null, $serviceid=null){
        //echo $serviceid; exit();
        $sql="(select program_group_id, COUNT(id_program_group_members) AS members
        FROM program_group_members 
            WHERE program_group_members.member_status = 'Active'
        Group by program_group_id) as memberdata"; 

        $sql2="(SELECT   `group_visits`.`group_id`, COUNT(group_id) as total_schedule FROM 
                 `group_visits` GROUP by `group_visits`.`group_id`) as  each_group_total_visit";
        
        $this->db->select('program_groups.*, each_group_total_visit.total_schedule , date_format(created_on,"%d-%m-%Y") as created_on, ifnull(memberdata.members,0) as members ', false);
      
        $this->db->join($sql, 'program_groups.id_program_groups = memberdata.program_group_id','left', false);
        $this->db->join($sql2, 'program_groups.id_program_groups = each_group_total_visit.group_id','left', false);
        $this->db->where('program_groups.business_id', $this->session->userdata('businessid'));
        if(null != $status){
            $this->db->where('program_groups.group_status', $status);
        }
        if(null != $serviceid && $serviceid > 0){
            $this->db->where('program_groups.program_service_id', $serviceid);
        }
        $this->db->order_by('id_program_groups','Desc');
        $query = $this->db->get('program_groups');
        
        return $query->result();        
    }
    
    function get_group_members($groupid, $status=null){
        //echo $serviceid; exit();
        
        
        if($this->input->post('group_status')!= null && $this->input->post('group_status')!= 'All'){
            $status = $this->input->post('group_status');
        }
        
        $sql="SELECT program_group_members.*, customers.customer_name, customers.customer_cell
            FROM program_group_members
            join program_groups on program_groups.id_program_groups = program_group_members.program_group_id
            join program_enrollment on program_enrollment.id_program_enrollment = program_group_members.program_enrollment_id
            join customers on customers.id_customers=program_enrollment.customer_id
            where program_group_members.program_group_id= ".$groupid;
        
        
        if(null != $status){
            $sql.= " AND program_group_members.member_status = '".$status."' ";
        }
        
        $sql.= " order by id_program_group_members Desc";
        
        $query = $this->db->query($sql);
        
        return $query->result();        
    }
    
    function get_group($groupid){
        //echo $serviceid; exit();
        $sql="SELECT *
            FROM program_groups             
            where program_groups.id_program_groups= ".$groupid;
        
        $query = $this->db->query($sql);
        
        return $query->row();        
    }
    
    function get_enrollments_by_service($program_service_id, $keyword=null){
        
        $sql = "SELECT program_enrolled_services .*, id_program_enrollment, customers.customer_name, customers.customer_cell, id_customers
                FROM program_enrollment 
                join customers on customers.id_customers=program_enrollment.customer_id
                join program_enrolled_services on program_enrolled_services.program_enrollment_id = program_enrollment.id_program_enrollment
                where program_enrolled_services.service_id = ".$program_service_id."
                AND program_enrolled_services.service_status='Active' ";
        
        if(null != $keyword && key != 'null'){
            
            $sql .= " AND (customer_name like '%".$keyword."%' OR customer_cell like '%".$keyword."%'";
            
        }
        
        
        $query = $this->db->query($sql);
        
        return $query->result_array();       
        
    }
    
    
    function get_coaching_invoice_detail($invoice_id){
        $this->db->select('*');
        $this->db->where('id_program_invoices', $invoice_id);
        $query = $this->db->get('program_invoices');
       // print_r($query->row()); exit();
        return $query->row();
    }
    
    function get_bynameco($match, $groupid) {
       
        $this->db->select('program_service_id');
        $this->db->where('id_program_groups', $groupid);
        $query = $this->db->get('program_groups');
        $data= $query->row();
        $service_id=$data->program_service_id;
        
        
        $this->db->select('id_customers, id_program_enrollment, customer_name, customer_cell, customer_name as "id"');
        $this->db->join('program_enrollment','customer_id = id_customers');
        $this->db->join('program_enrolled_services','program_enrollment.id_program_enrollment = program_enrolled_services.program_enrollment_id');
       
        $this->db->where('program_enrolled_services.service_id', $service_id);
        $a = '(customer_name like "%'.$match.'%" OR customer_cell like "%'.$match.'%")';
        $this->db->where($a);         
        
        
        //$this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customers');
        
        return $query->result_array();
    }

    
    function get_group_visits($id_program_groups, $start, $end){
        
        $this->db->select('visit_service_staffs.staff_name, visit_service_staffs.staff_id, customer_visits.group_id, visit_service_start,
                date_format(visit_service_start, "%d-%m-%Y") as startformatted, date_format(visit_service_end, "%d-%m-%Y") as endformatted,
                date_format(visit_service_start, "%H:%i") as starttime, date_format(visit_service_end, "%H:%i") as endtime, 
                visit_service_start start,  visit_service_end end,  count(id_customer_visits) as visits ');
        $this->db->join('customer_visits','id_customer_visits = visit_services.customer_visit_id');
        $this->db->join('customers','id_customers = customer_visits.customer_id');        
        $this->db->join('visit_service_staffs','visit_service_staffs.visit_service_id = visit_services.id_visit_services');  
        $this->db->where('customer_visits.group_id', $id_program_groups);
        $this->db->where_in('visit_status', ['open', 'invoiced']);
        $this->db->where('date(visit_service_start) >=', $start);
        $this->db->where('date(visit_service_start) <=', $end);
        $this->db->group_by('customer_visits.group_id');
        $this->db->group_by('date(visit_service_start)');
        $this->db->group_by('staff_id');
        $query = $this->db->get('visit_services');
        
         return $query->result_array();
        
        
    }
    
    function get_group_table_visits($id_program_groups, $start, $end, $type=null){        
       
        $this->db->select('id_group_visits as id, group_id, program_group, service_id, 
            staff.staff_fullname as staff_name, 
            date_format(visit_service_start, "%d-%m-%Y") as startformatted, 
            date_format(visit_service_end, "%d-%m-%Y") as endformatted,
            date_format(visit_service_start, "%H:%i") as starttime, 
            date_format(visit_service_end, "%H:%i") as endtime, 
            visit_service_start  as start,  visit_service_end as end, 
            staff_id resourceId,
            concat(program_group," For ", business_services.service_name," - With ", staff.staff_fullname," - Booked: ", group_visits.created_by, " - At: ", date_format(visit_service_start,"%H:%i:%s")) as title, 
            "#fff" as textColor, 
            "GroupSession" as event_type,
            visit_status,
            CASE WHEN visit_status = "invoiced"  THEN false
            ELSE true END as editable,
            CASE WHEN group_visits.visit_status = "invoiced" THEN "#c7c7c7"
            ELSE service_color  END as borderColor,
            service_color as backgroundColor,                
            group_visits.created_by as created_by                
            ', false);
        $this->db->join('business_services', 'business_services.id_business_services = group_visits.service_id');
        $this->db->join('staff', 'staff.id_staff = group_visits.staff_id');
        $this->db->join('program_groups','program_groups.id_program_groups = group_visits.group_id');
        $this->db->where('id_program_groups', $id_program_groups);
        $query = $this->db->get('group_visits');
            
        
        if(null==$type || $type != 'array'){
            return $query->result();
        }else {
            return $query->result_array();
        }
        
        
    }
    
    function get_group_member_visits($id_program_groups, $start, $end, $type=null){       
       // echo $id_program_groups; exit();
        if($type != 'array'){
            $this->db->select('id_customer_visits as id, id_customers, customer_name, id_visit_services, 
                visit_service_staffs.id_visit_service_staffs, visit_service_staffs.staff_name, 
                date_format(visit_service_start, "%d-%m-%Y") as startformatted, date_format(visit_service_end, "%d-%m-%Y") as endformatted,
                date_format(visit_service_start, "%H:%i") as starttime, date_format(visit_service_end, "%H:%i") as endtime, 
                visit_service_start start,  visit_service_end end, 
                visit_service_staffs.staff_id resourceId,
                concat(customer_name," For ", business_services.service_name," - With ",visit_service_staffs.staff_name," - Booked: ", customer_visits.created_by, " - At: ", date_format(visit_service_start,"%H:%i:%s")) as title, 
                "#fff" as textColor, 
                "Session" as event_type,
                visit_status,
                CASE WHEN customer_visits.visit_status = "invoiced" 
                THEN false
                ELSE true
                END as editable,
                CASE WHEN customer_visits.visit_status = "invoiced" THEN "#c7c7c7"
                ELSE service_color                 
                END as borderColor,
                service_color as backgroundColor,
                
                CASE WHEN customer_visits.inservice="Yes" THEN "check" ELSE "" END as inservice,
                customer_visits.created_by as created_by                
                ', false);
        
        } else {
            $this->db->select('visit_service_staffs.staff_name, 
                date_format(visit_service_start, "%d-%m-%Y") as startformatted, date_format(visit_service_end, "%d-%m-%Y") as endformatted,
                date_format(visit_service_start, "%H:%i") as starttime, date_format(visit_service_end, "%H:%i") as endtime, 
                visit_service_start start,  visit_service_end end,  count(id_customer_visits) as visits ');
        }
        
        $this->db->join('customer_visits','id_customer_visits = visit_services.customer_visit_id');
        $this->db->join('customers','id_customers = customer_visits.customer_id');        
        $this->db->join('visit_service_staffs','visit_service_staffs.visit_service_id = visit_services.id_visit_services');        
        $this->db->join('business_services','business_services.id_business_services = visit_services.service_id');
        $this->db->join('program_enrollment', 'program_enrollment.customer_id = customers.id_customers');
        $this->db->join('program_group_members', 'program_group_members.program_enrollment_id = program_enrollment.id_program_enrollment and member_status="Active"');
        $this->db->join('program_groups', 'program_groups.id_program_groups = program_group_members.program_group_id');
        $this->db->where('program_groups.id_program_groups', $id_program_groups);
        $this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $this->db->where_in('visit_status', ['open', 'invoiced']);
        $this->db->where('date(visit_service_start) >=', $start);
        $this->db->where('date(visit_service_start) <=', $end);
        if($type=='array'){
            $this->db->group_by('program_groups.id_program_groups');
            $this->db->group_by('date(visit_service_start)');
            $this->db->group_by('staff_id');
        }
        $query = $this->db->get('visit_services');
        
       // echo $query; exit();
        if(null==$type || $type != 'array'){
            return $query->result();
        }else {
            return $query->result_array();
        }
    } 




    function get_each_enrollment_invoices($enrollment_id,$invoice_id){
        $status =null;
      
        $sql="SELECT account_head_id, account_head FROM account_event_mapping
        join account_heads on id_account_heads = account_event_mapping.account_head_id
            where account_event_id = 1 and entity_name = 'balance'
             and account_event_mapping.business_id=".$this->session->userdata('businessid').";";
            $query=$this->db->query($sql);
            $ahdata = $query->row();
           $ah = $ahdata->account_head_id;   
           
        
        $this->db->select("id_program_invoices, id_program_enrollment, invoice_number, number_of_sessions,  invoiced_amount,  payment_mode,
        IFNULL(program_invoices.invoice_other_charges,0) as invoice_other_charges, IFNULL(program_invoices.invoice_discount,0) as invoice_discount, salestax, IFNULL(program_invoice_payment.payment_paid_amount,0) as paid_amount, advance_used, IFNULL(program_invoice_payment.payment_cc_charge,0) as cc_charge , rounding_adjustment, return_amount,
        IFNULL(program_invoice_payment.payment_paid_cash,0) as  paid_cash, IFNULL(program_invoice_payment.payment_paid_card,0) as  paid_card, IFNULL(program_invoice_payment.payment_paid_check,0) as  paid_check, payment_mode, 
                        vouchers.paid,
                        vouchers.receivable,
                        vouchers.balance,
                        program_invoice_status as invoice_status, 
                        program_invoices.created_on, date_format(invoice_date,'%d-%m-%Y'),
                        program_invoice_remarks as remarks, program_invoice_remarks as program_invoice_remarks, 
                        program_invoices.canceled_by, program_invoices.canceled_on, program_invoices.business_id,  
                        program_invoices.created_by, payment_date, payment_received_by,
                        id_program_enrollment, service_id, service_name, per_session_rate as per_session, 
                        total_sessions, 
                        invoiced_amount-paid_amount as invoice_balance,
                        id_customers as customer_id, customers.customer_name, customers.customer_cell, customer_address, customer_email, invoice_remarks", false);        
        $this->db->join("program_enrollment", "program_enrollment_id = id_program_enrollment");
        $this->db->join("customers", "customers.id_customers = program_enrollment.customer_id");
        $this->db->join("program_enrolled_services", "program_enrolled_services.id_program_enrolled_services = program_invoices.program_enrolled_service_id", "left");       
        $sql = "(SELECT program_invoice_id,
                sum(debit) as receivable, 
                sum(credit) as paid, 
                round(sum(debit)-sum(credit),2) as balance
                FROM account_vouchers 
                join account_voucher_detail on account_voucher_detail.account_voucher_id=account_vouchers.id_account_vouchers
                and account_head_id=".$ah." where account_vouchers.voucher_status !='Cancelled'  group by program_invoice_id) as vouchers";
            // SQL query to calculate the sum of various payment methods for each program invoice
        $this->db->join($sql, 'vouchers.program_invoice_id = program_invoices.id_program_invoices');   

            // Subquery for program invoice payments
            $sql_payments = "(SELECT 
            program_invoice_payments.program_invoice_id, 
            IFNULL(SUM(program_invoice_payments.paid_amount), 0) AS payment_paid_amount,
            IFNULL(SUM(program_invoice_payments.paid_cash), 0) AS payment_paid_cash,
            IFNULL(SUM(program_invoice_payments.paid_card), 0) AS payment_paid_card,
            IFNULL(SUM(program_invoice_payments.paid_check), 0) AS payment_paid_check,
            IFNULL(SUM(program_invoice_payments.paid_online), 0) AS payment_paid_online,
            IFNULL(SUM(program_invoice_payments.paid_other), 0) AS payment_paid_other,
            IFNULL(SUM(program_invoice_payments.cc_charge), 0) AS payment_cc_charge,
            IFNULL(SUM(program_invoice_payments.other_charges), 0) AS payment_other_charges,
            IFNULL(SUM(program_invoice_payments.payment_discount), 0) AS payment_discount
            FROM program_invoice_payments  
            JOIN program_invoices ON program_invoice_payments.program_invoice_id = program_invoices.id_program_invoices
            WHERE program_invoice_payments.payment_status != 'Cancelled'
            GROUP BY program_invoice_payments.program_invoice_id) as program_invoice_payment";
            $this->db->join($sql_payments, 'program_invoice_payment.program_invoice_id = program_invoices.id_program_invoices' , "left");
            $this->db->where('program_enrollment.id_program_enrollment', $enrollment_id); 
            $this->db->where('program_invoices.id_program_invoices ', $invoice_id);       
                    $this->db->where('program_invoices.program_invoice_status ', 'Active'); 
                    if(null != $status){
                        $this->db->where('program_invoices.payment_mode', $status);
                    }
                    $query = $this->db->get("program_invoices");

                    
                    //echo $query; exit();
                    return $query->result_array();
    } 

    function invoice_each_payments_data($invoice_id){ 


        $sql = "SELECT program_invoice_payments.* FROM `program_invoices`  INNER join program_invoice_payments on  program_invoice_payments.program_invoice_id = `program_invoices`.`id_program_invoices` 
        where `program_invoices`.`id_program_invoices` =$invoice_id and  `program_invoices`.`program_invoice_status`='Active' and  program_invoice_payments.payment_status='Paid'";
        $resp = $this->db->query($sql);
        $data = $resp->result();
        return $data;

    } 
    function cancel_program_invoice_payment() { 
        $invoice_id = $_POST['invoice_id']; 
        $program_invoice_paymentid = $_POST['program_invoice_paymentid'];  
    
        // Cancel voucher
        $this->db->set('voucher_status', 'Cancelled');
        $this->db->set('cancelled_on', date('Y-m-d H:i:s'));
        $this->db->set('cancelled_by', $this->session->userdata('username'));
        $this->db->where('program_invoice_payment_id', $program_invoice_paymentid);
        $this->db->update('account_vouchers'); 
    
        // Update payment status
        $this->db->set('payment_status', 'Cancelled'); 
        $this->db->where('id_program_invoice_payments', $program_invoice_paymentid); 
        $this->db->update('program_invoice_payments'); 
    
        $response = array('status' => 'success', 'message' => 'Invoice payment cancelled successfully.');
    
        // Return or echo response
        echo json_encode($response);
    } 


    function get_program_groups(){ 

        $sql = "SELECT * FROM `program_groups` where business_id =? and group_status =?";
        $resp = $this->db->query($sql, array($this->session->userdata('businessid'),'Active'));
        return $data = $resp->result();

    }
    
    function get_program_groups_attendance_report($program_group_id, $staff_id, $today) { 
        // Escaping variables to prevent SQL injection
        $program_group_id = $this->db->escape($program_group_id);
        $staff_id = $this->db->escape($staff_id);
        $today = $this->db->escape($today);
        $sql = "SELECT 
                    customer_visits.id_customer_visits, 
                    program_groups.id_program_groups, 
                    program_groups.program_group, 
                    program_groups.program_service_name,  
                    staff.staff_fullname, 
                    customers.customer_name, 
                    group_visits.group_visit_date, 
                    group_visits.visit_service_start, 
                    group_visits.visit_service_end, 
                    customer_visits.inservice, 
                    customer_visits.inservice_time 
                FROM 
                    program_groups 
                INNER JOIN 
                    customer_visits ON program_groups.id_program_groups = customer_visits.group_id
                INNER JOIN 
                    group_visits ON group_visits.id_group_visits = customer_visits.group_visit_id 
                INNER JOIN 
                    staff ON staff.id_staff = group_visits.staff_id
                INNER JOIN 
                    customers ON customers.id_customers = customer_visits.customer_id"; 
            if ($program_group_id === $this->db->escape('individual')) {
                // $sql .= " INNER JOIN visit_service_staffs ON visit_service_staffs.customer_visit_id = customer_visits.id_customer_visits";
                // $sql .= " WHERE customer_visits.group_id = 0";
                // $sql .= " AND visit_service_staffs.staff_id = $staff_id"; 
                $sql="SELECT 
                            customer_visits.id_customer_visits, 
                            visit_services.service_name  as program_service_name,  
                            staff.staff_fullname, 
                            customers.customer_name, 
                            customer_visits.customer_visit_date as group_visit_date, 
                        visit_services.visit_service_start as visit_service_start, 
                        visit_services.visit_service_end as visit_service_end, 
                            customer_visits.inservice, 
                            customer_visits.inservice_time 
                        FROM customer_visits
                        INNER JOIN visit_services ON visit_services.customer_visit_id = customer_visits.id_customer_visits
                        INNER JOIN visit_service_staffs ON visit_service_staffs.customer_visit_id = customer_visits.id_customer_visits
                        INNER JOIN staff ON staff.id_staff = visit_service_staffs.staff_id
                        INNER JOIN customers ON customers.id_customers = customer_visits.customer_id  
                        where  visit_service_staffs.staff_id = $staff_id  and customer_visits.group_id = 0 and visit_services.visit_service_status='Active'  and   date( customer_visits.customer_visit_date) = $today
                         GROUP by  customer_visits.id_customer_visits" ;
                } else {
                    $sql .= " WHERE program_groups.id_program_groups = $program_group_id"; 
                    $sql .= " AND program_groups.group_status = 'Active'  
                    AND group_visits.staff_id = $staff_id 
                    AND DATE(group_visits.group_visit_date) = $today";
                } 
                
        $resp = $this->db->query($sql);
        return $resp->result();
    } 


    function get_program_groups_attendance_reports_without_staff($program_group_id, $today,$enddate,$member_id) { 
        // Escaping variables to prevent SQL injection
        $program_group_id = $this->db->escape($program_group_id);
        $startdate = $this->db->escape($today);
        $enddate = $this->db->escape($enddate);
        $member_id = $this->db->escape($member_id);
        
        // Construct the SQL query
                    $sql = "SELECT 
                    customer_visits.id_customer_visits, 
                    program_groups.id_program_groups, 
                    program_groups.program_group, 
                    program_groups.program_service_name,  
                    customers.customer_name, 
                    group_visits.group_visit_date, 
                    group_visits.visit_service_start, 
                    group_visits.visit_service_end, 
                    customer_visits.inservice, 
                    customer_visits.inservice_time 
                FROM 
                    program_groups 
                INNER JOIN 
                    customer_visits ON program_groups.id_program_groups = customer_visits.group_id
                INNER JOIN 
                    group_visits ON group_visits.id_group_visits = customer_visits.group_visit_id 
                INNER JOIN 
                    customers ON customers.id_customers = customer_visits.customer_id
                WHERE 
                    program_groups.id_program_groups = $program_group_id 
                    AND program_groups.group_status = 'Active'";
                if ($member_id !== $this->db->escape('All')) {
                     $sql .= " AND customer_visits.customer_id = $member_id";
                }
                $sql.="GROUP BY 
                    customer_visits.id_customer_visits";

            $resp = $this->db->query($sql);
            return $resp->result();
        
    }
    
    function get_group_by_program($program_id){ 
        $sql="SELECT * FROM `program_groups` where program_service_id=? and  business_id =? and group_status=?"; 
        $resp = $this->db->query($sql, array($program_id,$this->session->userdata('businessid'),'Active'));
        return $data = $resp->result();
    } 


    function getting_enroll_customer(){ 

        $sql="SELECT customers.id_customers , customers.customer_name , total_sessions , ifnull(sessions.scheduled,0) as scheduled
        FROM program_enrolled_services
        JOIN program_enrollment on program_enrollment.id_program_enrollment = program_enrolled_services.program_enrollment_id
        JOIN program_types on program_types.id_program_types = program_enrollment.program_type_id 
        JOIN customers on customers.id_customers = program_enrollment.customer_id 
        
        LEFT JOIN(
             select program_enrolled_service_id, ifnull(count(*),0) as scheduled from customer_visits
            where customer_visits.visit_status in('open', 'invoiced')    
            and program_enrolled_service_id > 0
             group by program_enrolled_service_id
        ) as sessions on sessions.program_enrolled_service_id = program_enrolled_services.id_program_enrolled_services
        WHERE 1=1   
        AND program_enrollment.business_id = ? 
        group by customers.id_customers"; 
        $resp = $this->db->query($sql, array($this->session->userdata('businessid')));
        return $data = $resp->result();
     }
    

    
    
}
