<?php

namespace Ignite\Core\Models\Grid\Scopes;

use Illuminate\Support\Carbon;
use Yajra\DataTables\Contracts\DataTableScope;

class DateScope implements DataTableScope
{
    /** @var string */
    private $field;

    /** @var Carbon */
    private $start;

    /** @var Carbon */
    private $end;

    /**
     * DateScope constructor.
     *
     * @param string $field
     * @param string $startDate
     * @param string $endDate
     */
    public function __construct($field, $startDate, $endDate)
    {
        $this->field = $field;
        $startDate = str_ireplace(['/', '\\', '.'], '-', $startDate);

        $this->start = empty($startDate) ? Carbon::now() : Carbon::parse();

        $endDate = str_ireplace(['/', '\\', '.'], '-', $endDate);
        $this->end = empty($endDate) ? Carbon::now()->endOfYear() : Carbon::parse($endDate);
    }

    /**
     * Apply the date scope to the query.
     *
     * @param \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder|mixed
     */
    public function apply($query)
    {
        return $query->whereBetween($this->field, [
            $this->start->startOfDay()->format('Y-m-d H:i:s'),
            $this->end->endOfDay()->format('Y-m-d H:i:s')
        ]);
    }
}
