<?php

namespace App\Reporting;

use App\Contracts\ReportTile;
use Carbon\Carbon;
use Mtc\Crm\Models\Enquiry;
use Mtc\MercuryDataModels\ReportingStat;

class DailyEnquiryCountTile 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 = Enquiry::query()
                ->where('created_at', '>=', Carbon::now()->startOfDay())
                ->count();
        }
        return $this->value;
    }

    public function difference(): mixed
    {
        return round(($this->value() - $this->secondaryValue()) / ($this->secondaryValue() ?: 1), 2);
    }

    public function secondaryValue(): mixed
    {
        if (empty($this->second_value)) {
            $this->second_value = ReportingStat::query()
                ->where('key', 'enquiries')
                ->where('date', Carbon::now()->subDay()->format('Y-m-d'))
                ->first()
                ->value ?? 0;
        }

        return $this->second_value;
    }

    public function subtitle(): string
    {
        return 'today';
    }

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

    public function secondaryValueName(): string
    {
        return 'yesterday';
    }
}
