<?php

namespace App\Exports;

use App\Models\Exam;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Events\BeforeSheet;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;


class ExamStudentExport implements 
FromView,
ShouldAutoSize,
WithEvents
{
    use Exportable;
    private $roomId;
    public function __construct( $roomId)
    {
        $this->roomId = $roomId;
    }
    /**
    * @return \Illuminate\Support\Collection
    */
    public function view():View
    {
        $exams =   Exam::with('uploaded')
      ->where('room_id',$this->roomId)->get()
      ->map(function ($item)
      {
        $item->uploaded->map(function ($item)
       {
        foreach ($item->answers as $answer) {
            $item->totalMark +=$answer->mark;
            $item->questionMark += $answer->question->mark;
        }
        return $item->answers;
       });

       return $item;
      });
        return view('exports.exam-student',[
                'exams'=>$exams
        ]);
    }

public function registerEvents(): array
{
    return [
                BeforeSheet::class  =>function(BeforeSheet $event){
                    $event->getDelegate()->setRightToLeft(true);
                },
                AfterSheet::class =>function (AfterSheet $event)
                {
                    $event->sheet->getStyle('A1:I1')->applyFromArray([
                        'font'=>[
                            'bold'=>true
                        ]
                    ]);
                }
    ] ;
    }
}
