<?php

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

class Coaching_controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // Your own constructor code

        $this->load->model('business_model');
        $this->load->model('programs_model');
        $this->load->model('coaching_model');
        $this->load->model('service_model');
        $this->load->model('customer_model');
        $this->load->model('staff_model');
        $this->load->model('visits_model');
        $this->load->model('accounting_model');
        $this->load->model('scheduler_model');
        $this->load->model('attendance_model');

        if ($this->session->userdata('role') === 'Reception' || $this->session->userdata('role') === 'Program Admin' || $this->session->userdata('role') === 'Program Reception' || $this->session->userdata('role') === 'Admin' || $this->session->userdata('role') === 'Super User' || $this->session->userdata('role') === 'Accountant'|| $this->session->userdata('role') === 'Staff Schedule' || $this->session->userdata('role') === 'Trainer') {


        } else {
            redirect('logout');
        }
    }

    public function coachingsearch() {
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            //storemanager,hr,reception...user serial
            //checkroles(0, 0, 0);
            $this->load->helper('url');
            $uri = $this->uri->uri_string();
            $data['current_uri'] = $uri;
            $subnav ='' ;
            if($data['current_uri'] == "coachingsearch/individual"){
                $subnav = 'CoachingRegister';
            }else{
                $subnav  = 'CoachingRegisterGroup';
            }
            $data['nav'] = 'Programs';
            $data['subnav'] = $subnav;

            $data['scheduler_style'] = $this->business_model->getbusinessdetails();

            $data['program_type'] = 'coachingregister';
            $data['program'] = 'Coaching';


            $this->load->view('includes/header', $data);
            $this->load->view('coaching/select_customer_view');
            $this->load->view('includes/footer');
        }
    }
    public function coachingregister($customer_id ,$flag_for_individual_or_group) {

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

            if($customer_id > 0){
                $data['customer'] = $this->customer_model->get_byid($customer_id);
            }
            //storemanager,hr,reception...user serial
            //checkroles(0, 0, 0);
            $data['nav'] = 'Programs';
            $sub_nav = '';
            if($flag_for_individual_or_group == "group_client"){
                $sub_nav  = 'CoachingRegisterGroup';
            }else{
                $sub_nav = 'CoachingRegister';
            }
            $data['subnav'] =   $sub_nav;
            $data['scheduler_style'] = $this->business_model->getbusinessdetails();

            //echo $this->session->userdata('training'); exit();

            if($this->session->userdata('gym')=='Yes' ){
                $this->db->select('*');
                $this->db->where('program_type', 'Gym');
                $query = $this->db->get('program_types');

                $program_types=$query->result_array();

                $data['program_id'] = $program_types[0]['id_program_types'];
                $data['registration_fee'] = $program_types[0]['registration_fee'];
                $data['program_type']='Gym';
            } else {
                $this->db->select('*');
                $this->db->where('program_type', 'Coaching');
                $query = $this->db->get('program_types');
                $program_types=$query->result_array();

                $data['program_id'] = $program_types[0]['id_program_types'];
                $data['registration_fee'] = $program_types[0]['registration_fee'];
                $data['program_type']='Programs';
            }

            $data['services'] = $this->service_model->get_program_services($data['program_type']);
            $data['flag_for_individual_or_group'] =  $flag_for_individual_or_group;
            $this->load->view('includes/header', $data);
            $this->load->view('coaching/coaching_register_view');
            $this->load->view('includes/footer');
        }

    }

    public function enroll_customer(){   
        $program_id  = $this->input->post('program_id');
        $program_type  = $this->input->post('program_type');
        $customerid =$this->input->post('txtcustomerid');
        $tableData = stripcslashes($this->input->post('TableData'));
        $tableData = json_decode($tableData,TRUE);
        if($customerid > 0){
            foreach( $tableData as $row) {
                if($row['program_group_id'] > 0){
                    $sql = "SELECT program_enrollment.customer_id , program_enrollment.id_program_enrollment  FROM `program_group_members` 
                        INNER join program_enrollment on  program_enrollment.id_program_enrollment =`program_group_members`.`program_enrollment_id` 
                        where   program_enrollment.customer_id =? and  `program_group_members`.`program_group_id`=?";
                    $resp = $this->db->query($sql, array($customerid,$row['program_group_id']));
                    $group_member_exist_or_not  = $resp->row();
                    if($group_member_exist_or_not){
                        //  echo "One of the groups you have selected already has a student in it.";  
                        print_r('Warning_of_validation,'.$group_member_exist_or_not->id_program_enrollment);
                        exit;
                    }
                }
            }
        } 
        // print_r($customerid); exit();
        $customername= $this->input->post('txtcustomername');
        $customercell=$this->input->post('txtcustomercell');
        $customerphone1=$this->input->post('txtcustomerphone1');
        $customerphone2=$this->input->post('txtcustomerphone2');
        $customergender=$this->input->post('txtcustomergender');
        $customertype=$this->input->post('txtcustomertype');
        $customerfathername=$this->input->post('txtcustomerfathername');
        $customerfathercell=$this->input->post('txtcustomerfathercell');
        $customerfatherprofession=$this->input->post('txtcustomerfatherprofession');
        $customermothername=$this->input->post('txtcustomermohtername');
        $customermothercell=$this->input->post('txtcustomermothercell');
        $customermotherprofession=$this->input->post('txtcustomermotherprofession');
        $customercard=$this->input->post('txtcustomercard');
        $customeremail=$this->input->post('txtcustomeremail');
        $customeraddress=$this->input->post('txtcustomeraddress');
        $customerbirthday=$this->input->post('txtcustomerbirthday');
        $customerbirthmonth=$this->input->post('txtcustomerbirthmonth');
        $customerallergies=$this->input->post('txtcustomerallergies');
        $customeralert=$this->input->post('txtcustomeralert');
        $emergencyperson=$this->input->post('txtemergencyperson');
        $emergencynumber=$this->input->post('txtemergencynumber');
        $age=$this->input->post('txtage');
        $education=$this->input->post('txteducation');
        $beautyeducation=$this->input->post('txtbeautyeducation');
        $languagesArray=$this->input->post('txtlanguages');
        $languages='';
        if(is_array($languagesArray)){
            foreach ($languagesArray as $language){
                $languages = $language.', '.$languages;
            }
        }
        $languages =$languages;
        $beautyexperience=$this->input->post('txtexperience');
        $goals=$this->input->post('txtgoals');

        $programid=$this->input->post('txtprograms');
        $programsessionid=$this->input->post('txtprogramsessions');
        $startdate=$this->input->post('txtstartdate');
        $validity = $this->input->post('txtRegistrationValidity');

        (null != $this->input->post('txtweight')) ? $txtweight=$this->input->post('txtweight') :  $txtweight = 0;
        (null != $this->input->post('txtweight')) ? $txtweight=$this->input->post('txtweight') :  $txtweight = 0;
        (null != $this->input->post('txtarms')) ? $txtarms=$this->input->post('txtarms') :  $txtarms = 0;
        (null != $this->input->post('txtthighs')) ? $txtthighs=$this->input->post('txtthighs') :  $txtthighs = 0;
        (null != $this->input->post('txthips')) ? $txthips=$this->input->post('txthips') :  $txthips = 0;
        (null != $this->input->post('txtchest')) ? $txtchest=$this->input->post('txtchest') :  $txtchest = 0;
        (null != $this->input->post('txtwaist')) ? $txtwaist=$this->input->post('txtwaist') :  $txtwaist = 0;
        (null != $this->input->post('txtbmi')) ? $txtbmi=$this->input->post('txtbmi') :  $txtbmi = 0;
        (null != $this->input->post('txtheight')) ? $txtheight=$this->input->post('txtheight') : $txtheight = 0;

        (null != $this->input->post('txtRegistrationFee')) ? $txtregistrationfee=$this->input->post('txtRegistrationFee') : 0;

        //////Work with customer first///////////
        $data = array(
            'customer_name' => $customername,
            'customer_email' => $customeremail,
            'customer_cell' => $customercell,
            'customer_address' => $customeraddress,
            'customer_phone1' => $customerphone1,
            'customer_phone2' => $customerphone2,
            'customer_birthday' => $customerbirthday,
            'customer_birthmonth' => $customerbirthmonth,
            'customer_allergies' => $customerallergies,
            'customer_alert' => $customeralert,
            'customer_type' => $customertype,
            'father_name' => $customerfathername,
            'father_cell' => $customerfathercell,
            'father_profession' => $customerfatherprofession,
            'mother_name' => $customermothername,
            'father_cell' => $customermothercell,
            'father_profession' => $customermotherprofession,
            'customer_gender' => $customergender,
            'customer_card' => $customercard,
            'emergency_contact_person' => $emergencyperson,
            'emergency_contact_number' => $emergencynumber,
            'business_id' => $this->session->userdata('businessid'),
            'age' => $age,
            'height' => $txtheight,
            'bmi' => $txtbmi
        );
        if($customerid>1){ //Update the existing custome
            $this->db->where('id_customers', $customerid);
            $this->db->update('customers', $data);
        }else{ //Insert new customer & get new customer id
            $this->db->insert('customers', $data);
            $customerid = $this->db->insert_id();
        }

        //////////Now Enroll Customer in Program////////////////

        if ($customerid <= 0){
            // Set flash data 
            print_r('error');
            exit();
        } else {
            $data = array(
                'program_type_id' => $program_id,
                'customer_id' => $customerid,
                'education' => $education,
                'beautyexperience' => $beautyexperience,
                'languages' => $languages,
                'goals' => $goals,
                'start_date' => date('Y-m-d'),
                'valid_until' => $validity,
                'created_by' => $this->session->userdata('username'),
                'business_id' => $this->session->userdata('businessid'),
                'current_weight' => $txtweight,
                'current_arms' => $txtarms,
                'current_thighs' => $txtthighs,
                'current_hips' => $txthips,
                'current_chest' => $txtchest,
                'current_waist' => $txtwaist
            );
            $this->db->insert('program_enrollment', $data);
            $enrollmentid = $this->db->insert_id();


            $tax= $this->business_model->get_tax_perc('service');
            $taxperc=$tax->tax_percentage;
            //Registration Fee - Create Invoice
            if($txtregistrationfee > 0){
                // if($this->input->post('txtcustomerid') <=0){ 
                $data = array(
                    "program_enrollment_id" => $enrollmentid,
                    "program_enrolled_service_id" => 0,
                    "number_of_sessions" => 0,
                    "invoice_number" => 'Reg-'.$enrollmentid.'-'.date('Y'),
                    "invoice_date" => date('Y-m-d H:i:s'),
                    "program_invoice_status" => "Active",
                    "payment_mode" => "Receivable",
                    "program_invoice_remarks" => 'Registration Fee '.date('Y-m-d').' - '. $validity.' '.$customername,
                    "business_id" => $this->session->userdata("businessid"),
                    "invoiced_amount" => $txtregistrationfee,
                    "invoice_balance"  => $taxperc > 0 ? $txtregistrationfee + round($txtregistrationfee*$taxperc/100,2) : $txtregistrationfee,
                    "salestax" => $taxperc > 0 ? round($txtregistrationfee*$taxperc/100,2): 0,
                    "invoice_discount" => 0,
                    "created_by" => $this->session->userdata("username"),
                    "invoice_remarks" => 'Enrolled Charge'

                );

                $this->db->insert('program_invoices', $data);
                $invoice_id = $this->db->insert_id();
                ////Add receivable account vouchers                    
                $this->create_receivable_voucher($invoice_id, $txtregistrationfee);
                // }

            }
            ///End Registration Fee
            // Unescape the string values in the JSON array
            // Decode the JSON array
            // now $tableData can be accessed like a PHP array
            foreach($tableData as $row){
                ///Add each service in the Program
                $data = array(
                    'program_enrollment_id' => $enrollmentid,
                    'service_id' => $row['service_id'],
                    'service_name' => $row['service_name'],
                    'service_category' => $program_type,
                    'per_session_rate' => $row['service_rate'],
                    'per_session_rate' => $row['service_rate'],
                    'total_sessions' => $row['total_sessions']
                );
                $this->db->insert('program_enrolled_services', $data);
                $sessionserviceid = $this->db->insert_id();
                ///if service invoicing is set then create service invoice as well
                if(COACHING_MODE == 'service'){
                    $invoiced_amount = ($row['service_rate']*$row['total_sessions'])-$row['program_discount']; 
                    if($row['other_charges'] > 0){
                        $invoiced_amount = ($row['service_rate']*$row['total_sessions'])+$row['other_charges'];
                    }

                    $data = array(
                        "program_enrollment_id" => $enrollmentid,
                        "program_enrolled_service_id" => $sessionserviceid,
                        "number_of_sessions" => $row['total_sessions'],
                        "invoice_number" => 'Inv-'.$enrollmentid.'-'.$row['service_id'].'-'.date('Y'),
                        "invoice_date" => date('Y-m-d H:i:s'),
                        "program_invoice_status" => "Active",
                        "payment_mode" => "Receivable",
                        "business_id" => $this->session->userdata("businessid"),
                        "invoiced_amount" => $invoiced_amount,
                        "invoice_balance" => $taxperc > 0 ? $invoiced_amount + round($invoiced_amount*$taxperc/100,2) : $invoiced_amount,
                        "salestax" => $taxperc > 0 ? round($invoiced_amount*$taxperc/100,2): 0,
                        "invoice_discount" => $row['program_discount'],
                        "invoice_other_charges" => $row['other_charges'],
                        "created_by" => $this->session->userdata("username"),
                        "program_invoice_remarks" => $row['service_name'].' Fee '.$customername,
                        "invoice_remarks" => 'Enrolled Charge'
                    );
                    $this->db->insert('program_invoices', $data);
                    $invoice_id=$this->db->insert_id();
                    ////Add receivable account vouchers                    
                    $this->create_receivable_voucher($invoice_id, $invoiced_amount);
                }

            // =========> Add group member Start from here <========================   
                    if ($row['program_group_id'] > 0) {
                        $program_group_data = array(
                            'program_enrollment_id' => $enrollmentid,
                            'program_group_id' => $row['program_group_id'],
                            'added_by' => $this->session->userdata("username"),
                            'added_on' => date('Y-m-d H:i:s'),
                            'member_status' => 'Active'
                        );
                        $this->db->insert('program_group_members', $program_group_data);
                        $group_member_id = $this->db->insert_id();

                        // Fetch customer_id from customer_visits
                        $sql = "SELECT `customer_visits`.`customer_id` FROM `customer_visits` WHERE group_id = ? GROUP BY group_id";
                        $resp = $this->db->query($sql, array($row['program_group_id']));
                        $customer_visit_data = $resp->row();

                        if ($customer_visit_data) {
                            $customer_id_for_customer_visit = $customer_visit_data->customer_id;

                            // Fetch customer visit data
                            $sql = "SELECT `customer_visits`.`business_id`, `customer_visits`.`customer_id`, `customer_visits`.`customer_visit_date`, 
                                            `customer_visits`.`visit_status`, `customer_visits`.`visit_color_type`, `customer_visits`.`group_id`, 
                                            `customer_visits`.`group_visit_id`, `customer_visits`.`created_on`, `customer_visits`.`program_enrolled_service_id`
                                    FROM `customer_visits` WHERE group_id = ? AND customer_id = ?";
                            $resp = $this->db->query($sql, array($row['program_group_id'], $customer_id_for_customer_visit));
                            $customer_visit_data_for_insert_customer_visit = $resp->result();

                            foreach ($customer_visit_data_for_insert_customer_visit as $data) {
                                // Insert new customer visit
                                $data_customer_visit = array(
                                    'business_id' => $data->business_id,
                                    'customer_id' => $customerid,
                                    'customer_visit_date' => $data->customer_visit_date,
                                    'visit_status' => 'open',
                                    'visit_color_type' => 'Dark',
                                    'visit_color' => 'Dark',
                                    'group_id' => $row['program_group_id'],
                                    'group_visit_id' => $data->group_visit_id,
                                    'created_by' => $this->session->userdata('username'),
                                    'program_enrolled_service_id' => $sessionserviceid,
                                );
                                $this->db->insert('customer_visits', $data_customer_visit);
                                $visit_id = $this->db->insert_id();

                                // Fetch service details
                                $sql = "SELECT `program_groups`.`program_service_id`, `program_groups`.`program_service_name` FROM `program_groups` WHERE id_program_groups = ?";
                                $resp = $this->db->query($sql, array($row['program_group_id']));
                                $group_data_service_id = $resp->row();

                                if ($group_data_service_id) {
                                    $this->db->select('id_business_services, id_service_category, id_service_types, service_name, service_category, service_type, service_rate');
                                    $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('id_business_services', $group_data_service_id->program_service_id);
                                    $query = $this->db->get('business_services');
                                    $service_data = $query->row();

                                    if ($service_data) {
                                        // Fetch group visit data
                                        $sql = "SELECT `group_visits`.`visit_service_start`, `group_visits`.`visit_service_end`, `group_visits`.`staff_id` FROM `group_visits` WHERE id_group_visits = ?";
                                        $resp = $this->db->query($sql, array($data->group_visit_id));
                                        $group_visit_data = $resp->row();

                                        if ($group_visit_data) {
                                            // Insert visit service
                                            $data = array(
                                                'business_id' => $this->session->userdata('businessid'),
                                                'customer_visit_id' => $visit_id,
                                                'service_id' => $service_data->id_business_services,
                                                'service_name' => $service_data->service_name,
                                                'visit_service_start' => $group_visit_data->visit_service_start,
                                                'visit_service_end' => $group_visit_data->visit_service_end,
                                                'update_date' => date('Y-m-d H:i:s'),
                                                'service_flag' => 'servicetype',
                                                'id_service_category' => $service_data->id_service_category
                                            );
                                            $this->db->insert('visit_services', $data);
                                            $visit_service_id = $this->db->insert_id();

                                            // Fetch staff details
                                            $this->db->select('id_staff, staff_fullname');
                                            $this->db->where('id_staff', $group_visit_data->staff_id);
                                            $query = $this->db->get('staff');
                                            $staff_data = $query->row();

                                            if ($staff_data) {
                                                // Insert visit staff
                                                $data = array(
                                                    'business_id' => $this->session->userdata('businessid'),
                                                    'customer_visit_id' => $visit_id,
                                                    'visit_service_id' => $visit_service_id,
                                                    'staff_id' => $staff_data->id_staff,
                                                    'staff_name' => $staff_data->staff_fullname
                                                );
                                                $this->db->insert('visit_service_staffs', $data);
                                                $visit_staff_id = $this->db->insert_id();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // =========> Add group member end here <========================   
            }
        }
        print_r('Success,'.$enrollmentid);
    }
    public function add_service_to_enrollment(){ 
       
        $customer_name= $this->input->post('customer_name');
        $customer_id = $this->input->post('customer_id'); 

        if($customer_id > 0){

               if($this->input->post('program_group_id') > 0){
                    $sql = "SELECT program_enrollment.customer_id , program_enrollment.id_program_enrollment  FROM `program_group_members` 
                        INNER join program_enrollment on  program_enrollment.id_program_enrollment =`program_group_members`.`program_enrollment_id` 
                        where   program_enrollment.customer_id =? and  `program_group_members`.`program_group_id`=?";
                    $resp = $this->db->query($sql, array($customer_id,$this->input->post('program_group_id') ));
                    $group_member_exist_or_not  = $resp->row();
                    if($group_member_exist_or_not){
                        //  echo "One of the groups you have selected already has a student in it.";  
                        echo 'Warning_of_validation,' . $group_member_exist_or_not->id_program_enrollment;
                        exit;

                    }
                 }
            
        }

        $data = array(
            'program_enrollment_id' => $this->input->post('enrollment_id'),
            'service_id' => $this->input->post('service_id'),
            'service_name' => $this->input->post('service_name'),
            'service_category' => $this->input->post('program_type'),
            'per_session_rate' => $this->input->post('per_session_rate'),
            'total_sessions' => $this->input->post('total_sessions')
        );
        $this->db->insert('program_enrolled_services', $data);
        $sessionserviceid = $this->db->insert_id();
        if($this->input->post('program_group_id') > 0){
            $program_group_data = array(
                'program_enrollment_id' =>  $this->input->post('enrollment_id'),
                'program_group_id' =>$this->input->post('program_group_id'),
                'added_by' => $this->session->userdata("username"),
                'added_on' => date('Y-m-d H:i:s'),
                'member_status' => 'Active'
            );
            $this->db->insert('program_group_members', $program_group_data);
            $group_member_id = $this->db->insert_id();

            $sql = "SELECT `customer_visits`.`customer_id` FROM `customer_visits` WHERE group_id = ? GROUP BY group_id";
            $resp = $this->db->query($sql, array($this->input->post('program_group_id')));
            $customer_visit_data = $resp->row();

            if ($customer_visit_data) {
                $customer_id_for_customer_visit = $customer_visit_data->customer_id;
                $sql = "SELECT `customer_visits`.`business_id`, `customer_visits`.`customer_id`, `customer_visits`.`customer_visit_date`, `customer_visits`.`visit_status`,
                                        `customer_visits`.`visit_color_type`, `customer_visits`.`group_id`, `customer_visits`.`group_visit_id`, `customer_visits`.`created_on`, `customer_visits`.`program_enrolled_service_id`
                                        FROM `customer_visits` WHERE group_id = ? AND customer_id = ?";
                $resp = $this->db->query($sql, array($this->input->post('program_group_id'), $customer_id_for_customer_visit));
                $customer_visit_data_for_insert_customer_visit = $resp->result();

                foreach ($customer_visit_data_for_insert_customer_visit as $data) {
                    $data_customer_visit = array(
                        'business_id' => $data->business_id,
                        'customer_id' => $customer_id,
                        'customer_visit_date' => $data->customer_visit_date,
                        'visit_status' => 'open',
                        'visit_color_type' => 'Dark',
                        'visit_color' => 'Dark',
                        'group_id' => $this->input->post('program_group_id'),
                        'group_visit_id' => $data->group_visit_id,
                        'created_by' => $this->session->userdata('username'),
                        'program_enrolled_service_id' => $sessionserviceid,
                    );
                    $this->db->insert('customer_visits', $data_customer_visit);
                    $visit_id = $this->db->insert_id();

                    $sql = "SELECT `program_groups`.`program_service_id`, `program_groups`.`program_service_name` FROM `program_groups` WHERE id_program_groups = ?";
                    $resp = $this->db->query($sql, array($this->input->post('program_group_id')));
                    $group_data_service_id = $resp->row();

                    // Insert visit service
                    $this->db->select('id_business_services, id_service_category, id_service_types, service_name, service_category, service_type, service_rate');
                    $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('id_business_services', $group_data_service_id->program_service_id);
                    $query = $this->db->get('business_services');
                    $service_data = $query->row();

                    $sql = "SELECT `group_visits`.`visit_service_start`, `group_visits`.`visit_service_end`, `group_visits`.`staff_id` FROM `group_visits` WHERE id_group_visits = ?";
                    $resp = $this->db->query($sql, array($data->group_visit_id));
                    $group_visit_data = $resp->row();

                    $data = array(
                        'business_id' => $this->session->userdata('businessid'),
                        'customer_visit_id' => $visit_id,
                        'service_id' => $service_data->id_business_services,
                        'service_name' => $service_data->service_name,
                        'visit_service_start' =>$group_visit_data->visit_service_start,
                        'visit_service_end' =>$group_visit_data->visit_service_end,
                        'update_date' => date('Y-m-d H:i:s'),
                        'service_flag' => 'servicetype',
                        'id_service_category' => $service_data->id_service_category
                    );
                    $this->db->insert('visit_services', $data);
                    $visit_service_id = $this->db->insert_id();

                    // Insert visit staff
                    $this->db->select('id_staff, staff_fullname');
                    $this->db->where('id_staff', $group_visit_data->staff_id);
                    $query = $this->db->get('staff');
                    $staff_data = $query->row();

                    $data = array(
                        'business_id' => $this->session->userdata('businessid'),
                        'customer_visit_id' => $visit_id,
                        'visit_service_id' => $visit_service_id,
                        'staff_id' => $staff_data->id_staff,
                        'staff_name' => $staff_data->staff_fullname
                    );
                    $this->db->insert('visit_service_staffs', $data);
                    $visit_staff_id = $this->db->insert_id();
                }
            }


        }

        ///if service invoicing is set then create service invoice as well
        if(COACHING_MODE == 'service'){
            $tax= $this->business_model->get_tax_perc('service');
            $taxperc=$tax->tax_percentage;
            $invoiced_amount = ($this->input->post('per_session_rate')*$this->input->post('total_sessions'))-$this->input->post('program_discount'); 
             if($this->input->post('other_charges')){ 
              $invoiced_amount = ($this->input->post('per_session_rate')*$this->input->post('total_sessions'))+$this->input->post('other_charges'); 
             }
            $data = array(
                "program_enrollment_id" => $this->input->post('enrollment_id'),
                "program_enrolled_service_id" => $sessionserviceid,
                "number_of_sessions" => $this->input->post('total_sessions'),
                "invoice_number" => 'Inv-'.$this->input->post('enrollment_id').'-'.$this->input->post('service_id').'-'.date('Y'),
                "invoice_date" => date('Y-m-d H:i:s'),
                "program_invoice_status" => "Active",
                "payment_mode" => "Receivable",
                "business_id" => $this->session->userdata("businessid"),
                "invoiced_amount" => $invoiced_amount,
                "invoice_balance" => $taxperc > 0 ? $invoiced_amount + round($invoiced_amount*$taxperc/100,2) : $invoiced_amount,
                "salestax" => $taxperc > 0 ? round($invoiced_amount*$taxperc/100,2): 0,
                "invoice_discount" => $this->input->post('program_discount'),
                "invoice_other_charges" => $this->input->post('other_charges'),
                "created_by" => $this->session->userdata("username"),
                "program_invoice_remarks" => $this->input->post('service_name').' Fee '.$customer_name,
                "invoice_remarks" => 'Enrolled Charge'
            );

            $this->db->insert('program_invoices', $data);
            $invoice_id=$this->db->insert_id();
            ////Add receivable account vouchers                    
            $this->create_receivable_voucher($invoice_id, $invoiced_amount);
        }
         echo $sessionserviceid; 
        // print_r('Warning_of_validation,'.$sessionserviceid);
    }

    public function update_service_enrollment_sessions(){
        $this->db->where('program_enrollment_id', $this->input->post('enrollment_id'));
        $this->db->where('service_id', $this->input->post('service_id'));

        $this->db->set('total_sessions',  $this->input->post('total_sessions'));
        $this->db->set('per_session_rate',  $this->input->post('session_rate'));
        $this->db->update('program_enrolled_services');
        ////create receivable voucher  

        echo $this->db->affected_rows();
    }

    public function remove_service_from_enrollment(){
        $this->db->where('program_enrollment_id', $this->input->post('enrollment_id'));
        $this->db->where('service_id', $this->input->post('service_id'));

        $this->db->set('service_status', 'InAvtive');
        $this->db->set('cancelled_by', $this->session->userdata('username'));
        $this->db->set('cancelled_on', date('Y-m-d H:m:s'));
        $this->db->set('service_status', 'InActive');
        $this->db->update('program_enrolled_services');
        //  cencelling Invoices  
        $this->db->where('program_enrolled_service_id',  $this->input->post('program_enrolled_services_id'));
        $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:m:s'));
        $this->db->update('program_invoices');


        // cancelling vouchers 
        $this->db->where('program_enrolled_service_id',  $this->input->post('program_enrolled_services_id'));
        $this->db->set('voucher_status', 'Cancelled');
        $this->db->set('cancelled_by', $this->session->userdata('username'));
        $this->db->set('cancelled_on', date('Y-m-d H:m:s'));
        $this->db->update('account_vouchers');

        echo $this->db->affected_rows();
    }


    public function coachingregisteredit($enrollment_id) {

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

            $data['nav'] = 'Reception';
            $data['subnav'] = 'CoachingRegister';

            $data['scheduler_style'] = $this->business_model->getbusinessdetails();

            // $data['program_id']=5;
            // $data['services'] = $this->service_model->get_program_services(); 

            if($this->session->userdata('gym')=='Yes' ){
                $this->db->select('*');
                $this->db->where('program_type', 'Gym');
                $query = $this->db->get('program_types');

                $program_types=$query->result_array();

                $data['program_id'] = $program_types[0]['id_program_types'];
                $data['registration_fee'] = $program_types[0]['registration_fee'];
                $data['program_type']='Gym';
            } else {
                $this->db->select('*');
                $this->db->where('program_type', 'Coaching');
                $query = $this->db->get('program_types');
                $program_types=$query->result_array();

                $data['program_id'] = $program_types[0]['id_program_types'];
                $data['registration_fee'] = $program_types[0]['registration_fee'];
                $data['program_type']='Programs';
            }


            $sql = "SELECT * FROM `program_group_members` where program_enrollment_id=? and cancelled_on is null";
            $resp = $this->db->query($sql, array($enrollment_id));
            $data_of_query = $resp->row();

            if($data_of_query){
                $data['flag_for_individual_or_group']  = "group" ;
            }else{
                $data['flag_for_individual_or_group']  ="individual_client";
            }
            $data['services'] = $this->service_model->get_program_services($data['program_type']);
            $data['program_enrollment'] = $this->coaching_model->get_enrollment($enrollment_id);
            $data['enrolled_services'] = $this->coaching_model->get_enrolled_services($enrollment_id);

            $this->load->view('includes/header', $data);
            $this->load->view('coaching/coaching_register_edit');
            $this->load->view('includes/footer');
        }

    }


    public function edit_enrollment(){

        $enrollmentid = $this->input->post('txtprogramenrollmentid');

        $customerid = $this->input->post('txtcustomerid');
        //print_r($customerid); exit();
        $customername= $this->input->post('txtcustomername');
        $customercell=$this->input->post('txtcustomercell');
        $customerphone1=$this->input->post('txtcustomerphone1');
        $customerphone2=$this->input->post('txtcustomerphone2');
        $customergender=$this->input->post('txtcustomergender');
        $customertype=$this->input->post('txtcustomertype');
        $customercard=$this->input->post('txtcustomercard');
        $customerprofession=$this->input->post('txtcustomerprofession');
        $customeremail=$this->input->post('txtcustomeremail');
        $customeraddress=$this->input->post('txtcustomeraddress');
        $customeranniversay=$this->input->post('txtcustomeranniversary');
        $customerbirthday=$this->input->post('txtcustomerbirthday');
        $customerbirthmonth=$this->input->post('txtcustomerbirthmonth');
        $customerallergies=$this->input->post('txtcustomerallergies');
        $customeralert=$this->input->post('txtcustomeralert');
        $emergencyperson=$this->input->post('txtemergencyperson');
        $emergencynumber=$this->input->post('txtemergencynumber');
        $age=$this->input->post('txtage');
        $goals=$this->input->post('txtgoals');


        $education=$this->input->post('txteducation');
        $beautyeducation=$this->input->post('txtbeautyeducation');
//        $languagesArray=$this->input->post('txtlanguages');
//        $languages='';
//        if(is_array($languagesArray)){
//            foreach ($languagesArray as $language){
//                $languages = $language.', '.$languages;
//            }
//        }
//        
//        
//        $languages =$languages;
        $beautyexperience=$this->input->post('txtexperience');


//        $programid=$this->input->post('txtprograms');
//        $programsessionid=$this->input->post('txtprogramsessions');
//        $startdate=$this->input->post('txtstartdate');



        //////Work with customer first///////////
        $data = array(
            'customer_name' => $customername,
            'customer_email' => $customeremail,
            'customer_cell' => $customercell,
            'customer_address' => $customeraddress,
            'customer_phone1' => $customerphone1,
            'customer_phone2' => $customerphone2,
            'customer_birthday' => $customerbirthday,
            'customer_birthmonth' => $customerbirthmonth,
            'customer_anniversary' => $customeranniversay,
            'customer_allergies' => $customerallergies,
            'customer_alert' => $customeralert,
            'customer_type' => $customertype,
            'profession' => $customerprofession,
            'customer_gender' => $customergender,
            'customer_card' => $customercard,
            'emergency_contact_person' => $emergencyperson,
            'emergency_contact_number' => $emergencynumber,
            'age' => $age
        );


        $this->db->where('id_customers', $customerid);
        $this->db->update('customers', $data);




        //////////Now Update Enrollment of Customer in Program////////////////


        $data1 = array(
            //'program_session_id' => $programsessionid,
            //'start_date' => $startdate,
            //'customer_id' => $customerid,
            'education' => $education,
            'beautyeducation' => $beautyeducation,
            'beautyexperience' => $beautyexperience,
            // 'languages' => $languages,
            'goals' => $goals,
            //'agreeddiscount' => $agreeddiscount      

        );

        $this->db->where('id_program_enrollment', $enrollmentid);
        $this->db->update('program_enrollment', $data1);

        // echo $this->db->affected_rows(); exit();

        redirect('coaching_register_edit/'.$enrollmentid);
    }

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

            $data['nav'] = 'Programs';
            $data['subnav'] = 'CoachingProspectMembers';

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


            $data['coaching_service'] = $this->input->post('coaching_service');
            $data['coaching_services'] = $this->service_model->get_program_services();

            $service_id=0;
            if($this->input->post('coaching_service')!= null && $this->input->post('coaching_service')!= 'All'){
                $service_id = $this->input->post('coaching_service');
            }
            if(null != $this->input->post('filter_veiw')){
                $data['status'] = $this->input->post('filter_veiw');
            }else{
                $data['status'] = 'Active';
            } 
            $data['program_members'] = $this->coaching_model->getting_coaching_members_for_pos($service_id, $data['status']);
            $customers_ids=[];
            foreach($data['program_members'] as $program_members){
                $customers_ids[] = $program_members['customer_id'];
            }
            $this->load->model('staff_model');
            $data['staff_list']=$this->staff_model->get_active_staff();
            $data['prospect_students'] = $this->coaching_model->get_prospect_students($customers_ids);

            $this->load->view('includes/header', $data);
            $this->load->view('coaching/coaching_prospect_student_view');
            $this->load->view('includes/footer');
        }
    }


    public function coaching_group_attendance_report(){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $program_group_id =0; 
            $member_id ="All";
            if (null !== $this->input->post('id_program_group')){
                $program_group_id =  $this->input->post('id_program_group');
            } 
            if (null !== $this->input->post('member_id')){
                $member_id =  $this->input->post('member_id');
            } 
            $staff_id=0; 
            $this->db->select('id_staff');
            $this->db->where('id_users', $this->session->userdata('userid'));
            $this->db->join('staff', 'staff_cell = user_mobile');
            $query = $this->db->get('users');
            $staff=$query->row(); 
             if($staff){
                $staff_id = $staff->id_staff;
             }
            if (null !== $this->input->post('staff_id')){
                $staff_id =  $this->input->post('staff_id');
            } 
            $today = date('Y-m-d', strtotime("-3 months"));
            $enddate = date('Y-m-d');
            if(null != $this->input->post('mDate') && $this->input->post('mDate')!=''){
                $today = $this->input->post('mDate');
                $enddate = $this->input->post('eDate');
            }
            $data['nav'] = 'Programs';
            $data['subnav'] = 'CoachingGroupAttendanceReport';
            $data['business'] = $this->business_model->getbusinessdetails();
            $data['program_groups'] = $this->coaching_model->get_program_groups();
            $data['program_group_attendance_report'] = $this->coaching_model->get_program_groups_attendance_reports_without_staff($program_group_id,$today,$enddate ,$member_id); 


            $data['program_group_id'] =  $program_group_id; 
            $data['program_staff_id'] =  $staff_id; 

            $data['staff'] = $this->staff_model->get_active_scheduler_staff($this->session->userdata('businessid') ); 
            // $data['group']=$this->coaching_model->get_group($program_group_id);
            $data['today']=$today; 
            $data['enddate']=$enddate; 
            $data['member_id']=$member_id; 
            // print_r($data['enddate']);
            $this->load->view('includes/header', $data);
            $this->load->view('coaching/program_group_attendance_report_view');
            $this->load->view('includes/footer');
        }

    }  

    public function monthly_student_attendance_report(){ 
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $program_group_id =0;
            if (null !== $this->input->post('id_program_group')){
                $program_group_id =  $this->input->post('id_program_group');
            }  
            $attendance_data=[];
            $selected_month =0;
            $selected_year =0;
            $select_customer_id =0; 

            $customer_data =[];
            if($this->input->post('enroll_member') !== null &&  $this->input->post('month') !== null &&   $this->input->post('year') !== null ){ 

                $selected_month  = $month = $this->input->post('month');
                $selected_year =  $year = $this->input->post('year');
                $select_customer_id = $select_customer_id = $this->input->post('enroll_member');
                $first_date_of_month = new DateTime("$year-$month-01");
                $last_date_of_month = new DateTime("$year-$month-01");
                $last_date_of_month->modify('last day of this month');
                $first_date = $first_date_of_month->format('Y-m-d');
                $last_date = $last_date_of_month->format('Y-m-d');  

                $sql = "SELECT * FROM `customers` where id_customers =?";
                $resp = $this->db->query($sql, array($select_customer_id));
                $customer_data = $customer_data = $resp->row();  
                $data['customer_data'] = $customer_data;  
                $sql = "WITH RECURSIVE dates AS (
                        SELECT DATE ? AS date
                        UNION ALL
                        SELECT date + INTERVAL 1 DAY
                        FROM dates
                        WHERE date + INTERVAL 1 DAY <= LAST_DAY(DATE ?)
                    )
                    SELECT 
                        c.customer_name, 
                        d.date, 
                        DAYNAME(d.date) as day,
                        visit_services.visit_service_start ,
                        visit_services.visit_service_end ,
                        CASE WHEN a.inservice = 'Yes' THEN 'present' ELSE 0 END AS present_count,
                        CASE WHEN a.inservice = 'No' THEN 'absent' ELSE 0 END AS absent_count
                    FROM customers c
                    CROSS JOIN dates d
                    LEFT JOIN customer_visits a
                    ON date(d.date) = date(a.customer_visit_date)
                    AND a.customer_id = c.id_customers 
                    LEFT JOIN visit_services on  visit_services.customer_visit_id =a.id_customer_visits
                    WHERE c.id_customers =? 
                    ORDER BY d.date  ASC";
                $resp = $this->db->query($sql, array($first_date , $last_date,$select_customer_id));
               $attendance_data = $resp->result();
               $data['month_attendance_data'] = $attendance_data; 
            }else{ 
                $month =  date("m", strtotime("first day of previous month"));
                $year =   date('Y');
                $select_customer_id = 0;
                $data['month_attendance_data'] = $attendance_data; 
            }

            $staff_id=0; 
            $this->db->select('id_staff');
            $this->db->where('id_users', $this->session->userdata('userid'));
            $this->db->join('staff', 'staff_cell = user_mobile');
            $query = $this->db->get('users');
            $staff=$query->row(); 
             if($staff){
                $staff_id = $staff->id_staff;
             }
            if (null !== $this->input->post('staff_id')){
                $staff_id =  $this->input->post('staff_id');
            } 
            $today = date('Y-m-d');
            if(null != $this->input->post('mDate') && $this->input->post('mDate')!=''){
                $today = $this->input->post('mDate') ;
            } 
            $data['nav'] = 'Programs';
            $data['subnav'] = 'CoachingMonthlyAttendanceReport';
            $data['business'] = $this->business_model->getbusinessdetails();
            $data['program_groups'] = $this->coaching_model->get_program_groups();

            $data['enroll_customers']=$this->coaching_model->getting_enroll_customer();

            $data['today']=$today; 
            $data['month'] = $month;
            $data['year'] = $year;   

            $data['select_customer_id']=$select_customer_id; 
            $data['selected_month'] = $selected_month;
            $data['selected_year'] = $selected_year;  
 

            $this->load->view('includes/header', $data);
            $this->load->view('coaching/student_monthly_attendance_report_view');
            $this->load->view('includes/footer');
        }
      
    }

    public function coaching_group_mark_student_attendance(){   
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $program_group_id =0;
            if (null !== $this->input->post('id_program_group')){
                $program_group_id =  $this->input->post('id_program_group');
            } 
            $staff_id=0; 
            $this->db->select('id_staff');
            $this->db->where('id_users', $this->session->userdata('userid'));
            $this->db->join('staff', 'staff_cell = user_mobile');
            $query = $this->db->get('users');
            $staff=$query->row(); 
             if($staff){
                $staff_id = $staff->id_staff;
             }
            if (null !== $this->input->post('staff_id')){
                $staff_id =  $this->input->post('staff_id');
            } 
            $today = date('Y-m-d');
            if(null != $this->input->post('mDate') && $this->input->post('mDate')!=''){
                $today = $this->input->post('mDate') ;
            } 
            $data['nav'] = 'Programs';
            $data['subnav'] = 'CoachingMarkStudentAttendance';
            $data['business'] = $this->business_model->getbusinessdetails();
            $data['program_groups'] = $this->coaching_model->get_program_groups();
            $data['program_group_attendance_report'] = $this->coaching_model->get_program_groups_attendance_report($program_group_id,$staff_id,$today);

            $data['program_group_id'] =  $program_group_id; 
            $data['program_staff_id'] =  $staff_id; 

            $data['staff'] = $this->staff_model->get_active_scheduler_staff($this->session->userdata('businessid') ); 
            // $data['group']=$this->coaching_model->get_group($program_group_id);
            $data['today']=$today;
            $this->load->view('includes/header', $data);
            $this->load->view('coaching/program_mark_student_attendance_view');
            $this->load->view('includes/footer');
        }
    } 


    public function coaching_group_mark_student_attendance_mark_in(){
        $customer_visit_id = $_POST['customer_visit_id'];  
        $attendance_date = $_POST['attendance_date'];   
        $attendance_date = date('Y-m-d', strtotime($attendance_date)).' '.date('H:i:s'); 
        $array =[];
         $sql = "UPDATE customer_visits 
                SET inservice = 'Yes', 
                    inservice_time = '".$attendance_date."' 
                WHERE id_customer_visits = ? ";
         $resp = $this->db->query($sql, array($customer_visit_id)); 
         if($resp){  
            $sql = "SELECT `customer_visits`.`inservice` , `customer_visits`.`inservice_time`  FROM `customer_visits` where id_customer_visits=?";
            $resp = $this->db->query($sql, array($customer_visit_id));
            $data = $resp->row();
             $array=["status"=>"success","inservice_time"=> $data->inservice_time];
          }else{
               $array=["status"=>"error","inservice_time"=>"none"];
          }
         echo json_encode($array);
         exit;
    }
    public function coaching_group_mark_student_attendance_cancel(){
        $customer_visit_id = $_POST['customer_visit_id'];  
        $array =[];
         $sql = "UPDATE customer_visits 
                SET inservice = 'No', 
                    inservice_time = Null 
                WHERE id_customer_visits = ? ";
         $resp = $this->db->query($sql, array($customer_visit_id)); 

         if($resp){  
            $sql = "SELECT `customer_visits`.`inservice` , `customer_visits`.`inservice_time`  FROM `customer_visits` where id_customer_visits=?";
            $resp = $this->db->query($sql, array($customer_visit_id));
            $data = $resp->row();
             $array=["status"=>"success","inservice_time"=> $data->inservice_time];
         }else{
               $array=["status"=>"error","inservice_time"=>"none"];
            
         }
         echo json_encode($array);
         exit;
    } 

    public function getting_groups_by_staff_id(){
        $staff_id = $_POST['staff_id'];
        $selected_date = date('Y-m-d H:i:s', strtotime($_POST['selected_date']));
        $business_id = $this->session->userdata('businessid');
        
        $sql = "SELECT 
                    `program_groups`.`id_program_groups`, 
                    `program_groups`.`program_group` 
                FROM 
                    `program_groups` 
                INNER JOIN 
                    `group_visits` 
                ON  
                    `group_visits`.`group_id` = `program_groups`.`id_program_groups` 
                WHERE 
                    `group_visits`.`staff_id` = ? 
                    AND 
                    `program_groups`.`business_id` = ? 
                    AND 
                    UNIX_TIMESTAMP(`group_visits`.`visit_service_end`) > UNIX_TIMESTAMP(?) 
                GROUP BY 
                    `program_groups`.`id_program_groups`, 
                    `program_groups`.`program_group`";
        
        $resp = $this->db->query($sql, array($staff_id, $business_id, $selected_date));
        $data = $resp->result();
        echo json_encode($data);
        exit;        
    } 
    public function getting_groups_by_date_range(){
        $start = date('Y-m-d', strtotime($_POST['selected_date']));
        $end = date('Y-m-d', strtotime($_POST['enddate'])); 
        $business_id = $this->session->userdata('businessid');
        $sql = "SELECT 
                    `program_groups`.`id_program_groups`, 
                    `program_groups`.`program_group` 
                FROM 
                    `program_groups` 
                INNER JOIN 
                    `group_visits` 
                ON  
                    `group_visits`.`group_id` = `program_groups`.`id_program_groups` 
                WHERE 
                    `program_groups`.`business_id` = ? 
                    AND 
                    date(`group_visits`.`visit_service_start`) BETWEEN date(?) AND date(?)
                GROUP BY 
                    `program_groups`.`id_program_groups`, 
                    `program_groups`.`program_group`";
        $params = array($business_id, $start, $end);
        $resp = $this->db->query($sql, $params);
        $data = $resp->result();
        echo json_encode($data);
        exit;     
    } 
    public function getting_groups_for_monthly_attendance_report() { 

        $business_id = $this->session->userdata('businessid');
         $year = $this->input->post('year');
         $month = $this->input->post('month');
         $customer_id = $this->input->post('customer_id'); 
         $sql = "
            SELECT program_groups.id_program_groups , program_groups.program_group
            FROM program_groups
            INNER JOIN program_group_members ON program_group_members.program_group_id = program_groups.id_program_groups
            INNER JOIN program_enrollment ON program_enrollment.id_program_enrollment = program_group_members.program_enrollment_id
            WHERE program_enrollment.customer_id = ? AND program_groups.business_id =?
            ";
        $query = $this->db->query($sql, array($customer_id,$business_id)); 
        if ($query) {
            $data = $query->result(); 

            echo json_encode($data);
        } else {
            echo json_encode(['error' => 'Query failed']);
        }
    }
    

    public function coaching_members(){
        //echo $this->input->post('coaching_service'); exit();
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else { 
            
            $data['nav'] = 'Programs';
            $data['subnav'] = 'CoachingMembers';

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


            $data['coaching_service'] = $this->input->post('coaching_service');
            $data['coaching_services'] = $this->service_model->get_program_services();

            $service_id=0;
            if($this->input->post('coaching_service')!= null && $this->input->post('coaching_service')!= 'All'){
                $service_id = $this->input->post('coaching_service');
            }
            if(null != $this->input->post('filter_veiw')){
                $data['status'] = $this->input->post('filter_veiw');
            }else{
                $data['status'] = 'Active';
            }
            $data['program_members'] = $this->coaching_model->get_coaching_members($service_id, $data['status']);

            //print_r($data['program_members']); exit();

            $this->load->view('includes/header', $data);
            $this->load->view('coaching/coaching_members_view');
            $this->load->view('includes/footer');
        }

    }
    public function print_coaching_enrollment($enrollment_id){

        //ENROLLMENT FORM PAGE
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'Programs';
            $data['subnav'] = 'CoachingMembers';

            $data['business'] = $this->business_model->getbusinessdetails();
            $data['program_enrollment'] = $this->coaching_model->get_enrollment_with_balance($enrollment_id);
            $data['registration_fee'] = $this->coaching_model->get_registration_fee_status($enrollment_id);
            //print_r($data['registration_fee'] );exit();

            $data['enrollment_advance'] = $this->coaching_model->get_enrollment_advance($enrollment_id);
            //print_r($data['enrollment_advance'] );exit();
            //$data['program_schedule']= $this->coaching_model->get_program_session_services($data['program_enrollment'][0]['id_program_enrollment']);
            //print_r($data['program_schedule'] );exit();
            $this->load->view('includes/header', $data);
            $this->load->view('coaching/print_coaching_enrollment');
            $this->load->view('includes/footer');
        }

    } 
    
    ////GROUP SCHEDULING PAGE
    public function coaching_group_scheduling($id_program_groups, $service_id, $staff_id){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'Programs';
            $data['subnav'] = 'ProgramMembers';

            $data['calendar']='calendar';

            $data["id_program_groups"] = $id_program_groups;
            $data["service_id"] = $service_id;
            $data["staff_id"] = $staff_id;

            $this->db->select('*');
            $this->db->where('id_business_services',$service_id);
            $query=$this->db->get('business_services');
            $data['service'] = $query->row();

            //$data['events'] = json_encode($events);          

            //$booked_sessions = $this->coaching_model->get_group_booked_sessions($id_enrolled_services);            
            //null!= $booked_sessions[0]['appointments'] ? $data['booked'] = $booked_sessions[0]['appointments'] : $data['booked'] = 0;

            $data['staff'] = $this->staff_model->get_active_scheduler_staff($this->session->userdata('businessid') );
            $data['group']=$this->coaching_model->get_group($id_program_groups);

            $this->load->view('includes/header', $data);
            $this->load->view('coaching/coaching_group_scheduling');
            $this->load->view('includes/footer');
        }
    }

    public function get_group_members_schedule_ajax(){

        $group_id=$this->input->post('group_id');
        $start = $this->input->post('start');
        $end = $this->input->post('end');

        $data['visit_events'] = $this->coaching_model->get_group_member_visits($group_id, $start, $end);
        //$data['']
        echo json_encode($data);
    }

    public function get_group_schedule_ajax(){

        $group_id=$this->input->post('group_id');
        $start = $this->input->post('start');
        $end = $this->input->post('end');

        $data['visit_events'] = $this->coaching_model->get_group_table_visits($group_id, $start, $end);
        //$data['']

        echo json_encode($data);

    }

    public function get_group_schedule_groupedby(){
        $group_id=$this->input->post('group_id');
        $start = $this->input->post('start');
        $end = $this->input->post('end');

        $data['groupevents'] = $this->coaching_model->get_group_visits($group_id, $start, $end);
        echo json_encode($data);
    }

    public function cancel_group_visits(){
        $group_id=$this->input->post('group_id');
        $staff_id=$this->input->post('staff_id');
        $date = $this->input->post('date');
        $reason=$this->input->post('cancelreason');

        $response = 0;
        if($group_id>0){
            ///Update Group Table Visit




            //update Customer Visit
            $sql = "UPDATE customer_visits, visit_services, visit_service_staffs 
                    SET `customer_visits`.`visit_status` = 'canceled', 
                    `customer_visits`.`canceled_by` = '".$this->session->userdata('username')."', 
                    `customer_visits`.`cancelreason` = 'This is a test cancelation on ". date('Y-m-d H:i:s')."' 
                    WHERE `customer_visits`.`id_customer_visits` = visit_services.customer_visit_id 
                    AND `visit_services`.`id_visit_services` = visit_service_staffs.visit_service_id
                    AND `visit_status` = 'open' AND `group_id` = '".$group_id."' AND visit_service_start = '". $date ."' 
                    AND `visit_service_staffs`.`staff_id` = '". $staff_id ."'";
            // echo $sql; exit();

            $query = $this->db->query($sql);

            $response = $query;

        }
        echo $response;
    }

    public function add_group_visit() {
        //exit();

        if ($this->session->userdata('role') == '') {
            $this->load->view('login_view');
        }else{

            $group_id = htmlspecialchars($this->input->post('program_group_id', TRUE));
            $service_id = htmlspecialchars($this->input->post('service_id', TRUE));
            $staff_id = htmlspecialchars($this->input->post('staffid', TRUE));
            $visit_date = htmlspecialchars($this->input->post('day', TRUE));
            $actual_visit_date = htmlspecialchars($this->input->post('day', TRUE));

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

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

            $weedays = $this->input->post('weekday', TRUE);


            $group_visit_id=[];
            //Add visits to group_vists table
            if(null != $group_id && $group_id != 0 && $group_id != ''){

                if($repeat > 1){
                    $visit_date = $actual_visit_date;


                    for($x=1; $x<= $repeat; $x++){//loop the number of repeats sent by user

                        //loop on the whole week
                        for($y=0; $y<=6; $y++){
                            $visitdayofweek = date('w', strtotime($visit_date)); //get the week day number of currently selected date

                            if(in_array($visitdayofweek, $weedays)){ //check if the day of the week is selected by user
                                $data=array(
                                    'group_id' => $group_id,
                                    'service_id' => $service_id,
                                    'staff_id' => $staff_id,
                                    'visit_service_start' => $visit_date.'T'.$start.':00',
                                    'visit_service_end' => $visit_date.'T'.$end.':00',
                                    'business_id' => $this->session->userdata('businessid'),
                                    'created_by' => $this->session->userdata('username'),
                                    'group_visit_date'=> date('Y-m-d H:i:s')
                                );
                                $this->db->insert('group_visits', $data);
                                $group_visit_id[] = $this->db->insert_id();
                                //$repeatinterval = $repeattype.' days';
                                $x++;
                            }
                            $nextvd = date_add(date_create($visit_date), date_interval_create_from_date_string('1 days'));
                            $visit_date = $nextvd->format('Y-m-d');
                        }
                    }
                } else{
                    //create the visit
                    $data=array(
                        'group_id' => $group_id,
                        'service_id' => $service_id,
                        'staff_id' => $staff_id,
                        'visit_service_start' => $visit_date.'T'.$start,
                        'visit_service_end' => $visit_date.'T'.$end,
                        'business_id' => $this->session->userdata('businessid'),
                        'created_by' => $this->session->userdata('username'),
                        'group_visit_date'=> date('Y-m-d H:i:s')
                    );
                    $this->db->insert('group_visits', $data);
                    $group_visit_id[] = $this->db->insert_id();
                }
            }
            ////////////////////////////////////////

            //Get Group Customers
            $this->db->select('id_customers, customer_name, customer_cell, id_program_enrollment, service_id, id_program_enrolled_services');
            $this->db->join('program_enrollment', 'program_enrollment.id_program_enrollment = program_group_members.program_enrollment_id');
            $this->db->join('program_enrolled_services', 'program_enrolled_services.program_enrollment_id = program_enrollment.id_program_enrollment');
            $this->db->join('customers', 'customers.id_customers=program_enrollment.customer_id');
            $this->db->where('program_group_id', $group_id);
            $this->db->where('member_status', 'Active');
            $this->db->where('program_enrolled_services.service_id', $service_id);
            $query = $this->db->get('program_group_members');
            $members = $query->result();


            $this->db->select('*, date_format(visit_service_start, "%Y-%m-%d") as group_visit_date, date_format(visit_service_start, "%H:%m:%s") as visit_service_start, date_format(visit_service_end, "%H:%m:%s") as visit_service_end');
            $this->db->where_in('id_group_visits', $group_visit_id);

            $query = $this->db->get('group_visits');
            $group_visits = $query->result();

            $customer_visit_id=0;

            foreach($members as $member){
                $program_enrollment_id = $member->id_program_enrollment;
                $program_enrolled_service_id = $member->id_program_enrolled_services;
                $customer_id = $member->id_customers;
                $customer_name = $member->customer_name;

                if(null != $customer_id && $customer_id != 0 && $customer_id != ''){

                    if($repeat > 1){
                        foreach($group_visits as $group_visit){
                            $customer_visit_id = $this->visits_model->add_visit_with_receivable($customer_id, $customer_name, $staff_id, $service_id, $group_visit->group_visit_date, $group_visit->visit_service_start, $group_visit->visit_service_end, $program_enrolled_service_id, $group_id, $group_visit->id_group_visits);
                        }
                    } else{
                        //create the visit
                        $customer_visit_id = $this->visits_model->add_visit_with_receivable($customer_id, $customer_name, $staff_id, $service_id, $actual_visit_date, $start, $end, $program_enrolled_service_id, $group_id, $group_visit_id[0]);
                    }
                }
            }
            if($customer_visit_id > 0){
                $this->session->set_flashdata('Success', 'Successfully Added Appointment!');
            } else {
                $this->session->set_flashdata('Error', 'Some Error Occurred, Group Appointments were Not Added!');
            }


            redirect(base_url('coaching_group_scheduling/'.$group_id.'/'.$service_id.'/'.$staff_id));

        }
    }

    public function update_group_visit(){
        //exit();

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

        $staff_id=$this->input->post('staff_id');
        $start = null != $this->input->post('modal_start_date') ? $this->input->post('modal_start_date')."T".$this->input->post('modal_start_time')  : $this->input->post('start');
        $end = null != $this->input->post('modal_start_date') ? $this->input->post('modal_start_date')."T".$this->input->post('modal_end_time')  : $this->input->post('end');

        $id_group_visits=$this->input->post('id_group_visits');
        $service_id = $this->input->post('id_visit_services');

        $groupvisitdata=array(
            'service_id' => $service_id,
            'visit_service_start' => $start,
            'visit_service_end' => $end,
            'staff_id' => $staff_id
        );
        $this->db->where('id_group_visits', $id_group_visits);
        $this->db->update('group_visits', $groupvisitdata);

        ///update customer visit
        $sql = "update customer_visits, visit_services, visit_service_staffs
                set visit_services.update_date = '".date('Y-m-d H-:i:s')."',
                visit_services.visit_service_start = '".$start."',
                visit_services.visit_service_end = '".$end."',
                visit_service_staffs.staff_id = '".$staff_id."'
                where customer_visits.id_customer_visits = visit_services.customer_visit_id
                and visit_services.id_visit_services = visit_service_staffs.visit_service_id
                and visit_service_staffs.visit_service_id = visit_services.id_visit_services
                and customer_visits.group_visit_id = ". $id_group_visits ."
        ";
        $update = $this->db->query($sql);
        if(null == $this->input->post('modal_start_date')){
            if($update > 0){
                echo 'success|Existing Visits Updated!';
            }else {
                echo 'error|No Existing Visits Updated!';
            }
        }else{

            //coaching_group_scheduling/4/538/0
            redirect(base_url('coaching_group_scheduling/'.$group_id.'/'.$service_id.'/'.$staff_id));

        }
    }



    ///MEMBER SCHEDULING PAGE
    public function coaching_service_provisioning($id_program_enrollment, $id_enrolled_services, $service_id, $staff_id){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'Programs';
            $data['subnav'] = 'ProgramMembers';

            $data['calendar']='calendar';

            $data["id_program_enrollment"] = $id_program_enrollment;
            $data["id_enrolled_services"] = $id_enrolled_services;
            $data["service_id"] = $service_id;
            $data["staff_id"] = $staff_id;


            $data['scheduling_details'] = $this->coaching_model->get_scheduling_details($id_program_enrollment, $id_enrolled_services);
            //print_r($data['scheduling_details']);exit();

            $this->db->select('*');
            $this->db->where('id_business_services',$service_id);
            $query=$this->db->get('business_services');

            $data['service'] = $query->row();
            //print_r($data['service']);exit();

            $events = $this->coaching_model->get_calendar_visits($id_enrolled_services);
            $booked_sessions = $this->coaching_model->get_booked_sessions($id_enrolled_services);

            if(null != $booked_sessions){
                $data['booked'] = $booked_sessions[0]['appointments'];
            }else{
                $data['booked'] = 0;
            }

            //echo $data['booked'] ; exit();
            $data['events'] = json_encode($events);

            $data['staff'] = $this->staff_model->get_active_scheduler_staff($this->session->userdata('businessid') );

            $this->load->view('includes/header', $data);
            $this->load->view('coaching/coaching_service_scheduling');
            $this->load->view('includes/footer');
        }

    } 

    //// Program completion certificate 
    public function program_completion_certificate($id_program_enrollment, $id_enrolled_services, $service_id, $staff_id){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'Programs';
            $data['subnav'] = 'ProgramMembers';
            $data['calendar']='calendar';  
            $data["id_program_enrollment"] = $id_program_enrollment;
            $data["id_enrolled_services"] = $id_enrolled_services;
            $data["service_id"] = $service_id;
            $data["staff_id"] = $staff_id; 
            $sql="SELECT 
                        SUM(ifnull(program_invoices.invoiced_amount,0)) AS invoice_amount,  
                        SUM(ifnull(program_invoice_payments.paid_amount ,0)) AS paid_amount 
                        FROM 
                            program_invoices 
                        LEFT JOIN 
                         program_invoice_payments 
                        ON 
                        program_invoice_payments.program_invoice_id = program_invoices.id_program_invoices 
                        AND program_invoice_payments.payment_status != 'Cancelled' 
                        WHERE 
                        program_invoices.program_enrolled_service_id = ?  and program_invoices.business_id =?
                        GROUP BY 
                            program_invoices.program_enrolled_service_id"; 
                $resp = $this->db->query($sql, array($id_enrolled_services ,$this->session->userdata('businessid')));
                $invoice_data  = $resp->row(); 
         
                $data["invoice_data"] =   $invoice_data;
               $sql="SELECT program_enrolled_services.service_name , customers.customer_name , business.business_name , business.business_logo FROM 
               `program_enrollment` INNER join program_enrolled_services on program_enrolled_services.program_enrollment_id = `program_enrollment`.`id_program_enrollment`
               inner join customers on  customers.id_customers = `program_enrollment`.`customer_id`
               INNER join business on business.id_business = customers.business_id
               where  program_enrollment.id_program_enrollment=? and  business.id_business =?"; 
                $resp = $this->db->query($sql, array($id_program_enrollment ,$this->session->userdata('businessid')));
                $certificate_data  = $resp->row(); 

                $sql="SELECT `business_signature_images`.`signature_image` FROM `business_signature_images` where business_id=?"; 
                $resp = $this->db->query($sql, array($this->session->userdata('businessid')));
                $ceo_signature  = $resp->row(); 

                $data["ceo_signature"] = $ceo_signature ;  
                $data["certificate_data"] = $certificate_data;  
              // $this->load->view('includes/header', $data);
              $this->load->view('coaching/student_program_certificate_view', $data);
              // $this->load->view('includes/footer');
        }
    } 

    public function get_staff_schedule_ajax(){

        $staff_id=$this->input->post('staff_id');
        $day=$this->input->post('day');

        $data['visit_events'] = $this->coaching_model->get_staff_schedule($staff_id, $day);
        //$data['']

        echo json_encode($data);

    }


    public function addvisit() {

//        $visit_date = htmlspecialchars($this->input->post('day', TRUE));
//        $start = htmlspecialchars($this->input->post('start', TRUE));
//        $repeat = htmlspecialchars($this->input->post('repeat', TRUE));   
//        
//        for($x=1; $x<= $repeat; $x++){
//            echo '<pre>';
//            print_r($visit_date);
//            echo '</pre>';
//            $nextvd = date_add(date_create($visit_date), date_interval_create_from_date_string("7 days")); 
//            $visit_date = $nextvd->format('Y-m-d'); 
//            
//        }
//            
//        exit();

        if ($this->session->userdata('role') == '') {
            $this->load->view('login_view');
        }else{

            $customer_id = htmlspecialchars($this->input->post('customerid', TRUE));
            $customer_name = htmlspecialchars($this->input->post('customername', TRUE));
            $staff_id = htmlspecialchars($this->input->post('staffid', TRUE));
            $service_id = htmlspecialchars($this->input->post('serviceid', TRUE));
            $visit_date = htmlspecialchars($this->input->post('day', TRUE));
            $actual_visit_date = htmlspecialchars($this->input->post('day', TRUE));

            $start = htmlspecialchars($this->input->post('start', TRUE));
            $end = htmlspecialchars($this->input->post('end', TRUE));
            $program_enrolled_service_id = htmlspecialchars($this->input->post('program_enrolled_service_id', TRUE));
            $program_enrollment_id = htmlspecialchars($this->input->post('program_enrollment_id', TRUE));

            $totalsessions = $this->input->post('total_sessions');
            $bookedsessions = $this->input->post('booked_sessions');
            $remainingsessions=$totalsessions - $bookedsessions;

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

            $customer_visit_id=0;

            if(null != $customer_id && $customer_id != 0 && $customer_id != ''){

                if($repeat > 1){
                    $visit_date = $actual_visit_date;
                    for($x=1; $x<= $repeat; $x++){
                        $customer_visit_id = $this->visits_model->add_visit_with_receivable($customer_id, $customer_name, $staff_id, $service_id, $visit_date, $start, $end, $program_enrolled_service_id);
                        $repeatinterval = $repeattype.' days';
                        $nextvd = date_add(date_create($visit_date), date_interval_create_from_date_string($repeatinterval));
                        $visit_date = $nextvd->format('Y-m-d');
                    }
                } else{
                    //create the visit
                    $customer_visit_id = $this->visits_model->add_visit_with_receivable($customer_id, $customer_name, $staff_id, $service_id, $actual_visit_date, $start, $end, $program_enrolled_service_id);
                }
            }
            if($customer_visit_id > 0){
                $this->session->set_flashdata('Success', 'Successfully Added Appointment!');
            } else {
                $this->session->set_flashdata('Error', 'Some Error Occurred, Appointment was Not Added!');
            }


            redirect(base_url('coaching_service_provisioning/'.$program_enrollment_id.'/'.$program_enrolled_service_id.'/'.$service_id.'/'.$staff_id));

        }
    }


    public function updatevisit() {

        if ($this->session->userdata('role') == '') {
            echo 'sessionexpired';
        }else{

            $id_visit_services = htmlspecialchars($this->input->post('id_visit_services', TRUE));
            $id_visit_service_staff = htmlspecialchars($this->input->post('id_visit_service_staffs', TRUE));
            $old_staff_id = htmlspecialchars($this->input->post('old_staff_id', TRUE));
            $staff_id = htmlspecialchars($this->input->post('staff_id', TRUE));

            if(null != $this->input->post("modal_start_date")){
                $startdate = $this->input->post("modal_start_date");
                $starttime = $this->input->post("modal_start_time");
                $endtime = strtotime($starttime);
                $endtime = $endtime + 3600;
                $start = $startdate.'T'.$starttime;
                $end = $startdate.'T'.strftime('%H:%M:%S', $endtime);;
            }else {
                $start = htmlspecialchars($this->input->post('start', TRUE));
                $end = htmlspecialchars($this->input->post('end', TRUE));
            }

            $visit_status = htmlspecialchars($this->input->post('visit_status', TRUE));
            //echo $id_visit_service_staff; exit();
            $staff = $this->scheduler_model->getStaff($staff_id);

            $staffData = array(
                'staff_id' => $staff_id,
                'staff_name' => $staff->staff_fullname,
                'block_other' => $staff->staff_shared
            );

            $serviceData = array(
                'visit_service_start' => $start,
                'visit_service_end' => $end,
                'update_date' => date('Y-m-d H:i:s')
            );

            $update = $this->coaching_model->updateVisit($id_visit_services, $staff_id, $old_staff_id, $staffData, $serviceData);

            ///check if invoiced

            if(strtolower($visit_status) == 'invoiced'){

                $InvstaffData = array(
                    'staff_id' => $staff_id,
                    'staff_name' => $staff->staff_fullname
                );

                $update1 = $this->scheduler_model->updateInvoiceStaff($id_visit_service_staff, $old_staff_id, $InvstaffData);
            }
            if($this->input->post('id_program_enrollment') !=null){
                redirect(base_url('coaching_service_provisioning/'.$this->input->post('id_program_enrollment').'/'.$this->input->post('id_enrolled_services').'/'.$this->input->post('service_id').'/'.$staff_id));
            }else{
                if ($update) {
                    $data = $this->scheduler_model->getMaxVisitServiceId(date('Y-m-d', strtotime($start)));
                    echo "success|" . $data->update_date;
                }
            }
        }
    }



