<?php

namespace App\Exports;

use App\Constants\Status;
use App\Models\Student\StudentInfo;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class StudentsInfoExport implements FromQuery, WithHeadings, WithMapping
{
    protected $filters;

    public function __construct($filters)
    {
        $this->filters = $filters;
    }

    public function query()
    {

        $query = StudentInfo::query()
            ->with([
                'user',
                'branch',
                'studentClass',
                'section',
                'shift',
                'guardianInfo',
            ]);

        // Apply filters
        if (!empty($this->filters['branch'])) {
            $query->where('branch_id', $this->filters['branch']);
        }

        if (!empty($this->filters['shift'])) {
            $query->where('shift_id', $this->filters['shift']);
        }

        if (!empty($this->filters['group'])) {
            $query->where('group_id', $this->filters['group']);
        }

        if (!empty($this->filters['student_class'])) {
            $query->where('student_class_id', $this->filters['student_class']);
        }

        if (!empty($this->filters['section'])) {
            $query->where('section_id', $this->filters['section']);
        }

        return $query->where('status', '!=', Status::GRADUATED);
    }

    public function headings(): array
    {
        return [
            'Student ID',
            'First Name',
            'Last Name',
            'Gender',
            'Date of Birth',
            'Mobile No',
            'Email',
            'Class',
            'Section',
            'Shift',
            'Branch',
            'Father Name',
            'Mother Name',
            'Guardian Name',
            'Guardian Number',
        ];
    }

    public function map($student): array
    {
        return [
            $student->student_id_no,
            $student->first_name,
            $student->last_name,
            $student->gender,
            $student->date_of_birth,
            $student->mobile_no,
            $student->email,
            $student->studentClass->class_name ?? '',
            $student->section->section_name ?? '',
            $student->shift->shift_name ?? '',
            $student->branch->branch_name ?? '',
            $student->father_name,
            $student->mother_name,
            $student->guardianInfo->guardian_name,
            $student->guardian_mobile,

        ];
    }
}
