db = \Config\Database::connect(); parent::__construct(); $this->coatingMachineDetails_model = new CoatingMachineDetailsModel(); $this->drierMachineDetails_model = new DrierMachineDetailsModel(); $this->factoryMachine_model = new FactoryMachineModel(); $this->factoryVehicleDieselDetails_model = new FactoryVehicleDieselDetailsModel(); $this->factoryVehicleDieselStockSummary_model = new FactoryVehicleDieselStockSummaryModel(); $this->rawmaterialdetails_model = new Rawmaterialdetails_model(); $this->incomingSilicaSandDetails_model = new IncomingSilicaSandDetailsModel(); $this->inwardGateRegister_model = new Inwardgateregister_model(); $this->bagStockDetails_model = new BagStockDetailsModel(); $this->dustAndRoughStockDetails_model = new DustAndRoughModel(); $this->resinStockDetails_model = new ResinStockModel() ; $this->session = session(); helper('form'); $this->isLoggedIn(); } public function index() { // } //Coating Machine Details starts public function loadView_coatingMachineDetails(){ if ($this->request->getMethod() === 'POST'){ $month = $this->request->getPost('month'); $date = DateTime::createFromFormat('M-Y', $month); $formattedDate = $date->format('Y-m'); $month=$formattedDate; } else{ $month = date('Y-m'); } $this->global['pageTitle'] = 'Coating Machine Details '; $data['coatingMachineDetails']= $this->coatingMachineDetails_model ->where('is_active', 1) ->orderBy('created_at','DESC') ->like('created_at', $month, 'after') ->findAll(); $date = DateTime::createFromFormat('Y-m', $month); $formattedDate = $date->format('M-Y'); $data['month']=$formattedDate; return $this->loadViews("CoatingMachineDetail", $this->global, $data, NULL); } public function addNewCoatingMachineDetails(){ $postData=$this->request->getPost(); $inserted= $this->coatingMachineDetails_model->insert($postData); if ($inserted) { // Set flashdata for success message return redirect()->to('/coatingMachineDetails')->with('success', 'Coating Machine details updated successfully'); } else { // Set flashdata for error message return redirect()->back()->with('error', 'Failed to update Coating machine details'); } } public function updateCoatingMachineDetails(){ $putData=$this->request->getPost(); $id = $putData['editCoatingMachineDetailId']; $updated= $this->coatingMachineDetails_model->update($id,$putData); if ($updated) { // Set flashdata for success message return redirect()->to('/coatingMachineDetails')->with('success', 'Coating Machine details updated successfully'); } else { // Set flashdata for error message return redirect()->back()->with('error', 'Failed to update Coating machine details'); } } public function deleteCoatingMachineDetails(){ $id = $this->request->getGet('id'); $data['is_active']=0; $updated = $this->coatingMachineDetails_model->update($id,$data); if ($updated) { // Set flashdata for success message return redirect()->to('/coatingMachineDetails')->with('success', 'Coating Machine details deleted successfully'); } else { // Set flashdata for error message return redirect()->back()->with('error', 'Failed to delete Coating machine details'); } } //incoming Silica Sand Details starts public function loadView_incomingSilicaSandDetails(){ if ($this->request->getMethod() === 'POST'){ $month = $this->request->getPost('month'); $date = DateTime::createFromFormat('M-Y', $month); $formattedDate = $date->format('Y-m'); $month=$formattedDate; } else{ $month = date('Y-m'); } $data['month']=$month; $this->global['pageTitle']='Incoming Silica Sand Details'; $materialCodes = $this->rawmaterialdetails_model->getAllSilicaRawMaterialCode(); if (!empty($materialCodes)) { $data['igrDetails'] = $this->inwardGateRegister_model->findIgrDetailsForIncomingSilicaSand($materialCodes,$month); } else { $data['igrDetails'] = []; } $date = DateTime::createFromFormat('Y-m', $month); $formattedDate = $date->format('M-Y'); $data['month']=$formattedDate; return $this->loadViews("incomingSilicaSandDetails", $this->global, $data, NULL); } public function updateIncomingSilicaSandDetails(){ $postData = $this->request->getPost(); $incomingSilicaSandDetailsData = json_decode($postData['incomingSilicaSandDetailsData'], true); foreach($incomingSilicaSandDetailsData as $data){ $IGRNO=$data['IGR No']; $materialCode=$data['MaterialCode']; $dbData=[ 'igrNo_fk'=>$data['IGR No'], 'materialCode'=>$data['MaterialCode'], 'grade'=>$data['Grade'], 'gradeCondition'=>$data['Grade Condition'], '_10'=>$data['___10___'], '_20'=>$data['___20___'], '_30'=>$data['___30___'], '_40'=>$data['___40___'], '_50'=>$data['___50___'], '_70'=>$data['___70___'], '_100'=>$data['___100___'], '_140'=>$data['___140___'], '_200'=>$data['___200___'], '_300'=>$data['___300___'], 'pan'=>$data['PAN'], 'total'=>$data['Total'], 'afsSpec'=>$data['AFS Spec'], 'afsActual'=>$data['AFS Actual'], 'plus20loss'=>$data['Plus 20 loss%'], 'plus30Loss'=>$data['Plus 30 Loss %'], 'moistureSpec'=>$data['Moisture % Spec'], 'moistureActual'=>$data['Moisture Actual'], 'moistureLoss'=>$data['Moisture Loss'], 'moistureLossQty'=>$data['Moisture loss Qty'], 'sieveLossQty'=>$data['Sieve Loss Qty'], 'salableQty'=>$data['Salable Qty'], 'remark'=>$data['Remark'] ]; $resultExists=$this->incomingSilicaSandDetails_model ->where('igrNo_fk',$IGRNO) ->where('materialCode',$materialCode) ->first(); if(!empty($resultExists)){ $updated = $this->incomingSilicaSandDetails_model ->where('igrNo_fk', $IGRNO) ->where('materialCode', $materialCode) ->set($dbData) ->update(); }else{ $inserted = $this->incomingSilicaSandDetails_model->insert($dbData); } } echo "Data Saved Successfully"; } // Bag Stock details starts public function loadView_bagStockDetails(){ if ($this->request->getMethod() === 'POST'){ $month = $this->request->getPost('month'); $date = DateTime::createFromFormat('M-Y', $month); $formattedDate = $date->format('Y-m'); $month=$formattedDate; } else{ $month = date('Y-m'); } $data=[]; $data['month']=$month; $this->global['pageTitle']='Bag Stock Details'; $previousMonth = DateTime::createFromFormat('Y-m', $month)->modify('-1 month')->format('Y-m'); $previousMonthStartDate = "$previousMonth-01"; $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); $data['previousMonthBagStockDetails'] = $this->bagStockDetails_model ->select(['materialCode', 'date' ,'balanceStock']) ->distinct() ->where('date =', $previousMonthEndDate) ->groupBy(['materialCode','date']) ->orderBy('date','desc') ->orderBy('materialCode','asc') ->findAll(); $startDate = "$month-01"; $endDate = date("Y-m-t", strtotime($startDate)); $data['bagStockDetails'] = $this->bagStockDetails_model ->where('date >=', $startDate) ->where('date <=', $endDate) ->groupBy(['materialCode','date']) ->orderBy('date','asc') ->orderBy('materialCode','asc') ->findAll(); // Initialize an empty array to hold the grouped data $data['groupedBagStockDetails'] = []; // Temporary array to store grouped data by date $groupedByDate = []; // Group by 'date' foreach ($data['bagStockDetails'] as $detail) { $date = $detail['date']; // Initialize the array for this date if it doesn't exist if (!isset($groupedByDate[$date])) { $groupedByDate[$date] = []; } // Append the detail to the sub-array for this date $groupedByDate[$date][] = $detail; } // Reset the structure to have indexed arrays without the date keys $data['groupedBagStockDetails'] = array_values($groupedByDate); $bagMaterials= $this->rawmaterialdetails_model->getAllBagMaterialCode(); foreach($bagMaterials as $key => $bagMaterial){ $materialCode = $bagMaterial['MaterialCode']; $bagMaterials[$key]['customers'] = $this->bagStockDetails_model ->select('customer') ->where('date >=', $startDate) ->where('date <=', $endDate) ->where('materialCode', $materialCode) ->first()['customer'] ?? ''; } $bagMaterialcount = count($bagMaterials); $data['bagMaterialcount'] = $bagMaterialcount; $data['bagMaterials'] = $bagMaterials; $date = DateTime::createFromFormat('Y-m', $month); $formattedDate = $date->format('M-Y'); $data['month']=$formattedDate; return $this->loadViews("bagStockDetails", $this->global, $data, NULL); } public function updateBagStockDetails(){ $postData = $this->request->getPost(); $updateBagStockDetailsData = json_decode($postData['updateBagStockDetails'], true); foreach($updateBagStockDetailsData as $data){ $date = $data['date']; $materialCode = $data['materialCode']; $dbData= [ 'date' =>$data['date'], 'materialCode' =>$data['materialCode'], 'customer' =>$data['customer'], 'opening' =>$data['opening'], 'receipt' =>$data['receipt'], 'used' =>$data['used'], 'balanceStock' =>$data['balanceStock'], ]; $resultExists=$this->bagStockDetails_model ->where('date',$date) ->where('materialCode',$materialCode) ->first(); if(!empty($resultExists)){ $updated=$this->bagStockDetails_model ->where('date',$date) ->where('materialCode',$materialCode) ->set($dbData) ->update(); }else{ $inserted = $this->bagStockDetails_model->insert($dbData); } } echo "Data Saved Successfully"; } //Dust And Rough Stock Details public function loadView_dustAndRoughStockDetails(){ if ($this->request->getMethod() === 'POST'){ $month = $this->request->getPost('month'); $date = DateTime::createFromFormat('M-Y', $month); $formattedDate = $date->format('Y-m'); $month=$formattedDate; } else{ $month = date('Y-m'); } $data=[]; $data['month']=$month; $this->global['pageTitle']='Dust And Rough Stock Details'; $startDate = "$month-01"; $endDate = date("Y-m-t", strtotime($startDate)); $data['dustAndRoughStockDetails'] = $this->dustAndRoughStockDetails_model ->where('date >=', $startDate) ->where('date <=', $endDate) ->orderBy('date','asc') ->findAll(); $date = DateTime::createFromFormat('Y-m', $month); $formattedDate = $date->format('M-Y'); $data['month']=$formattedDate; return $this->loadViews("dustAndRoughStockDetails", $this->global, $data, NULL); } public function updateDustAndRoughStockDetails(){ $postData = $this->request->getPost(); $updateDustAndRoughStockDetailsData = json_decode($postData['updateDustAndRoughStockDetails'], true); $updates = []; $inserts = []; foreach($updateDustAndRoughStockDetailsData as $data){ $date = $data['date']; $dbData= [ 'date' => $data['date'], 'finalRough' => $data['finalRough'], 'dust' => $data['dust'], 'total' => $data['total'] ]; $resultExists=$this->dustAndRoughStockDetails_model ->where('date',$date) ->first(); if (empty($resultExists)) { $inserts[] = $dbData; } else { $updates[] = $dbData; } } if (!empty($inserts)) { $this->dustAndRoughStockDetails_model->insertBatch($inserts); } if (!empty($updates)) { $updateResult = $this->dustAndRoughStockDetails_model->updateBatch($updates, 'date'); if ($updateResult === FALSE) { echo "Error during update"; } else { echo "Data Updated Successfully"; return; } } echo "Data Saved Successfully"; } //Resin Stock Details public function loadView_resinStockDetails(){ if ($this->request->getMethod() === 'POST'){ $month = $this->request->getPost('month'); $date = DateTime::createFromFormat('M-Y', $month); $formattedDate = $date->format('Y-m'); $month=$formattedDate; } else{ $month = date('Y-m'); } $data=[]; $data['month']=$month; $this->global['pageTitle']='Resin Stock Details'; $previousMonth = DateTime::createFromFormat('Y-m', $month)->modify('-1 month')->format('Y-m'); $previousMonthStartDate = "$previousMonth-01"; $previousMonthEndDate = date("Y-m-t", strtotime($previousMonthStartDate)); $data['previousMonthResinStockDetails'] = $this->resinStockDetails_model ->select(['materialCode', 'date' ,'balanceStock']) ->distinct() ->where('date =', $previousMonthEndDate) ->groupBy(['materialCode','date']) ->orderBy('date','desc') ->orderBy('materialCode','asc') ->findAll(); $startDate = "$month-01"; $endDate = date("Y-m-t", strtotime($startDate)); $data['resinStockDetails'] = $this->resinStockDetails_model ->where('date >=', $startDate) ->where('date <=', $endDate) ->groupBy(['materialCode','date']) ->orderBy('date','asc') ->orderBy('materialCode','asc') ->findAll(); // Initialize an empty array to hold the grouped data $data['groupedResinStockDetails'] = []; // Temporary array to store grouped data by date $groupedByDate = []; // Group by 'date' foreach ($data['resinStockDetails'] as $detail) { $date = $detail['date']; // Initialize the array for this date if it doesn't exist if (!isset($groupedByDate[$date])) { $groupedByDate[$date] = []; } // Append the detail to the sub-array for this date $groupedByDate[$date][] = $detail; } // Reset the structure to have indexed arrays without the date keys $data['groupedResinStockDetails'] = array_values($groupedByDate); $resinMaterials= $this->rawmaterialdetails_model->getAllResinMaterialCode(); foreach($resinMaterials as $key => $resinMaterial){ $materialCode = $resinMaterial['MaterialCode']; $resinMaterials[$key]['customers'] = $this->bagStockDetails_model ->select('customer') ->where('date >=', $startDate) ->where('date <=', $endDate) ->where('materialCode', $materialCode) ->first()['customer'] ?? ''; } $resinMaterialCount = count($resinMaterials); $data['resinMaterialCount'] = $resinMaterialCount; $data['resinMaterials'] = $resinMaterials; $date = DateTime::createFromFormat('Y-m', $month); $formattedDate = $date->format('M-Y'); $data['month']=$formattedDate; return $this->loadViews("resinStockDetails", $this->global, $data, NULL); } public function updateResinStockDetails(){ $postData = $this->request->getPost(); $updateResinStockDetailsData = json_decode($postData['updateResinStockDetails'], true); $updates = []; $inserts = []; foreach($updateResinStockDetailsData as $data){ $date = $data['date']; $materialCode = $data['materialCode']; $dbData = [ 'date' =>$data['date'], 'materialCode' =>$data['materialCode'], 'customer' =>$data['customer'], 'opening' =>$data['opening'], 'receipt' =>$data['receipt'], 'used' =>$data['used'], 'balanceStock' =>$data['balanceStock'], ]; $resultExists = $this->resinStockDetails_model ->where('date',$date) ->where('materialCode',$materialCode) ->first(); if(empty($resultExists)){ $inserts[] = $dbData; }else{ $updates[] = $dbData; } } if (!empty($inserts)) { $this->resinStockDetails_model->insertBatch($inserts); } if (!empty($updates)) { $updateResult = $this->resinStockDetails_model->updateBatch($updates, 'id'); if ($updateResult === FALSE) { echo "Error during update"; } else { echo "Data Updated Successfully"; return; } } echo "Data Saved Successfully"; } // --------------------------------------------gwm---------------------------------------------- function getMonthDatesFromInput($monthYear) { $date = DateTime::createFromFormat('M-Y', $monthYear); if (!$date) { return "Invalid date format. Use 'M-yyyy' format."; } $year = $date->format('Y'); $month = $date->format('m'); $totalDays = cal_days_in_month(CAL_GREGORIAN, $month, $year); $dates = []; for ($day = 1; $day <= $totalDays; $day++) { $currentDate = DateTime::createFromFormat('Y-m-d', "$year-$month-$day"); $dates[] = [ 'readable' => $currentDate->format('d-m-Y'), 'database' => $currentDate->format('Y-m-d') ]; } return $dates; } function fillMissingDates($monthData, $drierDetails) { $filledDetails = []; $drierDetailsByDate = []; foreach ($drierDetails as $detail) { $drierDetailsByDate[$detail['date']] = $detail; } foreach ($monthData as $day) { $date = $day['database']; if (isset($drierDetailsByDate[$date])) { $filledDetails[] = $drierDetailsByDate[$date]; } else { $filledDetails[] = [ 'id' => null, 'date' => $date, 'drier_on_time' => null, 'drier_off_time' => null, 'drier_running_hours' => '0.00', 'supplier_name' => null, 'input_sand_moisture' => '0.00', 'total_gas_consumption' => '0.00', 'gas_per_ton' => '0.00', 'input_sand_qty' => '0.00', 'moisture_loss_qty' => '0.00', 'sand_dried_qty' => '0.00', 'qty_per_hours' => '0.00', 'dust_qty' => '0.00', 'customer_name' => null, 'created_at' => null, 'updated_at' => null ]; } } return $filledDetails; } function generateTimeOptions() { $times = []; $start = strtotime('00:00'); // Start at midnight (12:00 AM) $end = strtotime('23:45'); // End at 11:45 PM while ($start <= $end) { $timeValue = date('H:i', $start); // 24-hour format for value $timeLabel = date('h:i A', $start); // 12-hour format with AM/PM for display $times[$timeValue] = $timeLabel; // Store time in associative array $start = strtotime('+15 minutes', $start); // Increment by 15 minutes } return $times; } function drierMachineDetails() { $currentMonth = $this->request->getPost('month') ? $this->request->getPost('month') : date('M-Y'); $monthData = $this->getMonthDatesFromInput($currentMonth); $data['startDate'] = $monthData[0]['database']; $data['endDate'] = $monthData[count($monthData)-1]['database']; $data['timeDropdown'] = $this->generateTimeOptions(); $data['drierDetails'] = $this->drierMachineDetails_model ->where('date >=', $data['startDate']) ->where('date <=', $data['endDate']) ->findAll(); $data['datefordropdown'] = $currentMonth; $data['data'] = $this->fillMissingDates($monthData, $data['drierDetails']); $this->global['pageTitle'] = 'Drier Details'; $this->loadViews("drierMachineDetails", $this->global, $data, NULL); } public function addOrEditdrierMachineDetails() { $drierData = json_decode($this->request->getPost('drierData'), true); if (empty($drierData)) { echo "No data received."; return; } foreach ($drierData as $row) { $data = [ 'date' => DateTime::createFromFormat('d-m-Y', $row['Date'])->format('Y-m-d'), 'drier_on_time' => $row['Drier On Time'], 'drier_off_time' => $row['Drier Off Time'], 'drier_running_hours' => $row['Running Hrs'], 'supplier_name' => $row['Supplier Name'], 'input_sand_moisture' => $row['i/p Sand Moisture(%)'], 'total_gas_consumption'=> $row['Tot Gas Consumption'], 'gas_per_ton' => $row['Gas Pre Ton'], 'input_sand_qty' => $row['i/p Sand Qty'], 'moisture_loss_qty' => $row['Moisture Loss Qty'], 'sand_dried_qty' => $row['Sand Dried Qty'], 'qty_per_hours' => $row['Qty Per Hrs'], 'dust_qty' => $row['Dust Qty'], 'customer_name' => $row['Customer Name'] ]; // Check if a row with the same date already exists $existingRow = $this->drierMachineDetails_model->where('date', $data['date'])->first(); if ($existingRow) { // If exists, update the row $this->drierMachineDetails_model->update($existingRow['id'], $data); } else { // If not, insert a new row $this->drierMachineDetails_model->insert($data); } } echo "Data successfully saved."; } public function factoryVehicleDieselDetails() { $currentMonth = $this->request->getPost('month') ? $this->request->getPost('month') : date('M-Y'); $monthData = $this->getMonthDatesFromInput($currentMonth); $data['startDate'] = $monthData[0]['database']; $data['endDate'] = $monthData[count($monthData)-1]['database']; $data['datefordropdown'] = $currentMonth; //Machine Details $data['machineDetails'] = $this->factoryMachine_model->where('energy_type', 'diesel')->where('is_active', 1)->findAll(); if(!count([$data['machineDetails']])) { return $this->response->setBody(""); } //Diesel Stock Summary Details $data['summaryDetails'] = $this->factoryVehicleDieselStockSummary_model->select('date,opening_stock as opening_stock_0,purchase_diesel as purchase_diesel_0,total_filling_diesel as total_filling_diesel_0,balance_stock as balance_stock_0')->where('date >=', $data['startDate'])->where('date <=', $data['endDate'])->findAll(); if(!count($data['summaryDetails'])) { //insert empty data $tempInsert = []; foreach ($monthData as $key => $value) { array_push($tempInsert,[ 'date'=>$value['database'] ]); } $this->factoryVehicleDieselStockSummary_model->insertBatch($tempInsert); $data['summaryDetails'] = $this->factoryVehicleDieselStockSummary_model->where('date >=', $data['startDate'])->where('date <=', $data['endDate'])->findAll(); } //Diesel Consumption Details $data['dieselConsumptionDetails'] = $this->getDieselConsumptionPivot($data['machineDetails'] , $data['startDate'] , $data['endDate']); if(!count($data['dieselConsumptionDetails'])) { //insert empty data $tempInsert = []; foreach ($monthData as $key => $value) { array_push($tempInsert,['date'=>$value['database'] , 'machine_id'=>$data['machineDetails'][0]['id'] ]); } $this->factoryVehicleDieselDetails_model->insertBatch($tempInsert); $data['dieselConsumptionDetails'] = $this->getDieselConsumptionPivot($data['machineDetails'] , $data['startDate'] , $data['endDate']); } $mergedArray = []; // Loop through the first array foreach ($data['summaryDetails'] as $item1) { $date = $item1["date"]; // Find the matching item in the second array by date foreach ($data['dieselConsumptionDetails'] as $item2) { if ($item2["date"] === $date) { // Merge the two arrays $mergedArray[] = array_merge($item1, $item2); break; // Stop once the matching date is found } } } $data['dieselConsumptionDetails'] = $mergedArray; $data['machineName'] = array_column($data['machineDetails'], 'machine_name'); $this->global['pageTitle'] = 'Drier Details'; $this->loadViews("factoryDieselMachineDetails", $this->global, $data, NULL); } public function getDieselConsumptionPivot($machineDetails , $startDate , $endDeate) { $machineIds = array_column($machineDetails, 'id'); if (empty($machineIds)) { return []; } $fields = ['opening_reading', 'closing_reading', 'filling_diesel', 'consumption', 'running_hours', 'mileage']; $pivotColumns = []; foreach ($machineIds as $machineId) { foreach ($fields as $field) { $pivotColumns[] = "MAX(CASE WHEN machine_id = $machineId THEN $field ELSE 0 END) AS {$field}_{$machineId}"; } } $pivotColumnString = implode(", ", $pivotColumns); $sql = "SELECT `date`, $pivotColumnString FROM `t_factoryVehicleDieselDetails` WHERE machine_id IN (" . implode(",", $machineIds) . ") AND `date` >= ? AND `date` <= ? GROUP BY `date`"; $query = $this->db->query($sql, [$startDate,$endDeate]); $result = $query->getResultArray(); return $result; } public function addOrEditfactoryVehicleDieselDetails() { $dieselMachineTableData = json_decode($this->request->getPost('dieselMachineTableData'), true); $transformedData = []; foreach ($dieselMachineTableData as $entry) { $date = $entry['date']; foreach ($entry as $key => $value) { if ($key === 'date') { continue; } preg_match('/(.*?)_(\d+)$/', $key, $matches); if (count($matches) === 3) { $field = $matches[1]; $machineId = $matches[2]; $insertKey = "{$date}_{$machineId}"; if (!isset($transformedData[$insertKey])) { $transformedData[$insertKey] = [ 'date' => DateTime::createFromFormat('d-m-Y', $date)->format('Y-m-d'), 'machine_id' => $machineId, 'opening_reading' => 0.00, 'closing_reading' => 0.00, 'filling_diesel' => 0.00, 'consumption' => 0.00, 'running_hours' => 0.00, 'mileage' => 0.00, ]; } $transformedData[$insertKey][$field] = (float) $value; } } } foreach ($transformedData as $row) { // Check if a row with the same date already exists $existingRow = $this->factoryVehicleDieselDetails_model->where('date', $row['date'])->where('machine_id', $row['machine_id'])->first(); if ($existingRow) { // If exists, update the row $this->factoryVehicleDieselDetails_model->update($existingRow['id'], $row); } else { // If not, insert a new row $this->factoryVehicleDieselDetails_model->insert($row); } } echo "Data successfully saved."; } }