<?php

namespace App\Reporting;

use App\Contracts\ReportTile;
use App\Reporting\Concerns\HasReportingPeriod;
use Mtc\MercuryDataModels\ReportingStat;

class EnquiryCountTile extends ReportTile
{
    use HasReportingPeriod;

    private $value;
    private $second_value;

    public function name(): string
    {
        return 'Enquiries';
    }

    public function value(): mixed
    {
        if (empty($this->value)) {
            $this->value = ReportingStat::query()
                ->where('key', 'enquiries')
                ->whereBetween('date', [$this->windowStart(), $this->windowEnd()])
                ->sum('value');
        }
        return $this->value;
    }

    public function difference(): mixed
    {
        if ($this->secondaryValue() > 0) {
            return (100 * round(($this->value() - $this->secondaryValue()) / ($this->secondaryValue() ?: 1), 2)) . '%';
        }
        return '';
    }

    public function secondaryValue(): mixed
    {
        if (empty($this->second_value)) {
            $this->second_value = ReportingStat::query()
                ->where('key', 'enquiries')
                ->whereBetween('date', [$this->previousStart(), $this->previousEnd()])
                ->sum('value');
        }

        return $this->second_value;
    }

    public function subtitle(): string
    {
        return $this->periodSubtitle();
    }

    #[\Override]
    public function differenceType(): string
    {
        if ($this->difference() > 0) {
            return 'positive';
        }
        return $this->difference() < 0
            ? 'negative'
            : 'noChange';
    }

    public function secondaryValueName(): string
    {
        return $this->previousPeriodName();
    }
}
