<?php

namespace App\Models\Base;

use App\Helpers\Helper;
use Hyn\Tenancy\Traits\UsesTenantConnection;
use Illuminate\Database\Eloquent\Model;
use Kyslik\ColumnSortable\Sortable;

class CfdiDownloadRequest extends Model
{
    use Sortable,UsesTenantConnection;

    protected $table = 'cfdi_download_requests';

    const PATH_FILES = 'files/cfdi_download_requests';

    /**
     * Attributes that should be mass-assignable.
     *
     * @var array
     */
    protected $fillable = [
        'created_uid',
        'updated_uid',
        'date',
        'folio',
        'folio_metadata',
        'type',
        'date_start',
        'date_end',
        'qty',
        'folio_download',
        'folio_download_metadata',
        'file',
        'file_metadata',
        'company_id',
        'completed',
        'status'
    ];

    /**
     * Sortable columns.
     *
     * @var array
     */
    public $sortable = [
        'date',
        'folio'
    ];

    public function scopeFilter($query, array $input = [])
    {
        $query->where(function ($query) {
            $query->where('cfdi_download_requests.company_id', '=', \App\Helpers\Helper::defaultCompany()->id);
        })->where(function($query) use ($input) {
            if (!empty($input['filter_search'])) {
                $search = $input['filter_search'];
                $query->orWhere('folio', 'like', '%' . str_replace(' ', '%%', $search) . '%');
            }
            if (!empty($input['filter_folio'])) {
                $folio = $input['filter_folio'];
                $query->orWhere('folio', 'like', '%' . str_replace(' ', '%%', $folio) . '%');
            }
            if (!empty($input['filter_date_from'])) {
                $query->whereDate('date', '>=', Helper::convertDateToSql($input['filter_date_from']));
            }
            if (!empty($input['filter_date_to'])) {
                $query->whereDate('date', '<=', Helper::convertDateToSql($input['filter_date_to']));
            }
            if (!empty($input['filter_type'])) {
                $query->where('type', '=', $input['filter_type']);
            }
        });

        return $query;
    }

    public function getTypeNameAttribute()
    {
        return $this->type == 1 ? __('base/cfdi_download.tab_received') : ($this->type == 2 ? __('base/cfdi_download.tab_issued') : '');
    }

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public function cfdiDownloadRequestFiles()
    {
        return $this->hasMany(CfdiDownloadRequestFile::class);
    }
}
