<?php

namespace App\Exports;

use App\Models\CaptureItem;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;


class CaptureSubjectExport implements FromCollection, WithHeadings
{
    public function __construct($captureSubject)
    {
        if (!empty($captureSubject)) {
            $data = [];
            $tmp = [];
            $cis = CaptureItem::where('user_id', '=', auth()->user()->id)->where('subject', '=', $captureSubject)->get();
            foreach ($cis as $ci) {
                $ciData = json_decode($ci->data);
                $this->headers = [];
                foreach ($ciData as $key => $value) {
                    array_push($this->headers, $key);
                    $tmp[$key] = $value;
                }
                array_push($this->headers, 'created_at');
                $tmp['created_at'] = $ci->created_at;
                array_push($data, $tmp);
            }
            $this->captureItems = $data;
        }
    }

    public function collection()
    {
        return collect($this->captureItems);
    }
  
    public function headings(): array
    {
        return $this->headers;
    }
}