<?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 mixed */
    private $value;

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

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

    /**
     * DateScope constructor.
     *
     * @param string $field
     * @param mixed $value
     * @param string|null $startDate
     * @param string|null $endDate
     */
    public function __construct($field, $value = null, $startDate = null, $endDate = null)
    {
        $this->field = $field;
        $this->value = $value;

        $this->start = $this->cleanDate($startDate);
        $this->end = $this->cleanDate($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)
    {
        if (empty($this->start) && empty($this->end)) {
            return $query;
        }

        if (empty($this->end)) {
            return $query->where($this->field, '>=', Carbon::parse($this->start)->startOfDay()->format('Y-m-d H:i:s'));
        }

        if (empty($this->start)) {
            return $query->where($this->field, '<=', Carbon::parse($this->end)->endOfDay()->format('Y-m-d H:i:s'));
        }

        return $query->whereBetween($this->field, [
            Carbon::parse($this->start)->startOfDay()->format('Y-m-d H:i:s'),
            Carbon::parse($this->end)->endOfDay()->format('Y-m-d H:i:s')
        ]);
    }

    /**
     * Clean the provided date string.
     *
     * @param string $date
     *
     * @return string|string[]
     */
    protected function cleanDate($date)
    {
        return str_ireplace(["\\", '.', '-', '_'], '/', $date);
    }
}
