<?php

namespace Inside\DESK\Exports;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Str;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class NewslettersDeskStatisticsExport extends AbstractDeskStatisticsExport
{
    private array $filters;
    private ?string $langcode;

    public function __construct(array $filters = [], ?string $langcode = 'en')
    {
        parent::__construct();
        $this->filters = $filters;
        $this->langcode = $langcode;
    }

    public function query(): Builder
    {
        return $this->deskStatistics->getNewslettersStatisticsQuery($this->filters);
    }

    public function headings(): array
    {
        if ($this->langcode) {
            Lang::setLocale($this->langcode);
        }

        return [
            Lang::get("desk.statistics.newsletters.cols.sentDate"),
            Lang::get("desk.statistics.newsletters.cols.sent"),
            Lang::get("desk.statistics.newsletters.cols.viewed"),
            Lang::get("desk.statistics.newsletters.cols.clicked"),
            Lang::get("desk.statistics.newsletters.cols.uniqueClicked"),
            Lang::get("desk.statistics.newsletters.cols.langcode"),
        ];
    }

    public function map($row): array
    {
        return [
            Date::dateTimeToExcel(Carbon::createFromTimestampUTC($row->date_sent)),
            $row->sent ?? '0',
            $row->viewed ?? '0',
            $row->unique_clicked ?? '0',
            $row->clicked ?? '0',
            $row->langcode ? Str::upper($row->langcode) : '-',
        ];
    }

    public function columnFormats(): array
    {
        return [
            'A' => NumberFormat::FORMAT_DATE_DDMMYYYY,
        ];
    }
}
