<?php

namespace App\Reporting;

use App\Contracts\ReportTile;
use Carbon\Carbon;
use Mtc\MercuryDataModels\ReportingStat;

class EnquiryCountTile extends ReportTile
{
    private $value;
    private $second_value;

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

    public function value(): mixed
    {
        if (empty($this->value)) {
            $this->value = ReportingStat::query()
                ->where('key', 'enquiries')
                ->whereBetween('date', [Carbon::now()->subDays(30), Carbon::now()])
                ->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', [Carbon::now()->subDays(60), Carbon::now()->subDays(30)])
                ->sum('value');
        }

        return $this->second_value;
    }

    public function subtitle(): string
    {
        return 'last 30 days';
    }

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

    public function secondaryValueName(): string
    {
        return 'prev 30 d.';
    }
}