///Invoicing and Payment
    public function coaching_invoice_list($enrollment_id){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'Programs';
            $data['subnav'] = 'ProgramMembers';

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

            $program_enrollment_services = $this->coaching_model->get_enrollment_services($enrollment_id);

            $program_enrollment_payment = [];

            foreach($program_enrollment_services as $pes){
                $enrolled_service_id = $pes['id_program_enrolled_services'];
                $booked_sessions['bookings'] = $this->coaching_model->get_booked_sessions($enrolled_service_id);
                $invoices_sessions['invoiced'] = $this->coaching_model->get_invoiced_session_count($enrolled_service_id);
                $enrollment_invoices['invoices'] =  $this->coaching_model->get_enrollment_invoices($enrolled_service_id);

                $program_enrollment_payment[]=array_merge($pes, $enrollment_invoices, $booked_sessions, $invoices_sessions);
            }
//            echo '<pre>';
//            print_r($program_enrollment_payment);
//            exit();

            $data['program_enrollment']=$program_enrollment_payment;
            $data['registration_fee_invoice'] =  $this->coaching_model->get_enrollment_invoices(0, $enrollment_id);
            $data['remaining_advance'] = $this->coaching_model->get_remaining_advance($enrollment_id);


            $this->load->view('includes/header', $data);
            $this->load->view('coaching/coaching_invoice_list');
            $this->load->view('includes/footer');
        }

    }


    public function get_coaching_invoice_detail(){
        $invoice = $this->coaching_model->get_coaching_invoice_detail($this->input->post('invoice_id'));
        echo json_encode($invoice);
    }

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

            $data['nav'] = 'Programs';
            $data['subnav'] = 'TrainingPrograms';


            $data['invoice_id'] = $this->coaching_model->add_coaching_invoice();

            if($data['invoice_id']  && $data['invoice_id'] >0){
                $this->session->set_flashdata('Success', 'Receivable Successfully Added!');
            } else {
                $this->session->set_flashdata('Error', 'Some Error Occurred, Receivable Vocuher Not Added!');
            }
