<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class DashboardExport implements FromCollection, WithHeadings, WithStyles
{
    protected $data;
    protected $filterDetails;

    public function __construct($data, $filterDetails = [])
    {
        $this->data = $data;
        $this->filterDetails = $filterDetails;
    }

    public function collection()
    {
        return collect($this->data)->map(function ($item) {
            return [
                'check_in' => $item['stats']['check_in'] ?? 0,
                'visit_dealer' => $item['stats']['visit_dealer'] ?? 0,
                'visit_retailer' => $item['stats']['visit_retailer'] ?? 0,
                'visit_farmer' => $item['stats']['visit_farmer'] ?? 0,
            ];
        });
    }

    public function headings(): array
    {
        // Add Filter Details as Headings
        $headings = [
            ['Laporan Dashboard Visit'],
            ['Periode', $this->filterDetails['periode'] ?? '-'],
            ['Marketing Manager', $this->filterDetails['mk'] ?? '-'],
            ['Agronomis', $this->filterDetails['agro'] ?? '-'],
            ['Field Assistant', $this->filterDetails['fa'] ?? '-'],
            [''], // Empty row for spacing
            [
                'Check-in',
                'Visit Dealer',
                'Visit Retailer',
                'Visit Farmer',
            ]
        ];

        return $headings;
    }

    public function styles(Worksheet $sheet)
    {
        return [
            // Style the first row as title
            1    => ['font' => ['bold' => true, 'size' => 14]],

            // Bold the labels for the filters
            2    => ['font' => ['bold' => true]],
            3    => ['font' => ['bold' => true]],
            4    => ['font' => ['bold' => true]],
            5    => ['font' => ['bold' => true]],

            // Bold the table headers
            7    => ['font' => ['bold' => true]],
        ];
    }
}
