plantId = $plantId; $this->lineId = $lineId; $this->year = $year; $this->month = $month; $this->week = strtolower($week); } public function array(): array { $weekMapping = [ 'week_1' => 1, 'week_2' => 8, 'week_3' => 15, 'week_4' => 22, 'week_5' => 29, ]; $daysInMonth = Carbon::create( $this->year, $this->month, 1 )->daysInMonth; if ($this->week === 'all_weeks') { $startDay = 1; $maxDays = $daysInMonth; } else { if (!isset($weekMapping[$this->week])) { throw new \Exception('Please select a valid week.'); } $startDay = $weekMapping[$this->week]; $daysInMonth = Carbon::create( $this->year, $this->month, 1 )->daysInMonth; $maxDays = min(7, $daysInMonth - $startDay + 1); if ($maxDays <= 0) { throw new \Exception('Selected week has no dates in this month.'); } } // Plant Code $plant = Plant::find($this->plantId); if (!$plant) { throw new \Exception('Plant not found.'); } // Excel headings $headings = [ 'Plant Code', 'Item Code', ]; $selectedDates = []; for ($i = 0; $i < $maxDays; $i++) { $day = $startDay + $i; $date = Carbon::create( $this->year, $this->month, $day ); $selectedDates[] = $date->format('Y-m-d'); $headings[] = $date->format('d-m-Y'); } // Existing monthly production plans $plans = ProductionPlan::where('plant_id', $this->plantId) ->where('line_id', $this->lineId) ->whereMonth('created_at', $this->month) ->whereYear('created_at', $this->year) ->with('item') ->get(); $excelRows = []; foreach ($plans as $plan) { $itemCode = $plan->item->code ?? ''; // Get leave dates $leaveDates = $plan->leave_dates ?? []; if (is_string($leaveDates)) { $leaveDates = explode(',', $leaveDates); } $leaveDates = collect($leaveDates) ->map(fn ($date) => trim($date)) ->filter() ->map(fn ($date) => Carbon::parse($date)->format('Y-m-d')) ->toArray(); $row = [ $plant->code, $itemCode, ]; foreach ($selectedDates as $date) { // Leave date quantity is 0 if (in_array($date, $leaveDates)) { $row[] = 0; } else { // Sample default quantity $row[] = 0; } } $excelRows[] = $row; } return array_merge( [$headings], $excelRows ); } }