<?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 AlertsDeskStatisticsExport extends AbstractDeskStatisticsExport
{
    private ?string $search;
    private array $filters;
    private ?string $langcode;

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

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

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

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

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

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