<?php

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

class Service_controller extends CI_Controller {

    public function __construct() {

        parent::__construct();

        // Your own constructor code

        $this->load->model('service_model');
        $this->load->model('product_model');
        $this->load->model('customer_model');
        $this->load->model('business_model');
        if ($this->session->userdata('role') == '') {

            redirect('logout');
        }
    }

   

    function getServicesCategories() {

        $data = $this->service_model->get_services_categories();
        $x=0;

        echo json_encode($data);
    }

    function getServicesTypes() {

        $data = $this->service_model->get_services_types();
        $x=0;

        echo json_encode($data);
    }

    function getServicesByCategory() {

        $id_service_category = htmlentities($this->input->post('id_service_category', TRUE));
        $flag =$this->input->post('flag');

        $data = $this->service_model->get_services_by_category($id_service_category, $flag);
        
        
//        $i = 0;
//        foreach ($data as $d) {
//            $data[$i]->service_rate = number_format($d->service_rate);
//            $i++;
//        }
        echo json_encode($data);
    }

   

    public function services() {

        //get the posted values
        $data = $this->service_model->get_services();
        $data['business']=$this->business_model->getbusinessdetails();
        echo(json_encode($data));
    }

    public function set_service_categories($idservice_type) {
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'my_business';
            $data['subnav'] = 'servicetypes';

            if ($idservice_type && $idservice_type != "") {
                $data['idservice_type'] = $idservice_type;
                $data['service_type'] = $this->service_model->get_service_type_byid($idservice_type);
                $data['service_types'] = $this->service_model->getservice_type();
                $data['servicecategories'] = $this->service_model->getcategories_by_servicetype($idservice_type);
            } else {
                $data['servicecategories'] = $this->service_model->getservice_categories();
            }


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

            $this->load->view('setting/servicecategories_view');

            $this->load->view('includes/footer');
        }
    }

    public function delete_category() {



        $result = $this->service_model->delete_category();

        echo('success|' . $result);
    }

    public function update_category() {



        $result = $this->service_model->update_category();

        echo('success|' . $result);
    }

    public function add_category() {



        $result = $this->service_model->add_category();

        echo('success|' . $result);
    }

    public function set_services($id_service_category) {
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'my_business';
            $data['subnav'] = 'servicetypes';

            //$scid = $this->input->post('id_service_category', TRUE);
            $scid = $id_service_category;

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

            $data['services'] = $this->service_model->get_all_services($scid);

            $data['service_category'] = $this->service_model->get_category_byid($scid);

            $data['productsbrand'] = $this->product_model->get_all_brands('yes');

            //$data['products'] = $this->product_model->get_product_list();

            //$data['services_products'] = $this->product_model->get_services_products();

            $data['servicedepartments'] = $this->service_model->getservice_dept();
            $data['businesses'] = $this->business_model->get_all_businesses();
            
            $data['category'] = $this->service_model->get_list_category();
            
            $this->load->view('includes/header', $data);
            $this->load->view('setting/services_view');
            $this->load->view('includes/footer');
        }
    }

    public function add_service() {



        $result = $this->service_model->add_service();

        echo('success|' . $result);
    }

    public function update_service() {



        $result = $this->service_model->update_service();

        echo('success|' . $result);
    }

    public function delete_service() {



        $result = $this->service_model->delete_service();

        echo('success|' . $result);
    }

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

            $data['nav'] = 'my_business';
            $data['subnav'] = 'servicelist';

            $data['services'] = $this->service_model->get_service_list();

            $data['productsbrand'] = $this->product_model->get_all_brands('yes');

            //$data['products'] = $this->product_model->get_product_list();

            //$data['services_products'] = $this->product_model->get_services_products();

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

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

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

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

            $data['nav'] = 'my_business';
            $data['subnav'] = 'servicetypes';

            $data['servicetype'] = $this->service_model->getservice_type();

            $data['servicedepartments'] = $this->service_model->getservice_dept();
            
            $this->load->view('includes/header', $data);
            $this->load->view('setting/service_type_view');
            $this->load->view('includes/footer');
        }
    }

    public function add_service_type() {
        //exit();
        $result = $this->service_model->add_service_type();

        echo('success|' . $result);
    }

    public function update_service_type() {
        //exit();
        $result = $this->service_model->update_service_type();

        if($this->input->post('service_department')!=''){
            $sql="update business_services, service_category set business_services.service_department = '".$this->input->post('service_department')."' 
                where business_services.service_category_id = service_category.id_service_category  
                and service_type_id = " .$this->input->post('id_service_types')."; ";
            
            $query = $this->db->query($sql);
        }
        
        
        echo('success|' . $result);
    }

    public function service_type_image() {
        if ($this->input->post('id_service_type_image', TRUE) && $this->input->post('id_service_type_image', TRUE) != "") {
            $image = "";
            if ($_FILES['service_type_image']['name'] && $_FILES['service_type_image']['name'] != "") {
                $image = $this->image_upload('images/servicetype', 'service_type_image', 'gif|jpg|png');
                if ($image == FALSE) {
                    $this->session->set_flashdata('errorimage', 'The image dimension must be 128 X 128');
                    redirect(base_url('servicetypes'));
                } else {
                    $image = $image;
                }
            } else {
                $image = ($this->input->post('org_image', TRUE) != "" ? $this->input->post('org_image', TRUE) : NULL);
            }

            $result = $this->service_model->service_type_image($image);
            if ($result) {
                redirect(base_url('servicetypes'));
            }
        }
    }

    public function category_image() {
        if ($this->input->post('id_service_category_image', TRUE) && $this->input->post('id_service_category_image', TRUE) != "") {
            $image = "";
            if ($_FILES['service_category_image']['name'] && $_FILES['service_category_image']['name'] != "") {
                $image = $this->image_upload('images/category', 'service_category_image', 'gif|jpg|png');
                if ($image == FALSE) {
                    $this->session->set_flashdata('errorimage', 'The image dimension must be 128 X 128');
                    redirect(base_url('service_categories'));
                } else {
                    $image = $image;
                }
            } else {
                $image = ($this->input->post('org_image', TRUE) != "" ? $this->input->post('org_image', TRUE) : NULL);
            }

            $result = $this->service_model->category_image($image);
            if ($result) {
                redirect(base_url('service_categories' . '/' . $this->input->post('id_service_type_image', TRUE)));
            }
        }
    }

    function image_upload($folder = NULL, $image = NULL, $type = NULL, $width = NULL, $height = NULL, $encrypt = NULL) {
        $config['upload_path'] = 'assets/' . $folder . '/';
        $config['allowed_types'] = $type;
        $config['max_size'] = '2048';

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

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

        if (!$this->upload->do_upload($image)) {
            return FALSE;
        } else {
            return $this->upload->data('file_name');
        }
    }

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

            $data['nav'] = 'my_business';
            $data['subnav'] = 'facial_record_list';

            //$data['customers'] = $this->customer_model->get_customers();
            //$data['facial_records'] = $this->service_model->get_facial_records();


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

    public function get_facial_list_ajax(){
        $data['draw']= $this->input->post('draw');
        $data['$start'] = $this->input->post('start');
        $data['$length'] = $this->input->post('length');
        
        $data['customer']= $this->input->post('customer');
        $data['facial']= $this->input->post('facial');
        $data['exfoliant']= $this->input->post('exfoliant');
        $data['mask']= $this->input->post('mask');
        $data['cleanser']= $this->input->post('cleanser');
        $data['date']= $this->input->post('date');
        $data['remarks']= $this->input->post('remarks');
        
        
        $total= $this->service_model->get_countoffacials();        
        $data['data'] =$this->service_model->get_facial_list_ajax();
        
        $filtered=  sizeof($data['data']);
        
        $data['recordsTotal'] = $total;
        $data['recordsFiltered'] = $total;
        
        echo(json_encode($data));
        
        //$data['facial_records'] = 
        
    }

    function facial_record_add() {
        $result = $this->service_model->facial_record_add();
        echo('success|' . $result);
        die;
    }

    function facial_record_update() {
        $result = $this->service_model->facial_record_update();
        echo('success|' . $result);
        die;
    }

    public function order_function() {
        $id = $this->input->post('id');
        $orderid = $this->input->post('orderid');
        $type = $this->input->post('type');
        
        $result = $this->service_model->update_order_function($id, $orderid, $type);
        echo('success|' . $result);
        die;
    }
    
    public function edit_services(){
        $data['services'] = $this->service_model->edit_services();
        $data['services_products'] = $this->service_model->get_services_products_byid($this->input->post('id_business_services'));
        echo (json_encode($data));
        die;
    }
    
    public function edit_service_types(){
        $data = $this->service_model->edit_service_types();
        echo (json_encode($data));
        die;
    }
    
    public function edit_service_category(){
        $data = $this->service_model->edit_service_category();
        echo (json_encode($data));
        die;
    }
    
    public function edit_facial_record(){
        $data = $this->service_model->edit_facial_record();
        echo (json_encode($data));
        die;
    }
    public function get_package_types(){
        $data = $this->service_model->get_package_types();
        echo (json_encode($data));
        die;
        
    }
    public function get_package_category(){
        
        $ptype = $this->input->post('package_type_id');
        
        $data = $this->service_model->get_package_category($ptype);
        
        echo (json_encode($data));
        die;
        
    }
    public function get_loyaltyservices(){
        $data = $this->service_model->get_loyalty_serices($this->input->post('loyalty_points'));
        echo (json_encode($data));
        
    }
    public function search_loyaltyservices(){
        
        $data = $this->service_model->search_all_services($this->input->get('servicename'));
        echo (json_encode($data));
        
    }
    
    public function search_all_services(){
        
        $data = $this->service_model->search_all_services($this->input->get('servicename'));
        echo (json_encode($data));
        
    }
    
    public function getServiceProducts(){
        $serviceid = $this->input->post('serviceid');
        $data = $this->service_model->get_service_products($serviceid);
        echo (json_encode($data));
    }
    
    public function pricelist(){
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'reception';
            $data['subnav'] = 'pricelist';

            $data['service_types'] = $this->service_model->get_services_types();
            
            
            $data['business'] =  $this->business_model->getbusinessdetails();
            $taxes=$this->business_model->getbusinesstaxes('service','all');
            $ttax=0;
            foreach ($taxes as $tax){
                $ttax=$ttax+$tax['tax_percentage'];
            }

            $data['taxes']=$ttax;

            $x=0;


            $data['service_categories'] = $this->service_model->getservice_categories();
            $x=0;

            $data['services'] = $this->service_model->get_services();

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

    public function copy_to_branches(){

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

        ///select details of the service from headoffice
        $sql = "select * from business_services
        join service_category on service_category.id_service_category=business_services.service_category_id
        join service_type on service_type.id_service_types = service_category.service_type_id
        where id_business_services = ".$service_id;

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

        $servicedata = $query->row();


        //get all branches
        $business_id = null;
        if($this->input->post('business_id') != null){
            $business_id =  $this->input->post('business_id');
        }
        $sqlbranches = "select * from business where business.common_products = 'Yes' and business.ho='No' ";
        if($business_id != null){
            $sqlbranches .= " and id_business = ".$business_id.";";
        }

        $query1 = $this->db->query($sqlbranches);

        $branches = $query1->result();

        foreach($branches as $branch){
           // check if similar service exists in other branches
            $checkingsql = "select * from business_services 
            join service_category on service_category.id_service_category=business_services.service_category_id
            join service_type on service_type.id_service_types = service_category.service_type_id
            where business_services.business_id = ".$branch->id_business." and business_services.ref_number = ".$servicedata->id_business_services;
            $query2 = $this->db->query($checkingsql);
            $checkingresult = $query2->row();

            if($query2->num_rows()>0){
                //update

                $this->db->set('order_id', $servicedata->order_id);
                $this->db->set('service_name', $servicedata->service_name);
                $this->db->set('service_desc', $servicedata->service_desc);
                $this->db->set('service_rate', $servicedata->service_rate);
                $this->db->set('service_active', $servicedata->service_active);
                $this->db->set('commission_perc', $servicedata->commission_perc);
                $this->db->set('helper_perc', $servicedata->helper_perc);
                $this->db->set('service_color', $servicedata->service_color);
                $this->db->set('service_duration', $servicedata->service_duration);
                $this->db->set('max_per_day', $servicedata->max_per_day);
                $this->db->set('service_mode', $servicedata->service_mode);
                $this->db->set('service_department', $servicedata->service_department);
                $this->db->where('id_business_services', $checkingresult->id_business_services);
                $this->db->update('business_services');


                //manage the recipe as well
                //get all products attached
                $spsql = "select * from services_products where business_service_id = ".$servicedata->id_business_services;
                $querysp = $this->db->query($spsql);
                $spresult = $querysp->result_array();

                if($querysp->num_rows() > 0){
                    foreach($spresult as $product){
                        //check if this product is already linked to branches service
                        $sql="select * from services_products where business_service_id = ".$checkingresult->id_business_services. " and business_product_id = ".$product['business_product_id'];
                        $q = $this->db->query($sql);
                        $qresult = $q->row();

                        if($q->num_rows() > 0){
                            //if found update it
                            $this->db->where('id_services_products', $qresult->id_services_products);
                            $this->db->set('usage_qty', $product['usage_qty']);
                            $this->db->set('status', $product['status']);
                            $this->db->update('services_products');
                        } else {
                            //insert a new row
                            $pdata=array(
                                'business_service_id'=>$checkingresult->id_business_services,
                                'business_product_id'=>$product['business_product_id'],
                                'usage_qty'=>$product['usage_qty'],
                                'status'=>$product['status']
                            );
                            $this->db->insert('services_products', $pdata);
                        }
                    }
                }


                //check if 


                //echo json_encode($checkingresult);
                //exit();
            } else {
                //find matching category in the branch
                $sqlcategory = "select * from service_category where service_category.business_id = ".$branch->id_business." and service_category like '%".trim(substr($servicedata->service_category,0,8))."%';";
                $query3 = $this->db->query($sqlcategory);
                $categorydata = $query3->row();
                $category_id=0; $service_type_id=0;
                if($query3->num_rows()>0){
                    $category_id = $categorydata->id_service_category;
                }else{
                    //add type and category
                    $sqltype = "select * from service_type where service_type.business_id = ".$branch->id_business." and service_type like '%".$servicedata->service_type."%';";
                    $query4 = $this->db->query($sqltype);
                    $typedata = $query4->row();
                    if($query4->num_rows()>0){
                        $service_type_id = $typedata->id_service_types;
                    }else{
                        $data=array(
                            'business_id'=>$branch->id_business,
                            'order_id'=>0,
                            'service_type'=>$servicedata->service_type,
                            'service_type_image'=>$servicedata->service_type_image,
                            'service_type_active'=>$servicedata->service_type_active
                        );
                        $this->db->insert('service_type', $data);
                        $service_type_id=$this->db->insert_id();

                        $data=array(
                            'service_type_id'=>$service_type_id,
                            'business_id'=>$branch->id_business,
                            'order_id'=>0,
                            'service_category'=>$servicedata->service_category,
                            'service_category_image'=>$servicedata->service_category_image,
                            'service_category_active'=>$servicedata->service_category_active
                        );
                        $this->db->insert('service_category', $data);
                        $category_id=$this->db->insert_id();
                    }
                    
                }
                //insert new
                $data = array(
                    'service_category_id' => $category_id,
                    'business_id' => $branch->id_business,
                    'order_id' => $servicedata->order_id,
                    'service_name'  => $servicedata->service_name,
                    'service_desc'  => $servicedata->service_desc,
                    'created_date'  => date('Y-m-d H:i:s'),
                    'service_rate'  => $servicedata->service_rate,
                    'service_active'  => $servicedata->service_active,
                    'commission_perc'  => $servicedata->commission_perc,
                    'helper_perc'  => $servicedata->helper_perc,
                    'service_color'  => $servicedata->service_color,
                    'service_duration'  => $servicedata->service_duration,
                    'max_per_day'  => $servicedata->max_per_day,
                    'service_mode'  => $servicedata->service_mode,
                    'service_department'  => $servicedata->service_department,
                    'ref_number'  => $servicedata->id_business_services

                );
                $this->db->insert('business_services', $data);
                $newserviceid = $this->db->insert_id();

                ///insert the recepi
                $spsql = "select * from services_products where business_service_id = ".$servicedata->id_business_services;
                $querysp = $this->db->query($spsql);
                $spresult = $querysp->result_array();

                foreach($spresult as $product){
                    $pdata=array(
                        'business_service_id'=>$newserviceid,
                        'business_product_id'=>$product['business_product_id'],
                        'usage_qty'=>$product['usage_qty'],
                        'status'=>$product['status']
                    );
                    $this->db->insert('services_products', $pdata);
                }
                
            }

        }
        echo 'success|copied';
        exit();

    }


    public function copy_to_branch(){



    }

    public function compare_services(){
        $sql = "select id_business, business_name, business_address from business where business.common_products = 'Yes'";
        $query = $this->db->query($sql);
        $businesses = $query->result_array();


        $data['business'] = array();
        foreach($businesses as $business){

            $business['services'] = $this->service_model->compare_services($business['id_business']);             

            array_push($data['business'], array_merge($business));

        }
        // echo '<pre>';
        // print_r($data);
        // exit();

        $sql="select * from service_department";
        $query = $this->db->query($sql);
        $data['servicedepartments'] = $query->result_array();


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

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


}