//            echo '<pre>';
//            print_r($data['details']); exit();

            redirect(base_url('coaching_invoice_list/'.$this->input->post("program_enrollment_id")));
        }

    }


    public function cancel_coaching_invoice($invoiceid, $program_enrollment_id){

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

            $data['nav'] = 'Programs';
            $data['subnav'] = 'TrainingPrograms';

            if(null == $invoiceid){
                $invoiceid= $this->input->post('invoiceid');
            }

            $rowsaffected = $this->coaching_model->cancel_invoice($invoiceid);

            if($rowsaffected  && $rowsaffected > 0){
                $this->session->set_flashdata('Success', 'Invoice Successfully Cancelled!');
            } else {
                $this->session->set_flashdata('Error', 'Some Error Occurred, Invoice was not Cancelled!');
            }

            redirect(base_url('coaching_invoice_list/'.$program_enrollment_id));
        }


    }


    public function print_coaching_invoice($invoice_id){
        //echo $invoice_id; //exit();
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nodatatable']='nodatatable';

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

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

            $data['business'] = $this->business_model->getbusinessdetails();
            $data['taxes']=$this->coaching_model->getinvocietaxes($invoice_id);

            $data['invoice'] = $this->coaching_model->get_coaching_invoice($invoice_id);

            //print_r($data['invoice']);exit();
            $this->load->view('includes/header', $data);
            $this->load->view('coaching/exist_invoice_view');
            $this->load->view('includes/footer');
        }

    }

    public function print_pending_invoices($enrollmentid){
        //echo $invoice_id; //exit();
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nodatatable']='nodatatable';

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

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

            $data['business'] = $this->business_model->getbusinessdetails();
            $data['taxes']=$this->coaching_model->getenrollmentinvocietaxes($enrollmentid, 'Receivable');

            $data['invoice'] = $this->coaching_model->get_all_enrollment_invoices($enrollmentid, 'Receivable');

            //  print_r($data['invoice']);exit();

            $this->load->view('includes/header', $data);
            $this->load->view('coaching/exist_receivable_invoices_view');
            $this->load->view('includes/footer');
        }

    }


    public function print_all_invoices($enrollmentid){
        //echo $invoice_id; //exit();
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nodatatable']='nodatatable';

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

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

            $data['business'] = $this->business_model->getbusinessdetails();
            $data['taxes']=$this->coaching_model->getenrollmentinvocietaxes($enrollmentid, 'Receivable');

            $data['invoice'] = $this->coaching_model->get_all_enrollment_invoices($enrollmentid);

            //  print_r($data['invoice']);exit();

            $this->load->view('includes/header', $data);
            $this->load->view('coaching/exist_receivable_invoices_view');
            $this->load->view('includes/footer');
        }

    }

    public function invoice_payments_on_each_invoice($invoice_id , $enrollmentid){
        //echo $invoice_id; //exit();
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nodatatable']='nodatatable';

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

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

            $data['business'] = $this->business_model->getbusinessdetails();
            $data['taxes']=$this->coaching_model->getenrollmentinvocietaxes($enrollmentid, 'Receivable');
            $data['invoice'] = $this->coaching_model->get_each_enrollment_invoices($enrollmentid,$invoice_id);
            $data['invoice_payments_data'] = $this->coaching_model->invoice_each_payments_data($invoice_id);
            //    print_r($data['invoice_payments_data']);exit();
            $this->load->view('includes/header', $data);
            $this->load->view('coaching/existing_invoice_multiple_payment_view');
            $this->load->view('includes/footer');
        }

    }

    public function cancel_program_invoice_payment(){
        $r = $this->coaching_model->cancel_program_invoice_payment();
        echo json_encode($r);
    }

    public function open_receivable_invoices($enrollmentid){
        //echo $invoice_id; //exit();
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nodatatable']='nodatatable';

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

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

            $data['business'] = $this->business_model->getbusinessdetails();
            $data['taxes'] = $this->coaching_model->getenrollmentinvocietaxes($enrollmentid, 'Receivable');
            $data['invoice'] = $this->coaching_model->get_all_enrollment_invoices($enrollmentid, 'Receivable');
            $data['enrollmentid'] =  $enrollmentid;
            $this->load->view('includes/header', $data);
            $this->load->view('coaching/payment_receivable_invoices_view');
            $this->load->view('includes/footer');
        }

    }


    public function add_receivable_invoices_payment(){

        // exit();
        $id_program_enrollment = $this->input->post('id_program_enrollment');

        if($this->input->post('payingnow')!=0){
            $id_program_invoices = $this->input->post('id_program_invoice');
            $invoice_other_charges = $this->input->post('invoice_other_charges');
            $invoice_discount = $this->input->post('invoice_discount');
            $mode = $this->input->post('mode');
            $cc_charge = $this->input->post('cc_charge');
            $salestax = $this->input->post('salestax');
            $paid_amount = $this->input->post('paid_amount');
            $balance = $this->input->post('balance');
            foreach($id_program_invoices as $index => $id_invoice){

                if($paid_amount[$index]>0 ){ //No balance generated && $balance[$index] == 0 

                    //update invoice
                    $sql = "update program_invoices 
                    set invoice_other_charges = ".$invoice_other_charges[$index].",
                    invoice_discount = ".$invoice_discount[$index].",
                    salestax = ". $salestax[$index]."
                    where id_program_invoices = ".$id_invoice.";";
                    $this->db->query($sql);
                    //add to payment table
                    $data = array(
                        'program_invoice_id' => $id_invoice,
                        'cc_charge' => isset($cc_charge[$index]) ? $cc_charge[$index] : 0,
                        'paid_cash' => $mode[$index] == 'Cash' ? $paid_amount[$index] : 0,
                        'paid_card' => $mode[$index] == 'Card' ? $paid_amount[$index] : 0,
                        'paid_check' => $mode[$index] == 'Check' ? $paid_amount[$index] : 0,
                        'paid_amount' => $paid_amount[$index],
                        'payment_mode' => $mode[$index],
                        'payment_date'  => date('Y-m-d H:i:s'),
                        'payment_received_by'  => $this->session->userdata('username'),
                        'other_charges'=>  isset($invoice_other_charges[$index]) ? $invoice_other_charges[$index] : 0,
                        'payment_status'=>'Paid',
                        'payment_discount'=>isset($invoice_discount[$index]) ? $invoice_discount[$index] : 0,
                        'created_by' =>$this->session->userdata('username')
                    );
                    //update the payment using $id_invoice                    
                    $this->db->insert('program_invoice_payments', $data);
                    $program_invoice_payment_id =  $this->db->insert_id();

                    //create a receiving voucher RV
                    $voucherid[] = $this->create_receiving_voucher($id_invoice, date('d-m-Y H:i:s'), 0 ,$program_invoice_payment_id);
                    //echo 'voucher '.'<br>';
                    //print_r($voucherid);
                    //echo '<br>';
                }
            }
        }
        redirect('print_all_invoices/'.$id_program_enrollment);


    }

    public function add_invoice_payment(){

        //exit();

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

            $data['nav'] = 'Programs';
            $data['subnav'] = 'TrainingPrograms';


            $program_enrollment_id= $this->input->post('txtpaymentenrollmentid');
            $invoice_id = $this->coaching_model->add_invoice_payment();

            if($invoice_id > 0){
                $this->session->set_flashdata('Success', 'Invoice Payment Successfully Entered!');
            } else {
                $this->session->set_flashdata('Error', 'Invoice Payment Not Entered!');
            }

            redirect(base_url('coaching_invoice_list/'.$program_enrollment_id));
        }

    }

    function cancel_invoice_payment(){

        $invoiceid = $this->input->post('invoice_id');

        $sql="select * from program_invoices where program_invoice_remarks like 'Recovery invoice for invoice ID ".$invoiceid." %'";
        $query = $this->db->query($sql);
        //print_r($query->num_rows());
        //exit();
        if($query->num_rows() == 0){
            $sql="select * from program_invoices where id_program_invoices = ".$invoiceid;
            $query1 = $this->db->query($sql);
            $invoice = $query1->row();

            //update invoice
            $this->db->set('paid_amount', 0);
            $this->db->set('paid_cash', 0);
            $this->db->set('paid_card', 0);
            $this->db->set('paid_check', 0);
            $this->db->set('return_amount', 0);
            $this->db->set('balance_amount', $this->input->post('paid_amount')+$invoice->balance);
            $this->db->set('payment_mode', 'Receivable');
            $this->db->set('payment_date', null);
            $this->db->set('payment_received_by', null);
            $this->db->where('id_program_invoices', $invoiceid);
            $this->db->update('program_invoices');


            //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_id', $invoiceid);
            $this->db->where('voucher_type', 2);
            $this->db->update('account_vouchers');

            echo 'Success'.'|'.$invoiceid;
        } else {

            echo 'Error'.'|There are pending recovery invoices for invoice '.$invoiceid.'. Remove them first!';

        }

    }

    public function remove_recovery(){

        $invoiceid = $this->input->post('invoice_id');

        $sql1="select * from program_invoices where id_program_invoices=".$invoiceid;
        $query1 = $this->db->query($sql1);
        $row= $query1->row();
        $org_invoice_id=$row->org_invoice_id;

        //echo $org_invoice_id; exit();


        //check if other recovery invoices exists for the orginal invoice
        $sql="select * from program_invoices where program_invoice_status='Active' and program_invoice_remarks 
        like 'Recovery %' and id_program_invoices > ".$invoiceid.";";
        $query = $this->db->query($sql);



        if($query->num_rows()>0){
            echo 'Error'.'|There are pending recovery invoices created after invoice '.$invoiceid.'. Remove them first!';
        }else{
            $sql2="select * from program_invoices where  id_program_invoices = ".$invoiceid." and org_invoice_id = ".$org_invoice_id.";";
            $query2 = $this->db->query($sql2);
            $thisinvoice = $query2->row();

            $this->db->set('program_invoice_status', 'InActive');
            $this->db->where('id_program_invoices', $invoiceid);
            $this->db->update('program_invoices');

            $this->db->set('invoice_balance', $thisinvoice->invoice_balance + $thisinvoice->paid_amount);
            $this->db->where('id_program_invoices', $org_invoice_id);
            $this->db->update('program_invoices');


            echo 'Success'.'|'.$invoiceid;
        }

    }
    public function coach_schedule($day=null, $staffid=null){

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

            if(null == $staffid){
                $staffid=0;
            }

            if(null == $day){
                $day= date('Y-m-d');
            }

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

            $data['nav'] = 'Reception';
            $data['subnav'] = 'CoachingRegister';
            $data['menu'] = 'hidden';

            $data['calendar']='calendar';

            $data['business'] = $this->business_model->getbusinessdetails();
            $data['program_id']=5;
            $data['visit_events'] = $this->coaching_model->get_staff_schedule($staffid, $day);


            $this->db->select("id_staff, staff_fullname");
            $this->db->where("id_staff", $staffid);
            $query = $this->db->get('staff');
            $staffdetail=$query->row();

            $data['staff']=$staffdetail;
            $data['day']=$day;

            $this->load->view('includes/header', $data);
            $this->load->view('coaching/coach_schedule');
            $this->load->view('includes/footer');
        }

    }

    public function print_student_schedule($programenrollmentid, $enrolledserviceid){

        $data = $this->coaching_model->get_scheduling_details($programenrollmentid,0);
        echo json_encode($data);

    }



    ////////Coaching Groups//////////////    
    public function coaching_groups(){

        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            //storemanager,hr,reception...user serial
            //checkroles(0, 0, 0);
            $data['nav'] = 'Reception';
            $data['subnav'] = 'CoachingGroup';
            $status=null;
            $serviceid=null;
            if(null != $this->input->post('group_status') && $this->input->post('group_status')!='All'){
                $status = $this->input->post('group_status');
            }
            if(null != $this->input->post('service_id')){
                $serviceid = $this->input->post('service_id');
            }
            $data['business'] = $this->business_model->getbusinessdetails();
            $data['program_id']=5;
            $data['groups'] = $this->coaching_model->get_groups($status, $serviceid); 

            
            if($this->session->userdata('gym')=='Yes' ){
                $this->db->select('*');
                $this->db->where('program_type', 'Gym');
                $query = $this->db->get('program_types');

                $program_types=$query->result_array();

                $data['program_id'] = $program_types[0]['id_program_types'];
                $data['registration_fee'] = $program_types[0]['registration_fee'];
                $data['program_type']='Gym';
            } else {
                $this->db->select('*');
                $this->db->where('program_type', 'Coaching');
                $query = $this->db->get('program_types');
                $program_types=$query->result_array();

                $data['program_id'] = $program_types[0]['id_program_types'];
                $data['registration_fee'] = $program_types[0]['registration_fee'];
                $data['program_type']='Programs';
            }

            $data['coaching_services'] = $this->service_model->get_program_services($data['program_type']);


            // $data['coaching_services'] = $this->service_model->get_program_services();
            $data['coaching_service']= $this->input->post('service_id');
            $data['group_status']= $this->input->post('group_status'); 


            $this->load->view('includes/header', $data);
            $this->load->view('coaching/coaching_groups');
            $this->load->view('includes/footer');
        }
    } 
   
    public function addgroup(){

        $this->db->select('id_business_services, service_name');
        $this->db->where('id_business_services', $this->input->post('serviceid'));
        $query = $this->db->get('business_services');
        $service=$query->row();


        $data=array(
            'program_group' => $this->input->post('groupname'),
            'total_group_session' => $this->input->post('total_group_session'),
            'program_service_id' => $this->input->post('serviceid'),
            'program_service_name' => $service->service_name,
            'created_by' => $this->session->userdata('username'),
            'group_status' => 'Active',
            'business_id' => $this->session->userdata('businessid')
        );

        $this->db->insert('program_groups', $data);

        echo $this->db->insert_id();

    }

    public function editgroup(){
        $this->db->select('id_business_services, service_name');
        $this->db->where('id_business_services', $this->input->post('editserviceid'));
        $query = $this->db->get('business_services');
        $service=$query->row();


        $data=array(
            'program_group' => $this->input->post('editgroupname'),
            'total_group_session' => $this->input->post('edit_total_group_sessions'),
            'program_service_id' => $this->input->post('editserviceid'),
            'program_service_name' => $service->service_name,
            'created_by' => $this->session->userdata('username'),
            'group_status' => $this->input->post('editgroupstatus'),
            'business_id' => $this->session->userdata('businessid')
        );
        $this->db->where('id_program_groups',$this->input->post('id_program_groups'));
        $this->db->update('program_groups', $data);

        echo $this->db->affected_rows();
    }

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

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

            $data['nav'] = 'Reception';
            $data['subnav'] = 'CoachingGroup';

            $status=null;

            if(null != $this->input->post('group_status')){
                $status = $this->input->post('member_status');
            }

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

            $data['group'] = $this->coaching_model->get_group($groupid);
            $data['groups'] = $this->coaching_model->get_groups();


            $data['program_id']=5;
            $data['group_members'] = $this->coaching_model->get_group_members($groupid, $status);

            $data['coaching_services'] = $this->service_model->get_program_services();
            $data['coaching_service']= $this->input->post('service_id');
            $data['group_status']= $this->input->post('group_status');

            $this->load->view('includes/header', $data);
            $this->load->view('coaching/coaching_group_members');
            $this->load->view('includes/footer');
        }

    }

    public function addgroupmember(){
        //exit();
        //get enrollment id
        $data=array(
            'program_enrollment_id' => $this->input->post('id_program_enrollment'),
            'program_group_id' => $this->input->post('add_program_group_id'),
            'added_on' => date('Y-m-d H:i:s'),
            'added_by' => $this->session->userdata('username'),
            'member_status' => $this->input->post('add_program_member_status')
        );
        $this->db->insert('program_group_members', $data);
        echo $this->db->insert_id();
    }

    public function editgroupmember(){
        //exit();
        $data=array(
            'program_group_id' => $this->input->post('edit_program_group_id'),
            'member_status' => $this->input->post('edit_program_group_status')
        );
        $this->db->where('id_program_group_members', $this->input->post('id_program_group_members'));
        $this->db->update('program_group_members', $data);

        echo $this->db->affected_rows();

    }


    public function searchnameforco() {

        //get the posted values
        $customername = $this->input->get("customername", TRUE);
        $groupid = $this->input->get("groupid", TRUE);

        $data = $this->coaching_model->get_bynameco($customername, $groupid);

        echo(json_encode($data));
    }



    ///advance notes


    public function add_enrollment_advance(){

        $data= array(
            'program_enrollment_id' => $this->input->post('enrollment_id'),
            'advance_amount' => $this->input->post('advance_amount'),
            'advance_mode' => $this->input->post('advance_mode'),
            'advance_inst' => $this->input->post('advance_inst'),
            'advance_cccharge' => $this->input->post('advance_cc_charge'),
            'advance_remarks' => $this->input->post('advance_comment'),
            'advance_date' => $this->input->post('advance_date')

        );

        $advanceid= $this->coaching_model->add_program_advance($data, $this->input->post('enrollment_id'));


        echo $advanceid;
    }

    public function print_advance_note($advance_note_id){

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

            $data['nav'] = 'Reception';
            $data['subnav'] = 'CoachingRegister';
            $data['menu'] = 'hidden';

            $data['business'] = $this->business_model->getbusinessdetails();
            $data['program_id']=5;

            $sql = "SELECT program_advance_note.*, id_customers, id_program_enrollment, customer_address, customers.customer_name, customers.customer_cell, customers.customer_email,
                    date_format(advance_date,'%d-%m-%Y') as advance_date
                     FROM program_advance_note
                    join program_enrollment on program_enrollment.id_program_enrollment = program_advance_note.program_enrollment_id
                    join customers on customers.id_customers = program_enrollment.customer_id
                    where id_program_advance_note = ".$advance_note_id.";";
            $query = $this->db->query($sql);
            $data['advance'] = $query->result_array();

            $enrollment_id = $data['advance'][0]['id_program_enrollment'];


            $data['services'] = $this->coaching_model->get_enrollment_with_balance($enrollment_id);

            $this->load->view('includes/header', $data);
            $this->load->view('coaching/print_coaching_advance');
            $this->load->view('includes/footer');
        }
    }

    public function remove_enrollment_advance(){

        $this->db->select('sum(advance_amount) as advance_amount, sum(advance_used) as advance_used');
        $this->db->where('program_enrollment_id', $this->input->post('enrollment_id'));
        $this->db->where('advance_status', 'Active');
        $query = $this->db->get('program_advance_note');

        $advance_notes = $query->row();

        $advance_remaining = $advance_notes->advance_amount - $advance_notes->advance_used;

        if($advance_remaining > 0){
            $this->db->select('advance_amount');
            $this->db->where('id_program_advance_note', $this->input->post('advance_note_id'));
            $this->db->where('advance_status', 'Active');
            $query = $this->db->get('program_advance_note');

            $advance_note = $query->row();
            // print_r($advance_note); exit();
            if($advance_note->advance_amount <= $advance_remaining){
                $this->db->where('id_program_advance_note', $this->input->post('advance_note_id'));
                $this->db->set('advance_status', 'InActive');
                $this->db->set('cancelled_by', $this->session->userdata('username'));
                $this->db->set('cancelled_on', date('y-m-d H:i:s'));
                $this->db->update('program_advance_note');

                if($this->db->affected_rows()>0){
                    ////update advance account voucher
                    $this->db->where('visit_advance_id', $this->input->post('advance_note_id'));
                    $this->db->where('program_enrollment_id', $this->input->post('enrollment_id'));
                    $this->db->set('voucher_status', 'Cancelled');
                    $this->db->set('cancelled_by', $this->session->userdata('username'));
                    $this->db->set('cancelled_on', date('y-m-d H:i:s'));
                    $this->db->update('account_vouchers');
                }
                echo 'success';
            }   else {
                echo 'Advance is already used and cannot be removed!';
            }

        }else {
            echo 'Advance is already used and cannot be removed!';
        }
    }



    // $data = array(     
    //     'program_invoice_id' => $id_invoice,
    //     'cc_charge' => $cc_charge[$index],
    //     'paid_cash' => $mode[$index] == 'Cash' ? $paid_amount[$index] : 0,
    //     'paid_card' => $mode[$index] == 'Card' ? $paid_amount[$index] : 0,
    //     'paid_check' => $mode[$index] == 'Check' ? $paid_amount[$index] : 0,
    //     'paid_amount' => $paid_amount[$index],                        
    //     'payment_mode' => $mode[$index],
    //     'payment_date'  => date('Y-m-d H:i:s'),
    //     'payment_received_by'  => $this->session->userdata('username')                        
    // );

    function create_receiving_voucher($invoice_id, $paymentdate, $balance , $program_invoice_payment_id=null ){
        //get invoice
        $this->db->select("customer_name, customer_id, id_program_invoices, id_program_enrollment, program_enrolled_service_id, program_enrollment_id,
       program_invoice_payments.paid_amount, program_invoice_payments.paid_cash, program_invoice_payments.paid_card, program_invoice_payments.paid_check, advance_used, salestax, invoiced_amount, invoice_discount,
               rounding_adjustment, program_invoice_payments.cc_charge, return_amount,  program_invoices.invoice_other_charges as  invoice_other_charges, program_invoice_payments.payment_mode ,program_invoice_payments.id_program_invoice_payments");
        $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_invoice_payments", "program_invoice_payments.program_invoice_id = program_invoices.id_program_invoices", "left");
        //$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);
        $this->db->where("program_invoice_payments.id_program_invoice_payments", $program_invoice_payment_id);
        $query =$this->db->get("program_invoices");
        $invoice_data = $query->row();
        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' => date('Y-m-d H:i:s'),
                'voucher_amount' => $invoice_data->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'=>$invoice_data->payment_mode,
                '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,
                'program_invoice_payment_id	'=> $invoice_data->id_program_invoice_payments
            );

            $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" &&  $invoice_data->paid_cash > 0){$debitamount= $invoice_data->paid_cash;}
                if($debit[2]=="paid_card" &&  $invoice_data->paid_card > 0){$debitamount= $invoice_data->paid_card ;}
                if($debit[2]=="paid_check" &&  $invoice_data->paid_check > 0){$debitamount= $invoice_data->paid_check;}
                if($debit[2]=="advance_used" && $invoice_data->advance_used > 0){$debitamount= $invoice_data->advance_used ;}
                // if($debit[2]=="sale_discount" && $invoice_data->invoice_discount > 0){$debitamount= $invoice_data->invoice_discount;}

                // if($debit[2]=="rounded_adjustment" && $this->input->post('txtroundadj') > 0){$debitamount= $this->input->post('txtroundadj');}
                if($debit[2]=="rounded_adjustment"){
                    if($invoice_data->rounding_adjustment < 0){

                        $debitamount=$invoice_data->rounding_adjustment*-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"){
                    if($balance==0){
                        $creditamount = $invoice_data->paid_amount-  ($invoice_data->cc_charge);
                    } else {
                        // $creditamount = ($invoice_data->paid_amount+$invoice_data->invoice_discount) - ($invoice_data->salestax + $invoice_data->invoice_other_charges + $invoice_data->cc_charge);                        
                        $creditamount = ($invoice_data->paid_amount) - ($invoice_data->cc_charge);
                    }
                }

                // if($credit[2]=="sales_tax"){$creditamount= $invoice_data->salestax;}
                // if($credit[2]=="other_charges"){$creditamount= $invoice_data->invoice_other_charges;}
                if($credit[2]=="cc_fee"){$creditamount= $invoice_data->cc_charge;}
                if($credit[2]=="return_cash"){$creditamount= $invoice_data->return_amount;}
                //if($credit[2]=="rounded_adj"){$creditamount= $this->input->post('txtroundadj');}                       
                if($credit[2]=="rounded_adjustment"){
                    if($invoice_data->rounding_adjustment > 0){
                        $creditamount=$invoice_data->rounding_adjustment;
                    }

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

    function create_receivable_voucher($invoice_id, $receivable){
        //get invoice
        $this->db->select("invoice_date, customer_name, customer_id, id_program_invoices, program_enrolled_service_id, 
           program_invoices.program_enrollment_id,
            service_name as program_enrolled_services_name,
               paid_amount, paid_cash, paid_card, paid_check, advance_used, salestax, invoiced_amount, invoice_discount,
               rounding_adjustment, cc_charge, return_amount, invoice_other_charges, payment_mode, 
               program_invoices.business_id");
        $this->db->join("program_enrollment", "program_enrollment.id_program_enrollment = program_invoices.program_enrollment_id");
        $this->db->join("program_enrolled_services", "program_enrollment.id_program_enrollment = program_enrolled_services.program_enrollment_id and program_invoices.program_enrolled_service_id = program_enrolled_services.id_program_enrolled_services", 'LEFT');
        $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");
        $this->db->where("id_program_invoices", $invoice_id);
        $query =$this->db->get("program_invoices");
        //echo $query; exit();
        $invoice_data = $query->row();

        ///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' => $invoice_data->business_id,
            'description' => 'Service Sale Receivable Voucher for Enrollment ID ' . $invoice_data->program_enrollment_id . ', service '. $invoice_data->program_enrolled_services_name . ' on '. $invoice_data->invoice_date.', for '.$invoice_data->customer_name,
            'voucher_date' => date('Y-m-d H:i:s'),
            'voucher_amount' => $invoice_data->invoiced_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'=> 3,
            'payment_mode'=> '',
            'bank_name' => $bank_name,
            'program_invoice_id' => $invoice_id,
            'auto_voucher'=>'Yes',
            'sale_type'=>'Coaching',
            'program_enrolled_service_id' => $invoice_data->program_enrolled_service_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) + $invoice_data->salestax;}
            if($debit[2]=="sale_discount"){$debitamount = $invoice_data->invoice_discount;}
            $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 = ($invoice_data->invoiced_amount + $invoice_data->invoice_discount)-$invoice_data->invoice_other_charges ;}
            if($credit[2]=="sales_tax"){$creditamount = $invoice_data->salestax;}
            if($credit[2]=="other_charges"){$creditamount = $invoice_data->invoice_other_charges;}
            // if($credit[2]=="sale_discount"){$creditamount = $invoice_data->invoice_discount;}            

            $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 getting_groups_by_program(){
        $program_id = $this->input->post('id_program');
        $data['groups'] = $this->coaching_model->get_group_by_program($program_id);
        echo json_encode($data);
    } 

    function getting_members_by_group(){
         
        $group_id = $_POST['group_id'];
        $business_id = $this->session->userdata('businessid');
        
        $sql = "SELECT customers.id_customers , customers.customer_name FROM `customer_visits` 
            INNER join customers on  customers.id_customers = customer_visits.customer_id 
            where customer_visits.group_id =? and  customers.business_id =?
            GROUP by  customers.id_customers";
           $params = array($group_id,$business_id);
           $resp = $this->db->query($sql, $params);
           $data = $resp->result();
        echo json_encode($data);
        exit;     
    }



}
    
    

