CasperSecurity
<?php
namespace App\Exports;
use App\Models\EmployeeRegistration;
use App\Models\PayrollItems;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Illuminate\Support\Collection;
class AttendanceFormatExport implements WithHeadings
{
/**
* @return \Illuminate\Support\Collection
*/
protected $headings;
public $month;
public $year;
public function __construct()
{
$this->headings = $this->getAllDates();
}
public function collection()
{
if(session('selected_month')==null){
$selectedMonth = session('selected_month', \Illuminate\Support\Carbon::now());
$this->month=Carbon::parse($selectedMonth)->format('m');
$this->year=Carbon::parse($selectedMonth)->format('Y');
}else{
$this->month=Carbon::parse(session('selected_month'))->format('m');
$this->year=Carbon::parse(session('selected_month'))->format('Y');
}
$employees=EmployeeRegistration::where('status',1)->get();
session()->forget('selected_month');
}
public function headings(): array
{
return $this->headings;
}
private function getAllDates(){
// Initial headings
$headings = ['employee_id', 'attendance_id', 'attendance_date'];
// Determine selected month and year from session or default to the current date
if (session('selected_month') == null) {
$selectedMonth = Carbon::now();
} else {
$selectedMonth = Carbon::parse(session('selected_month'));
}
$this->month = $selectedMonth->format('m');
$this->year = $selectedMonth->format('Y');
// Generate dates for the entire selected month
$dates = [];
$daysInMonth = Carbon::createFromDate($this->year, $this->month)->daysInMonth;
for ($day = 1; $day <= $daysInMonth; $day++) {
$dates[] = Carbon::create($this->year, $this->month, $day)->format('Y-m-d');
}
// Merge headings with dates
return array_merge($headings, $dates);
}
}