<?php

namespace App\Exports;

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


class PhonebookExport implements FromCollection, WithHeadings
{
    public function __construct($listAll)
    {
        $data = [];
        if ($listAll) {
            $pbs = Phonebook::orderBy('name')->get();
            foreach($pbs as $pb) {
                $pbDatas = json_decode($pb->data);
                foreach ($pbDatas as $pbData) {
                    array_push($data, ['pb_name' => $pb->name, 'name' => $pbData->name, 'phone' => $pbData->phone, 'email' => empty($pbData->email)?null:$pbData->email, 'memo' => empty($pbData->memo)?null:$pbData->memo, 'column1' => empty($pbData->column1)?null:$pbData->column1, 'column2' => empty($pbData->column2)?null:$pbData->column2, 'column3' => empty($pbData->column3)?null:$pbData->column3, 'column4' => empty($pbData->column4)?null:$pbData->column4, 'column5' => empty($pbData->column5)?null:$pbData->column5]);
                }
            }
        } else {
            $pbs = Phonebook::where('user_id', '=', auth()->user()->id)->orderBy('name')->get();
            foreach($pbs as $pb) {
                $pbDatas = json_decode($pb->data);
                foreach ($pbDatas as $pbData) {
                    array_push($data, ['pb_name' => $pb->name, 'name' => $pbData->name, 'phone' => $pbData->phone, 'email' => empty($pbData->email)?null:$pbData->email, 'memo' => empty($pbData->memo)?null:$pbData->memo, 'column1' => empty($pbData->column1)?null:$pbData->column1, 'column2' => empty($pbData->column2)?null:$pbData->column2, 'column3' => empty($pbData->column3)?null:$pbData->column3, 'column4' => empty($pbData->column4)?null:$pbData->column4, 'column5' => empty($pbData->column5)?null:$pbData->column5]);
                }
            }
        }
        $this->phonebooks = $data;
    }

    public function collection()
    {
        return collect($this->phonebooks);
    }
  
    public function headings(): array
    {
        return ['pb_name','name','phone','email','memo','column1','column2','column3','column4','column5'];
    }
}