<?php

namespace App\Models;

use App\Exports\MapExport;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Mtc\MercuryDataModels\Traits\EnsuresSlug;

class ExportMap extends Model
{
    use HasFactory;
    use EnsuresSlug;

    protected $fillable = [
        'name',
        'active',
        'slug',
        'type',
        'conditions',
        'columns',
        'export_time',
        'next_due_at',
        'last_sent_at',
        'export_day_of_week',
        'export_day_of_month',
        'schedule',
        'format',
        'driver',
        'host',
        'root',
        'username',
        'password',
        'filename',
        'schedule_enabled',
        'include_header_row',
        'ftp_export_enabled',
    ];

    protected $casts = [
        'password' => 'encrypted',
        'active' => 'boolean',
        'schedule_enabled' => 'boolean',
        'include_header_row' => 'boolean',
        'ftp_export_enabled' => 'boolean',
        'conditions' => 'array',
        'columns' => 'array',
        'last_sent_at' => 'datetime:Y-m-d H:i',
        'next_due_at' => 'datetime:Y-m-d H:i',
    ];

    protected static function boot()
    {
        parent::boot();

        self::saving(function (self $exportMap) {
            $exportMap->ensureSlug();
        });
    }

    /**
     * Scope to filter by active state
     *
     * @param Builder $query
     * @param $value
     * @return void
     */
    public function scopeActive(Builder $query, $value = null)
    {
        if (in_array($value, [0, 1], true)) {
            $query->where('active', $value);
        }
    }

    /**
     * Get the next scheduled datetime for the report
     *
     * @param Carbon $from
     * @return mixed
     */
    public function getNextDueAt(Carbon $from)
    {
        return App::make(Config::get('export_maps.schedule_types.' . $this->schedule))
            ->nextTime($from, $this);
    }

    public function exportClass(): string
    {
        return match ($this->format) {
            'csv', 'xlsx' => MapExport::class,
            default => ''
        };
    }

    public function setSchedule()
    {
        if ($this->active !== true || $this->schedule_enabled !== true) {
            $this->next_due_at = null;
        }

        if ($this->isDirty('next_due_at')) {
            return;
        }

        $scheduleColumns = [
            'schedule_enabled',
            'schedule',
            'export_time',
            'export_day_of_week',
            'export_day_of_month',
        ];
        if ($this->isDirty($scheduleColumns)) {
            $this->next_due_at = $this->getNextDueAt(Carbon::now());
        }
    }
}
