session = session(); $this->BikemodelsModel = new BikemodelsModel(); $this->BikemakeModel = new BikemakeModel(); $this->BusinessModel = new BusinessModel(); $this->JobcardModel = new JobcardModel(); $this->JobcardOSModel = new JobcardOSModel(); $this->BranchModel = new BranchModel(); $this->UsersModel = new UsersModel(); $this->JobcardComplaintModel = new JobcardComplaintModel(); $this->JobcardCustomComplaintModel = new JobcardCustomComplaintModel(); $this->JobcardServiceModel = new JobcardServiceModel(); $this->JobcardProductModel = new JobcardProductModel(); $this->JobcardSubServiceModel = new JobcardSubServiceModel(); $this->ProductModel = new ProductModel(); $this->ServiceModel = new ServicesModel(); $this->ClientModel = new ClientModel(); $this->ComplaintModel = new ComplaintModel(); $this->OutsourceModel = new OutsourceModel(); $this->VehicleModel = new VehicleModel(); $this->RoleModel = new RoleModel(); $this->JobcardFileModel = new JobcardFileModel(); } public function job_card_index() { $data['id'] = $this->session->get('logged_user'); $data['role'] = $this->session->get('logged_user_role'); $data['jobs'] = $this->JobcardModel->getJobCardsWithProductsAndService($this->session->get('logged_user_branch_id'), $data); $data['logged_user_role'] = $this->session->get('logged_user_role'); // echo "
";
        // print_r($data);die;
        return view('jobs_list',$data);
    }


    public function getJobCardData($job_card_id)
    {
        $data['vehicle'] = $this->JobcardModel->get_jobcard_vehicle_details($job_card_id);
        $bus_id = $this->session->get('logged_user_business_id');
        $data['job_card'] = $this->JobcardModel->where('job_card_id',$job_card_id)->findAll();
        $data['company_address'] = $this->BranchModel->where('branch_id', $this->session->get('logged_user_branch_id'))->where('business_id', $bus_id)->where('isactive', 1)->findAll();
        $productdata = $this->JobcardModel->get_jobcard_products_details($job_card_id);
        $data['service'] = $this->JobcardModel->get_jobcard_service($job_card_id);
        $data['sub_service'] = $this->JobcardModel->get_jobcard_sub_service($job_card_id);
        $data['complaint'] = $this->JobcardModel->get_jobcard_complaint($job_card_id);
        $data['customcomplaint'] = $this->JobcardModel->get_jobcard_custom_complaint($job_card_id);
        $data['osdata'] = $this->JobcardModel->get_jobcard_os($job_card_id);
        $labourcost = array_merge($data['service'],$data['sub_service'],$data['complaint'],$data['customcomplaint'],$data['osdata']);

        /** CALCULATE LABOURCOST WITH TAX */
        $totalAmount = 0;
        $totalTax = 0;
        $hsn_sac = 0;

        // Calculate total amount and total tax
        foreach ($labourcost as $product) {
            $totalAmount += $product["labour_amount"];
            $totalTax = $product["tax"];
        }
        // Calculate total
        $total = $totalAmount + $totalTax;

        $discount = ($data['job_card'][0]['is_rework'] == 1) ? 0 : $data['job_card'][0]['discount'] ;
        $amt_with_tax = $totalAmount + ($totalAmount * $totalTax / 100);
        $totalAmount = ($amt_with_tax - (float)$discount) / (1 + ($totalTax/100));
        // Create single output array
        $labour_data[0] = [
            "name" => "Labour Cost",
            "product_name" => "Labour Cost",
            "qty" => '-',
            "per" => '-',
            "tax" => $totalTax,
            "amount" => $totalAmount,
            "custom_tax" => $totalTax,
            "custom_total" => $total
        ];
        $data['job_card_products'] = array_merge($productdata, $labour_data);

        $data['sum_of_tax'] = 0;
        $data['sum_of_sub_total'] = 0;
        $data['sum_of_total'] = 0;

        foreach ($data['job_card_products'] as $key=> $value) {
            $qty = $value['qty'] == '-' ? 1 : $value['qty']; 
            $amount = $value['amount']  * $qty;
            $tax = ($amount * $value['tax'] / 100);
            $total = $amount + $tax;

            //asign values to same array
            $data['job_card_products'][$key]['tax_amount'] = $tax;
            $data['job_card_products'][$key]['total_amount'] = $total;
            $data['job_card_products'][$key]['taxable_value'] = $amount;
            $data['job_card_products'][$key]['hsn_sac'] = $hsn_sac;

            //calculate sum
            $data['sum_of_tax'] += $tax;
            $data['sum_of_sub_total'] += $amount;
            $data['sum_of_total'] += $total;
            
        }
        
        // dd($data);
        return $data;
    }

    

    public function preview_jobcard_invoice($job_card_id)   
    {
        
        try {
            
            $data = $this->getJobCardData($job_card_id);
            
            $html = view('invoice_pdf_template_jobcard', $data);

            return $this->respond(['status' => 'success','code' => 200,'data' => $html],200);
            
        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed','code' => 500,'data' => $e],500);
       }
    }

    public function download_jobcard_invoice($job_card_id)
    {

        $data = $this->getJobCardData($job_card_id);
            
        // Create an mPDF object
        $mpdf = new Mpdf([
			'mode' => '',
			'format' => 'A4',
			'default_font_size' => 0,
			'default_font' => '',
			// 'margin_right' => 1,
			'margin_top' => 6,
			'margin_bottom' => 6,
			'margin_header' => 6,
			'margin_footer' =>-30,
			'orientation' => 'P',
		]);

       

        $mpdf->autoLangToFont = true; 
        $mpdf->autoScriptToLang = true;
        $mpdf->SetTitle('Invoice');
        $html = view('invoice_pdf_template_jobcard', $data);
       
        $mpdf->WriteHTML($html);

        // Output the PDF to the browser for download
        $mpdf->Output( $data['job_card'][0]['order_number'] .'_'. date('Y-m-d H-i-s') . '.pdf', 'D');

    }

    public function preview_jobcard($job_card_id)
    {
     try {
        
        $data = $this->getJobCardData($job_card_id);

        $html = view('jobcard_pdf_template', $data); 

        return $this->respond(['status' => 'success','code' => 200,'data' => $html],200);

        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed','code' => 500,'data' => $e],500);
       }
    }

    public function download_jobcard_files($job_card_id)
    {
     try {
        
        $data = $this->JobcardFileModel->where(['job_card_id'=>$job_card_id,'isactive'=>1])->findAll();

        return $this->respond(['status' => 'success','code' => 200,'data' => $data],200);

        } catch (\Exception $e) {
            return $this->respond(['status' => 'failed','code' => 500,'data' => $e],500);
       }
    }

    public function download_jobcard($job_card_id)
    {
        $data = $this->getJobCardData($job_card_id);


        // Create an mPDF object
        $mpdf = new Mpdf([
			'mode' => '',
			'format' => 'A4',
			'default_font_size' => 0,
			'default_font' => '',
			// 'margin_right' => 1,
			'margin_top' => 6,
			'margin_bottom' => 6,
			'margin_header' => 6,
			'margin_footer' =>-30,
			'orientation' => 'P',
		]);

       

        $mpdf->autoLangToFont = true; 
        $mpdf->autoScriptToLang = true;
        $mpdf->SetTitle('Invoice');
        $html = view('jobcard_pdf_template', $data);
        $mpdf->WriteHTML($html);

        // Output the PDF to the browser for download
        $mpdf->Output('JC_' . date('Y-m-d H-i-s') . '.pdf', 'D');

    }

    public function download_os()
    {
       
        $outsource = $this->JobcardModel->download_os($this->session->get('logged_user_branch_id'));

        if (count($outsource) > 0) {
            
            foreach ($outsource as &$value) { 
                $products = [];
                $product_ids = !empty(json_decode($value['product_id'], true)) ? json_decode($value['product_id'], true) : [0]; 
                $product = $this->JobcardProductModel->select('job_card_product.job_card_product_id,job_card_product.product_id,job_card_product.qty,products.product_name as pname')
                    ->join('products', 'products.product_id = job_card_product.product_id')
                    ->whereIn('job_card_product.job_card_product_id', $product_ids)->find();
    
                    foreach ($product as $pr_value) {
                        array_push($products,$pr_value);
                    }
                    $value['products'] = $products;
            }
    
            $groupedJobs = [];
    
            // Iterate over each job
            foreach ($outsource as $job) {
                $jobCardId = $job['job_card_id'];
                
                // Check if the job_card_id already exists in $groupedJobs
                if (!isset($groupedJobs[$jobCardId])) {
                    // If not, initialize an array for that job_card_id with all details except 'name'
                    $groupedJobs[$jobCardId] = $job;
                    // Remove the 'name' key and initialize 'names' array
                    unset($groupedJobs[$jobCardId]['name']);
                    $groupedJobs[$jobCardId]['names'] = [];
                }
                // Add the name to the 'names' array
                $groupedJobs[$jobCardId]['names'][] = $job['name'];
            }
    
            usort($groupedJobs, function($a, $b) {
                return strtotime($a['delivery_date']) - strtotime($b['delivery_date']);
            });
    
    
            $data['outsource'] = $groupedJobs;
    
            // Create an mPDF object
            $mpdf = new Mpdf([
                'mode' => '',
                'format' => 'A5',
                'default_font_size' => 0,
                'default_font' => '',
                
                // 'margin_right' => 1,
                'margin_top' => 6,
                'margin_bottom' => 6,
                'margin_header' => 6,
                'margin_footer' =>-30,
                'orientation' => 'P',
            ]);
    
           
            $mpdf->autoLangToFont = true; 
            $mpdf->autoScriptToLang = true;
            // Set PDF properties 
            $mpdf->SetTitle('Invoice');
            // $mpdf->SetAuthor($data[0]->branch_name);
            $mpdf->SetCreator('');
    
            // echo "
";
            // print_r($data);die;
            // Generate the PDF content (HTML) with data
            $html = view('outsourcing_template', $data);
            // echo $html;die;
            // Load HTML into the mPDF instance
            $mpdf->WriteHTML($html);
    
            // Output the PDF to the browser for download
            $mpdf->Output('OS_' . date('Y-m-d H-i-s') . '.pdf', 'D');

        }else{
            return redirect()->with('download_os', 'No Out Source')->back();
        }
    }

    public function individual_download_os($job_card_id){
        $outsource = $this->JobcardOSModel->individual_download_os($job_card_id);

        if (count($outsource) > 0) {
            
            foreach ($outsource as &$value) { 
                $products = [];
                $product_ids = !empty(json_decode($value['product_id'], true)) ? json_decode($value['product_id'], true) : [0]; 
                $product = $this->JobcardProductModel->select('job_card_product.job_card_product_id,job_card_product.product_id,job_card_product.qty,products.product_name as pname')
                    ->join('products', 'products.product_id = job_card_product.product_id')
                    ->whereIn('job_card_product.job_card_product_id', $product_ids)->find();
    
                    foreach ($product as $pr_value) {
                        array_push($products,$pr_value);
                    }
                    $value['products'] = $products;
            }
    
            $groupedJobs = [];
    
            // Iterate over each job
            foreach ($outsource as $job) {
                $jobCardId = $job['job_card_id'];
                
                // Check if the job_card_id already exists in $groupedJobs
                if (!isset($groupedJobs[$jobCardId])) {
                    // If not, initialize an array for that job_card_id with all details except 'name'
                    $groupedJobs[$jobCardId] = $job;
                    // Remove the 'name' key and initialize 'names' array
                    unset($groupedJobs[$jobCardId]['name']);
                    $groupedJobs[$jobCardId]['names'] = [];
                }
                // Add the name to the 'names' array
                $groupedJobs[$jobCardId]['names'][] = $job['name'];
            }
    
            usort($groupedJobs, function($a, $b) {
                return strtotime($a['delivery_date']) - strtotime($b['delivery_date']);
            });
    
    
            $data['outsource'] = $groupedJobs;
    
            // Create an mPDF object
            $mpdf = new Mpdf([
                'mode' => '',
                'format' => 'A5',
                'default_font_size' => 0,
                'default_font' => '',
                
                // 'margin_right' => 1,
                'margin_top' => 6,
                'margin_bottom' => 6,
                'margin_header' => 6,
                'margin_footer' =>-30,
                'orientation' => 'P',
            ]);
    
           
            $mpdf->autoLangToFont = true; 
            $mpdf->autoScriptToLang = true;
            // Set PDF properties 
            $mpdf->SetTitle('Invoice');
            // $mpdf->SetAuthor($data[0]->branch_name);
            $mpdf->SetCreator('');
    
            // echo "
";
            // print_r($data);die;
            // Generate the PDF content (HTML) with data
            $html = view('outsourcing_template', $data);
            // echo $html;die;
            // Load HTML into the mPDF instance
            $mpdf->WriteHTML($html);
    
            // Output the PDF to the browser for download
            $mpdf->Output('OS_' . date('Y-m-d H-i-s') . '.pdf', 'D');

        }else{
            return redirect()->with('msg', 'failed')->back();
        }
    }

           
    public function new_jobcard($job_card_id,$rework = null)
    {
        if ($job_card_id === '0') {

            $data['page_name']="Create Job Card";
            $data['jobs'] = [];  
            $data['jobcardfiles'] = [];  
           
            $client = $this->ClientModel
                            ->where('isactive',1)
                            ->where('branch_id',$this->session->get('logged_user_branch_id'))->findAll();

           
            $vehicle = $this->VehicleModel->getCustomerandVehicle($this->session->get('logged_user_branch_id'));
            
            $product = $this->ProductModel->select('products.*, manufacturer.manufacturer_name')
                                ->join('manufacturer', 'products.manufacturer_id = manufacturer.manufacturer_id','left')
                                ->where('products.isactive',1)
                                ->where('products.branch_id',$this->session->get('logged_user_branch_id'))
                                ->findAll();
            
            // echo $this->session->get('logged_user_branch_id');die;
            $service = $this->ServiceModel->where('isactive',1)->where('branch_id',$this->session->get('logged_user_branch_id'))->findAll();
            // echo json_encode($service);die;
           
           
            $complaint = $this->ComplaintModel->where('isactive',1)->findAll();

           
            $os_data = $this->OutsourceModel->where('is_active',1)->findAll();

            $data['complaint']= $complaint;   
            $data['product_1']=$product;   
            $data['product']="";   
            $data['service_1']=$service;   
            $data['service']=""; 
            $data['os_data']=$os_data;  
            $data['client']=$client;  
            $data['vehicle']=$vehicle; 
            $data['logged_user_role'] = $this->session->get('logged_user_role');

        } else if ($job_card_id !== '0') {
            // echo json_encode($this->session->get('logged_user_role'));die;
        
            
          
         
            
            $type = $this->JobcardModel->select('job_card.type')
                               ->where('job_card.job_card_id', $job_card_id)
                               ->get()->getRow()->type;
            /***  SERVICE DATA ***/
            $servicedata = $this->JobcardModel->service_data($job_card_id, $this->session->get('logged_user_branch_id'));
            // Using '&' to reference the original array element

            foreach ($servicedata as &$value) { 
                //  sub product datas
                $product_ids = !empty(json_decode($value['product_id'], true)) ? json_decode($value['product_id'], true) : [0]; 

                $product = $this->JobcardProductModel->select('job_card_product.* , products.product_name as pname, products.qty_stock, manufacturer.manufacturer_name')
                                                ->join('products', 'products.product_id = job_card_product.product_id')
                                                ->join('manufacturer', 'manufacturer.manufacturer_id = products.manufacturer_id','left')
                                                ->whereIn('job_card_product.job_card_product_id', $product_ids)->findAll();
                $value['product'] = $product;

                // sub service data
                $service_ids = !empty(json_decode($value['sub_service_id'], true)) ? json_decode($value['sub_service_id'], true) : [0]; 
                $service = $this->JobcardSubServiceModel->select('job_card_sub_service.* , services.service_name as s_name')
                    ->join('services', 'services.service_id = job_card_sub_service.sub_service_id')
                    ->whereIn('job_card_sub_service.job_card_sub_service_id', $service_ids)->findAll();
                $value['sub_service'] = $service;
            }
            // echo "
";
            // print_r($value);die;
            $data['editservicedata'] = $servicedata;
            /*** COMPLAINT DATA ***/
            $complaintdata = $this->JobcardModel->complaint_data($job_card_id, $this->session->get('logged_user_branch_id'));
            // Using '&' to reference the original array element
            foreach ($complaintdata as &$value) { 
                $product_ids = !empty(json_decode($value['product_id'], true)) ? json_decode($value['product_id'], true) : [0]; 
                $product = $this->JobcardProductModel->select('job_card_product.* , products.product_name as pname, products.qty_stock,manufacturer.manufacturer_name')
                                            ->join('products', 'products.product_id = job_card_product.product_id')
                                            ->join('manufacturer', 'manufacturer.manufacturer_id = products.manufacturer_id','left')
                                            ->whereIn('job_card_product_id', $product_ids)
                                            ->findAll();
                $value['product'] = $product;
            }
            $data['editcomplaintdata'] = $complaintdata;

            /*** CUSTOM COMPLAINT DATA ***/
            $ccomplaintdata = $this->JobcardModel->ccomplaint_data($job_card_id, $this->session->get('logged_user_branch_id'));
            // Using '&' to reference the original array element
            foreach ($ccomplaintdata as &$value) { 
                $product_ids = !empty(json_decode($value['product_id'], true)) ? json_decode($value['product_id'], true) : [0]; 
                $product = $this->JobcardProductModel->select('job_card_product.* , products.product_name as pname, products.qty_stock, manufacturer.manufacturer_name')
                                            ->join('products', 'products.product_id = job_card_product.product_id')
                                            ->join('manufacturer', 'manufacturer.manufacturer_id = products.manufacturer_id','left')
                                            ->whereIn('job_card_product_id', $product_ids)
                                            ->findAll();
                $value['product'] = $product;
            }
            $data['editccomplaintdata'] = $ccomplaintdata;

            /*** OUTSOURCING DATA ***/
            $os_data = $this->JobcardModel->os_data($job_card_id, $this->session->get('logged_user_branch_id'));
            // Using '&' to reference the original array element
            foreach ($os_data as &$value) { 
                $product_ids = !empty(json_decode($value['product_id'], true)) ? json_decode($value['product_id'], true) : [0]; 
                $product = $this->JobcardProductModel->select('job_card_product.* , products.product_name as pname, products.qty_stock, manufacturer.manufacturer_name')
                                                ->join('products', 'products.product_id = job_card_product.product_id')
                                                ->join('manufacturer', 'manufacturer.manufacturer_id = products.manufacturer_id','left')
                                                ->whereIn('job_card_product_id', $product_ids)
                                                ->findAll();
                $value['product'] = $product;
            }
            $data['editosdata'] = $os_data;

            // $complaint = $this->ComplaintModel->where('isactive',1)->findAll();

            // $data['complaint']= $complaint; 
            $data['os_data'] = $this->OutsourceModel->where('is_active',1)->findAll();
            
            $data['page_name']="Edit Job Card";
            
            $client = $this->ClientModel->where('isactive',1)->where('branch_id',$this->session->get('logged_user_branch_id'))->findAll();
            
            
            $jobs = $this->JobcardModel->where('job_card_id', $job_card_id)->get()->getRowArray();
            $data['jobs']=$jobs;
            $jobcardfiles = $this->JobcardFileModel->where(['job_card_id'=>$job_card_id,'isactive'=>1])->findAll();
            $data['jobcardfiles'] = $jobcardfiles;  
           
            
            $vehicles = $this->VehicleModel->where('isactive',1)->where('vehicle_id',$jobs['vehicle_id'])
                                    ->where('branch_id',$this->session->get('logged_user_branch_id'))
                                    ->first();
            // print_r($jobs['vehicle_id']);die;
            $makeId = $vehicles['make'];
            $modelId = $vehicles['model'];

            $ccId = $this->BikemodelsModel->where('model_id',$modelId)->get()->getRow()->cubic_capacity_id;
            
            // $complaint = $this->ComplaintModel->where('cubic_capacity_id',$ccId)->where('isactive',1)->findAll();
            $complaint = $this->ComplaintModel->where('isactive',1)->findAll();
            
            $data['complaint']= $complaint; 

            $make_name = $this->BikemakeModel->where('make_id',$makeId)->select('make')->first();
            $model_name = $this->BikemodelsModel->where('model_id',$modelId)->select('model_name')->first();
            $data['make_model'] = $make_name['make'].' ' . $model_name['model_name'];
            // Encode the modelId before searching
            // $encodedModelId = json_encode([$makeId]);
            // $encoded_make_id = json_encode(['0']);
            // $product1 = $this->ProductModel->select('products.* , manufacturer.manufacturer_name')
            //                 ->where('JSON_CONTAINS(make_id, \'' . $encodedModelId . '\')', null, false)
            //                 ->join('manufacturer', 'manufacturer.manufacturer_id = products.manufacturer_id')
            //                 ->where('qty_stock >',0)
            //                 ->findAll();
            // $product2 = $this->ProductModel->select('products.* , manufacturer.manufacturer_name')
            //                 ->orWhere('JSON_CONTAINS(make_id, \'' . $encoded_make_id . '\')', null, false)
            //                 ->join('manufacturer', 'manufacturer.manufacturer_id = products.manufacturer_id')
            //                 ->where('qty_stock >',0)
            //                 ->findAll();
            // $product = array_merge($product1, $product2);
            // $data['product']=$product;
            $encodedCCId = json_encode([(string)$ccId]);
            $product = $this->ProductModel
            ->select('products.*, manufacturer.manufacturer_name')
            ->join('manufacturer', 'manufacturer.manufacturer_id = products.manufacturer_id', 'left')
            ->where('products.isactive', 1)
            ->where('qty_stock >',0)
            ->where('JSON_VALID(products.cubic_centimeter_id) > 0', null, false)
            ->where("JSON_CONTAINS(products.cubic_centimeter_id, '{$encodedCCId}')", null, false)
            ->findAll();
            $data['product']=$product;

            $encodedMakeId = json_encode([$makeId]);
            // $service1 = $this->ServiceModel->where('cubic_capacity_id', $ccId)
            //                         ->orWhere('category', 0)
            //                         ->findAll();

                $encodedMakeId1 = 0;
                $encodedModelId1 = 0;

                $selectServiceString = ($type == "General") ? "services.wg_price,services.wg_labour_cost as labour_cost" : "services.wog_price,services.wog_labour_cost as labour_cost"; 
                
                // Query the database to find the service - cubic_capacity_id .. category 1 na standlone and ccId must
                $service1 = $this->ServiceModel->select('services.service_id,services.branch_id,services.cubic_capacity_id,services.service_name,services.category,services.tax,services.cgst,services.sgst,services.description, services.product_id,services.sub_service_id,services.created_at,services.created_by,services.updated_at,services.updated_by,services.isactive,cubic_capacity.value')            
                        ->select($selectServiceString)
                        ->join('cubic_capacity', 'cubic_capacity.id = services.cubic_capacity_id','left')
                        ->where('cubic_capacity_id', $ccId)
                        ->where('category',1)
                        ->where('services.isactive' ,1)
                        ->findAll();


                // Query the database to find the service - default values .. category 0 na common and ccId no need
                $service2 = $this->ServiceModel->select('services.service_id,services.branch_id,services.cubic_capacity_id,services.service_name,services.category,services.tax,services.cgst,services.sgst,services.description, services.product_id,services.sub_service_id,services.created_at,services.created_by,services.updated_at,services.updated_by,services.isactive,cubic_capacity.value')            
                        ->select($selectServiceString)
                        ->join('cubic_capacity', 'cubic_capacity.id = services.cubic_capacity_id','left')
                        ->where('category',0)
                        ->where('services.isactive' ,1)
                        ->findAll();

                // final service
                $service = array_merge($service1, $service2);

            $data['product']=$product;
            $data['service_1']=$service;
            // echo "
";
            // print_r($service);die;
            $jobs_product= $this->JobcardCustomComplaintModel->where('job_card_id', $job_card_id)->findAll();
            $data['jobs_product']=$jobs_product;
            $jobs_service= $this->JobcardServiceModel->where('job_card_id', $job_card_id)->findAll();
            $data['jobs_service']=$jobs_service;
            $data['client']=$client; 
         
            $vehicle = $this->VehicleModel->where('isactive',1)->where('branch_id',$this->session->get('logged_user_branch_id'))->findAll();
            $data['vehicle']=$vehicle; 
            $data['logged_user_role'] = $this->session->get('logged_user_role');
            if($rework == 're-work') { $data['rework']= true; }

        //    dd($data);
                
          

        }

        
        $data['workers'] = $this->RoleModel->get_workers($this->session->get('logged_user_branch_id'));
        $data['job_card_id'] = $job_card_id;
       
        $data['makeData'] =$this->BikemakeModel->findAll();
        
        
      
        return view('job_card_form',$data);
    }

    
    public function add_jobs()
    {
        // $data = json_decode($_POST['products']);
        // $service_data = $data[0]->service;
        // dd($service_data);

        if($this->session->get('logged_user_role') == "Store Manager") {            
            $data['status'] = $this->request->getPost('status');
            $job_card_id = $this->request->getPost('job_card_id');
            $this->JobcardModel->update($job_card_id, $data); // issued status update
            $issued_product_id = $this->request->getPost('issued_items');
            $this->update_store_status($issued_product_id, $data['status']);
            return redirect()->to('job_card_index');
        }

       

        $this->delete_items($this->request->getPost('delete_items'));
        $rework = $this->request->getPost('rework');
        // Job card INSERT
      

        // Retrieve and validate the delivery date
        $deliveryDate = $this->request->getPost('delivery_date');

        $job_card_data = [
            'client_name' => $this->request->getPost('client_id'),
            'client_mobile_no' => $this->request->getPost('mobile_no'),
            'type' => $this->request->getPost('type'),
            'vehicle_id'=>$this->request->getPost('vehicle_id'),
            'branch_id'=> $this->session->get('logged_user_branch_id'),
            'billing_address' => $this->request->getPost('billing_address'),
            'billing_city' => $this->request->getPost('city'),
            'billing_state' => $this->request->getPost('state'),
            'billing_postal_code' => $this->request->getPost('postalcode'),
            'fuel_qty'=> $this->request->getPost('fuel_qty'),
            'meter'=> $this->request->getPost('meter'),
            'delivery_date' => !empty($deliveryDate) ? $deliveryDate : '0000-00-00',
            'note'=> $this->request->getPost('note'),
            'status'=> $this->request->getPost('status'),
            'assigned_to'=> json_encode($this->request->getPost('assigned_to')),
            'trial_mechanic'=> $this->request->getPost('trial_mechanic'),
            'subtotal'=> $this->request->getPost('sub_total'), 
            'tax'=> $this->request->getPost('invoicetax'), 
            'discount'=> $this->request->getPost('discount'), 
            'total'=> $this->request->getPost('grand_total'),
            'isactive' => 1
        ];
        $update_client_address = $this->request->getPost('update_client_address');
        if(isset($update_client_address) && $update_client_address == 'on')
        {
            ClientDetailsUpdate::updateClientAddress($this->request->getPost('vehicle_id'),$job_card_data); 
        }
        $status = $this->request->getPost('status'); 
        // Insert or update sales order
        $job_card_id = $this->request->getPost('job_card_id');
        if (!empty($job_card_id)) {
            if ($status === "Paid") {
                $job_card_data = [];
                $job_card_data['status'] = $status;
                $job_card_data['mode_of_payment'] = $this->request->getPost('mode_of_payment');
            }else if($status == 'Cancelled')
            {
                // echo $status;die;
                $job_card_data = [];
                $job_card_data['status'] = $status;
                $job_card_data['isactive'] = 0;
            }
            $this->JobcardModel->update($job_card_id, $job_card_data);
        } else {

            $job_card_data['inv_no'] = InvNoHelper::generateInvoiceNumber(); 
            $this->JobcardModel->insert($job_card_data);
            $job_card_id = $this->JobcardModel->getInsertID(); // Get the last inserted ID

            if(isset($rework)) {
                $job_card = $this->JobcardModel->find($rework);
                $this->JobcardModel->update($job_card_id, ['order_number' => $job_card['order_number'], 'is_rework' => 1 ]);
            } else {
                $orderNumber = 'JC-' . date('md') . '-' . str_pad($job_card_id, 5, '0', STR_PAD_LEFT);
                $this->JobcardModel->update($job_card_id, ['order_number' => $orderNumber]);
            }
           
        }
                                                            
        /********** INSERT SERVICE DATA ************/
        $data = json_decode($_POST['products']);
        $service_data = $data[0]->service;

        foreach ($service_data as $item) {
            // Insert into the service table
            $service['job_card_id'] = $job_card_id;
            $service['service_id'] = $item->service_id;
            $service['qty'] = $item->quality;
            $service['tax'] = (int)$item->tax;
            $service['labour_cost'] = $item->labour_cost; 
            $service['amount'] = $item->amount; 

            if(empty($item->id)) {
                $this->JobcardServiceModel->insert($service);
                $service_id = $this->JobcardServiceModel->getInsertID();
            }
            else {
                if($status == 'Cancelled')
                {
                    $service = [];
                    $service['isactive'] = 0;
                }
                $this->JobcardServiceModel->update($item->id, $service);
                $service_id = $item->id;
            }
            // do same as sub_service product_data_insertion
            if(isset($item->product)) { $this->product_data_insertion($job_card_id, $service_id, $this->JobcardServiceModel, $item, $this->JobcardProductModel, $status, $rework); }
            if(isset($item->sub_service)) { $this->sub_service_data_insertion($job_card_id, $service_id, $this->JobcardServiceModel, $item, $this->JobcardSubServiceModel, $status, $rework); }
        }


        /********** INSERT COMPLAINT DATA ************/
        $complaint_data = $data[0]->complaint;

        foreach ($complaint_data as $item) {
            // Insert into the service table
            $service['job_card_id'] = $job_card_id;
            $service['complaint_id'] = $item->complaint_id;
            $service['labour_cost'] = $item->amount;
            $service['qty'] = $item->quality;
            $service['tax'] = (int)$item->tax;
            $service['amount'] = $item->amount;
            if(empty($item->id)) {
                $this->JobcardComplaintModel->insert($service);
                $complaint_id = $this->JobcardComplaintModel->getInsertID();
            }
            else {
                if($status == 'Cancelled')
                {
                    $service = [];
                    $service['isactive'] = 0;
                }
                $this->JobcardComplaintModel->update($item->id, $service);
                $complaint_id = $item->id;
            }
        
            if(isset($item->product)) { $this->product_data_insertion($job_card_id, $complaint_id, $this->JobcardComplaintModel, $item, $this->JobcardProductModel, $status, $rework); }
        }

        /********** INSERT CUSTOM COMPLAINT DATA ************/
        $c_complaint_data = $data[0]->custom_complaint;

        foreach ($c_complaint_data as $item) {
            // Insert into the service table
            $service['job_card_id'] = $job_card_id;
            $service['complaint_name'] = $item->complaint_id;
            $service['labour_cost'] = $item->labour_cost;
            $service['qty'] = $item->quality;
            $service['tax'] = $item->tax;
            $service['amount'] = $item->amount;
            if(empty($item->id) || $item->id == "product") {
                $this->JobcardCustomComplaintModel->insert($service);
                $cc_complaint_id = $this->JobcardCustomComplaintModel->getInsertID();
            }
            else {
                if($status == 'Cancelled')
                {
                    $service = [];
                    $service['isactive'] = 0;
                }
                $this->JobcardCustomComplaintModel->update($item->id, $service);
                $cc_complaint_id = $item->id;
            }
        
            if(isset($item->product)) { $this->product_data_insertion($job_card_id, $cc_complaint_id, $this->JobcardCustomComplaintModel, $item, $this->JobcardProductModel, $status, $rework); }
        }

        /********** INSERT OUTSOURCE DATA ************/
        $os_data = $data[0]->os;

        foreach ($os_data as $item) {
            // Insert into the service table
            $service['job_card_id'] = $job_card_id;
            $service['os_id'] = $item->os_id;
            $service['labour_cost'] = $item->amount;
            $service['qty'] = $item->quality;
            $service['tax'] = $item->tax;
            $service['amount'] = $item->amount;
            if(empty($item->id)) {
                $this->JobcardOSModel->insert($service);
                $os_id = $this->JobcardOSModel->getInsertID();
            }
            else {
                if($status == 'Cancelled')
                {
                    $service = [];
                    $service['isactive'] = 0;
                }
                $this->JobcardOSModel->update($item->id, $service);
                $os_id = $item->id;
            }
        
            if(isset($item->product)) { $this->product_data_insertion($job_card_id, $os_id, $this->JobcardOSModel, $item, $this->JobcardProductModel, $status, $rework); }
        }

        // Get the files from the request
        $path = ROOTPATH.'public/uploads/jobcardfiles/';
        if(!is_dir($path)) { mkdir($path, 0777, true); }

        $filesdetails = $this->request->getFiles();
        $manualfilename = $this->request->getPost('manual_file_name'); // Get user-entered file names
        if(isset($filesdetails['file']))
        {
          foreach ($filesdetails['file'] as $index => $file) {
              if ($file->isValid() && !$file->hasMoved()) {
                  // Move the file to the desired directory
                  $filename = (!empty($file->getName())) ? $file->getName() : $manualfilename[$index] ;
                  $file->move($path, $filename);
                  // Store the file information in the database
                  $uploadFiles = array(
                      'manual_file_name' => $manualfilename[$index], 
                      'file_name' => $filename, 
                      'job_card_id' => $job_card_id,
                      'created_by' => $this->session->get('logged_user')
                  );
                  $lastInsertFileId = $this->uploadAdditionalFile($uploadFiles);
                  $this->logger->info("last Insert File Id  = ".$lastInsertFileId); 
                }
          }
        }
        return redirect()->to('job_card_index');
    }

    public function update_store_status($issued_product_id, $status)
    {
        if($status == 'Issued') {
    
            $product_data = json_decode($issued_product_id);
            foreach ($product_data as $key => $value) {
                $jc_product = $this->JobcardProductModel->where('job_card_product_id', $value->id)->findAll();
                if($jc_product[0]['status'] == 0)
                {
                    $data['issued_qty'] = $value->qty;
                    if($value->qty == $jc_product[0]['qty']) { $data['status'] = 1; }
                    $res = $this->JobcardProductModel->update($value->id, $data);
                    if($res)
                    {
                        $deduct_qty = $value->qty - $jc_product[0]['issued_qty'];
                        // $this->updateProductQuantity($this->ProductModel, $jc_product[0]['product_id'], $deduct_qty);
                    }
                }
            }
        }
    }

    public function product_data_insertion($job_card_id, $parent_id, $ParentModel, $item, $JobcardProductModel, $status, $rework)
    {
        // Insert into the product table
        $id = [];
        // echo "
";
        // print_r($item);die;
        foreach ($item->product as $pt) {
            $product['job_card_id'] =  $job_card_id;
            $product['product_id'] = $pt->p_id;
            if(isset($pt->name)){
                $product['name'] = $pt->name;
            }
            $product['qty'] = $pt->qty;
            $product['tax'] = $pt->tax;
            $product['amount'] = $pt->amount;
            // $product['amount'] = $pt->amount / $pt->qty; 
            //(isset($rework) ? 0 : $pt->amount / $pt->qty );
            if(empty($pt->id)) {
                $this->JobcardProductModel->insert($product);
                $job_card_product_id = $this->JobcardProductModel->getInsertID();
            }
            else {
                if($status == 'Cancelled')
                {
                    $product = [];
                    $product['job_card_id'] =  $job_card_id;
                    $product['product_id'] = $pt->p_id;
                    $product['is_active'] = 0;
                }
                $old_data = $this->JobcardProductModel->find($pt->id);
                if($pt->qty != $old_data['issued_qty'] && $pt->qty > $old_data['issued_qty']) { $product['status'] = 0; }
                // echo $pt->id;die;
                $this->JobcardProductModel->update($pt->id, $product);
                $job_card_product_id = $pt->id;
            }
            array_push($id, $job_card_product_id);
        }
        $res =$ParentModel->update($parent_id, ['product_id' => json_encode($id) ]);
        if($res) {
            $this->product_data_maintanence($id, $status);
        }
    }


    public function sub_service_data_insertion($job_card_id, $parent_id, $ParentModel, $item, $JobcardSubServiceModel, $status, $rework)
    {
        // Insert into the product table
        $id = [];
        foreach ($item->sub_service as $pt) {
            
            $product['job_card_id'] =  $job_card_id;
            $product['sub_service_id'] = $pt->s_id;
            if(isset($pt->name)){
                $product['name'] = $pt->name;
            }
            $product['qty'] = $pt->qty;
            $product['tax'] = $pt->tax;
            $product['amount'] = $pt->amount / $pt->qty; //(isset($rework) ? 0 : $pt->amount / $pt->qty );
            if(empty($pt->id)) {
                $this->JobcardSubServiceModel->insert($product);
                $job_card_sub_service_id = $this->JobcardSubServiceModel->getInsertID();
            }
            else {
                if($status == 'Cancelled')
                {
                    $product = [];
                    $product['job_card_id'] =  $job_card_id;
                    $product['sub_service_id'] = $pt->s_id;
                    $product['is_active'] = 0;
                }
                $old_data = $this->JobcardSubServiceModel->find($pt->id);
                if($pt->qty != $old_data['issued_qty'] && $pt->qty > $old_data['issued_qty']) { $product['status'] = 0; }
                // echo $pt->id;die;
                $this->JobcardSubServiceModel->update($pt->id, $product);
                $job_card_sub_service_id = $pt->id;
            }
            array_push($id, $job_card_sub_service_id);
        }

        // $job_card_service_id = $parent_id;
        // $res =$ParentModel->update($parent_id, ['sub_service_id' => json_encode($id) ]);
        $parent_data_get = $ParentModel->where('job_card_id', $job_card_id)->first();

        $job_card_service_id = $parent_data_get['job_card_service_id'];
        $res= $ParentModel->update($job_card_service_id, ['sub_service_id' => json_encode($id)]);
        if($res) {
                    // print_r($parent_id);
        // print_r($id);
        // die;
            // $this->product_data_maintanence($id, $status);
        }
    }

    


    public function delete_items($delArr)
    {

        
        $data = json_decode($delArr);

        $product_data = $data[0]->product;
        if(!empty($product_data)) {
            foreach ($product_data as $item) {
                $conditions = [ 'job_card_product_id' => $item ];
                $this->JobcardProductModel->where($conditions)->delete();
            }
        }

        $sub_service_data = $data[0]->sub_service;
        if(!empty($sub_service_data)) {
            foreach ($sub_service_data as $item) {
                $conditions = [ 'job_card_sub_service_id' => $item ];
                $this->JobcardSubServiceModel->where($conditions)->delete();
            }
        }

        $service_data = $data[0]->service;
        if(!empty($service_data)) {
            foreach ($service_data as $item) {
                $conditions = [ 'job_card_service_id' => $item ];
                $service_deleted_data = $this->JobcardServiceModel->where($conditions)->findAll();
                if(isset($service_deleted_data[0]['product_id']))
                $this->product_delete($service_deleted_data[0]['product_id']);
                $this->JobcardServiceModel->where($conditions)->delete();
            }
        }

        $complaint_data = $data[0]->complaint;
        if(!empty($complaint_data)) {
            foreach ($complaint_data as $item) {
                $conditions = [ 'job_card_complaint_id' => $item ];
                $complaint_deleted_data = $this->JobcardComplaintModel->where($conditions)->findAll();
                if(isset($complaint_deleted_data[0]['product_id']))
                $this->product_delete($complaint_deleted_data[0]['product_id']);
                $this->JobcardComplaintModel->where($conditions)->delete();
            }
        }

        $ccomplaint_data = $data[0]->custom_complaint;
        if(!empty($ccomplaint_data)) {
            foreach ($ccomplaint_data as $item) {
                $conditions = [ 'job_card_cc_id' => $item ];
                $cc_deleted_data = $this->JobcardCustomComplaintModel->where($conditions)->findAll();
                if(isset($cc_deleted_data[0]['product_id']))
                $this->product_delete($cc_deleted_data[0]['product_id']);
                $this->JobcardCustomComplaintModel->where($conditions)->delete();
            }
        }

        $os_data = $data[0]->os;
        if(!empty($os_data)) {
            foreach ($os_data as $item) {
                $conditions = [ 'job_card_os_id' => $item ];
                $os_deleted_data = $this->JobcardOSModel->where($conditions)->findAll();
                if(isset($os_deleted_data[0]['product_id']))
                $this->product_delete($os_deleted_data[0]['product_id']);
                $this->JobcardOSModel->where($conditions)->delete();
            }
        }
    }

    /** DELETE JOB CARD-PRODUCT */
    public function product_delete($product) {
        $product_ids = json_decode($product, true);
        if (empty($product_ids)) return true;
        foreach ($product_ids as $item) {
            $conditions = [ 'job_card_product_id' => $item ];
            $this->JobcardProductModel->where($conditions)->delete();
        }
        return true;
    }

    public function product_data_maintanence($id_array,$status)
    {
    

        foreach ($id_array as $key => $product_id) {
            $product = $this->JobcardProductModel->find($product_id);
            $qty = isset($product['issued_qty']) ? $product['issued_qty'] : 0;
            if ($status == 'Issued') {
                // $this->subractProductQuantity( $product['product_id'], $qty);
            }elseif ($status == 'Cancelled'){
                
                $this->subractProductQuantity( $product['product_id'], $qty);
                $data['status'] = 0;
                // echo $product['job_card_product_id'];die;
                // $this->JobcardProductModel->where('job_card_product_id',$product['job_card_product_id'])->update($data);
            }
                    
        }
    }

    private function addBackProductQuantity( $product_id, $sold_qty)
    {
        // Fetch current product quantity
        $product = $this->ProductModel->find($product_id);

        $data['qty_stock'] = $product['qty_stock'] + $sold_qty;

        if($product['per'] == 'barrel')
        {
            $data['barrel'] = $data['qty_stock'] /  $product['ltr_per_barrel'];
        }
        else if($product['per'] == 'box')
        {
           $data['box'] = $data['qty_stock'] /  $product['qty_per_box'];
        }

        // Update quantity in Product table
        $this->ProductModel->update($product_id, $data );
    }

    private function subractProductQuantity( $product_id, $sold_qty)
    {
       
        // Fetch current product quantity
        $product = $this->ProductModel->find($product_id);
        
        $data['qty_stock'] = $product['qty_stock'] - $sold_qty;

        if($product['per'] == 'barrel')
        {
            $data['barrel'] = $data['qty_stock'] /  $product['ltr_per_barrel'];
        }
        else if($product['per'] == 'box')
        {
           $data['box'] = $data['qty_stock'] /  $product['qty_per_box'];
        }
        
        // Update quantity in Product table
        $this->ProductModel->update($product_id, $data );
    }

   


    public function delete_jobcard($job_card_id)
    {
       
        $where = ['job_card_id' => $job_card_id, 'isactive' => 1]; // Assuming 'isactive' is a column in your database
        $existingProduct = $this->JobcardModel->where($where)->first();
    
        if ($existingProduct) {
            $data['isactive'] = 0;
            
            if ($this->JobcardModel->update($job_card_id, $data)) {
                session()->setFlashdata('success', 'Deleted successfully.');
                $this->logger->info("Job Card: has been Inactivated successfully. Inactivated ID = ".$job_card_id); 
            }
        }
    
       
        return redirect()->to('job_card_index');
    }
    
    
    public function save_vehicle(){
        // Load ClientModel
       
       if($this->request->getPost('formType') == 'create')
       {
     

         $client['client_name'] = $this->request->getPost('createclientName');
         $client['mobile_no'] = $this->request->getPost('createclientMobile');
         $client['client_type'] = $this->request->getPost('createclientType');
         $client['branch_id'] = $this->session->get('logged_user_branch_id');

         $client_id = $this->ClientModel->insert($client);

         if($client_id){

            $data = [
                'client_id' =>  $client_id,
                'mobile_no' => $this->request->getPost('createclientMobile'),
                'reg_no' => $this->request->getPost('reg_no'),
                'model' => $this->request->getPost('model'),
                'make' => $this->request->getPost('make'),
                'branch_id'=> $this->session->get('logged_user_branch_id'),
                'city'=>'Chennai',
                'state'=>'Tamil Nadu',
                'isactive' => 1
            ];

         }
        

       }else{

        $data = [
            'client_id' => $this->request->getPost('client_id'),
            'mobile_no' => $this->request->getPost('mobile_no'),
            'reg_no' => $this->request->getPost('reg_no'),
            'model' => $this->request->getPost('model'),
            'make' => $this->request->getPost('make'),
            'branch_id'=> $this->session->get('logged_user_branch_id'),
            'city'=>'Chennai',
            'state'=>'Tamil Nadu',
            'isactive' => 1
        ];


       }
    
       
       
      
        // Attempt to insert the client data
        $id = $this->VehicleModel->insert($data);
        if ($id) {
            $vehicleData  = $this->VehicleModel->where('vehicle_id',$id)->first();

            // If insertion succeeds, return success response
            return $this->response->setJSON(['success' => true, 'message' => 'Client saved successfully.','vehicleData'=>$vehicleData]);
        } else {
            // If insertion fails, return error response
            return $this->response->setJSON(['success' => false, 'message' => 'Failed to save client.']);
        }
    }

    public function get_vehicle_products(){
    
    }


    public function getComplaints(){    
        $modelId = $this->request->getPost('model_id');
        $ccId = $this->BikemodelsModel->where('model_id',$modelId)->get()->getRow()->cubic_capacity_id;
        $modelName = $this->BikemodelsModel->where('model_id',$modelId)->get()->getRow()->model_name;

        // $complaint = $this->ComplaintModel->where('cubic_capacity_id',$ccId)
        $complaint = $this->ComplaintModel->select('complaints.*,cubic_capacity.value')            
                                    ->join('cubic_capacity', 'cubic_capacity.id = complaints.cubic_capacity_id','left')
                                    ->where('complaints.isactive',1)->findAll();

        if($complaint){
            // Send JSON response
            return $this->response->setJSON(['complaint'=>$complaint , 'modelName'=>$modelName ] );
        } else {
            // If service is not found, return an empty response or appropriate message
            return $this->response->setJSON(['complaint'=>[] , 'modelName'=>$modelName ]);
        }
    }

    public function getServices()
    {
        // Retrieve make_id and model_id from the request
        $makeId = $this->request->getPost('make_id');
        $modelId = $this->request->getPost('model_id');
        $type = $this->request->getPost('type');
        $selectServiceString = ($type == "General") ? "services.wg_price,services.wg_labour_cost as labour_cost" : "services.wog_price,services.wog_labour_cost as labour_cost"; 

        $ccId = $this->BikemodelsModel->where('model_id',$modelId)->get()->getRow()->cubic_capacity_id;

        // Query the database to find the service - cubic_capacity_id .. category 1 na standlone and ccId must
        $service1 = $this->ServiceModel->select('services.service_id,services.branch_id,services.cubic_capacity_id,services.service_name,services.category,services.tax,services.cgst,services.sgst,services.description, services.product_id,services.sub_service_id,services.created_at,services.created_by,services.updated_at,services.updated_by,services.isactive,cubic_capacity.value')            
                        ->select($selectServiceString)
                        ->join('cubic_capacity', 'cubic_capacity.id = services.cubic_capacity_id','left')
                        ->where('cubic_capacity_id', $ccId)
                        ->where('category',1)
                        ->where('services.isactive' ,1)
                        ->findAll();


       // Query the database to find the service - default values .. category 0 na common and ccId no need
       $service2 = $this->ServiceModel->select('services.service_id,services.branch_id,services.cubic_capacity_id,services.service_name,services.category,services.tax,services.cgst,services.sgst,services.description, services.product_id,services.sub_service_id,services.created_at,services.created_by,services.updated_at,services.updated_by,services.isactive,cubic_capacity.value')            
                        ->select($selectServiceString)
                        ->join('cubic_capacity', 'cubic_capacity.id = services.cubic_capacity_id','left')
                        ->where('category',0)
                        ->where('services.isactive' ,1)
                        ->findAll();

        // final service
        $service = array_merge($service1, $service2);

        $modelName = $this->BikemodelsModel->where('model_id',$modelId)->get()->getRow()->model_name;
        $makeName = $this->BikemakeModel->where('make_id',$makeId)->get()->getRow()->make;

        if($service){
            // Send JSON response
            return $this->response->setJSON(['service'=>$service , 'modelName'=>$modelName ,'makeName'=>$makeName] );
        } else {
            // If service is not found, return an empty response or appropriate message
            return $this->response->setJSON(['service'=>[] , 'modelName'=>$modelName ,'makeName'=>$makeName]);
        }
    }

    public function getServicesOld()
    {
        // Retrieve make_id and model_id from the request
        $makeId = $this->request->getPost('make_id');
        $modelId = $this->request->getPost('model_id');

        // Encode the makeId before searching
        $encodedMakeId = json_encode([$makeId]); 

        // Encode the modelId before searching
        $encodedModelId = json_encode([$modelId]);

        // Load the ProductModel
       

        // Query the database to find the service based on make_id and model_id
        $service1 = $this->ServiceModel->where('makes_id LIKE \'%"' . $makeId . '"%\'', null, false)
                        ->where('models_id LIKE \'%"' . $modelId . '"%\'', null, false)
                        ->where('category',1)
                        ->where('isactive' ,1)
                        ->findAll();

        $encodedMakeId1 = 0;
        $encodedModelId1 =0;
    
        $common_services = $this->ServiceModel->where('makes_id LIKE \'%"' . $encodedMakeId1 . '"%\'', null, false)
                                        ->where('models_id LIKE \'%"' . $encodedModelId1 . '"%\'', null, false)
                                        ->where('category',1)
                                        ->where('isactive' ,1)
                                        ->findAll();

        $service2 = $this->ServiceModel->where('category',0)
                                 ->where('isactive' ,1)
                                 ->findAll();
        $service = array_merge($common_services, $service1, $service2);

        $modelName = $this->BikemodelsModel->where('model_id',$modelId)->get()->getRow()->model_name;
        $makeName = $this->BikemakeModel->where('make_id',$makeId)->get()->getRow()->make;

        if($service){
            // Send JSON response
            return $this->response->setJSON(['service'=>$service , 'modelName'=>$modelName ,'makeName'=>$makeName] );
        } else {
            // If service is not found, return an empty response or appropriate message
            return $this->response->setJSON(['service'=>[] , 'modelName'=>$modelName ,'makeName'=>$makeName]);
        }
    }
    // Check if service exists
	function uploadAdditionalFile($myfiles)
	{
        if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
      
        $id = $this->JobcardFileModel->insert($myfiles);
		$aff = $this->JobcardFileModel->affectedRows();
		return $aff > 0 ? $this->JobcardFileModel->insertID() : 0;
	}
    public function deleteJobCardFile()
    {
        $file_id = $this->request->getPost('file_id');
        
      
        $where = ['file_id' => $file_id, 'isactive' => 1 ];
        $existingFile = $this->JobcardFileModel->where($where)->first();
    
        
        if ($existingFile) {
            $data['isactive'] = 0;
            $data['updated_by'] = $this->session->has('logged_user');

            
            if ($this->JobcardFileModel->update($file_id, $data)) {
                // session()->setFlashdata('success', 'Deleted successfully.');
                return $this->response->setJSON(['success' => true, 'message' => 'File deleted successfully.','file_id'=>$file_id]);
                $this->logger->info("job card file : has been deleted successfully. Inactivated ID = ".$file_id); 
            }
            return $this->response->setJSON(['success' => false, 'message' => 'Failed to deleted.']);
        }
    }
    
  
}