<?php

namespace App\Models\Sales;

use App\Helpers\Helper;
use App\Models\Base\Company;
use App\Models\Catalogs\CfdiUse;
use App\Models\Catalogs\Project;
use App\Models\Base\BranchOffice;
use App\Models\Base\DocumentType;
use App\Models\Catalogs\Currency;
use App\Models\Catalogs\PaymentWay;
use App\Models\Catalogs\TaxRegimen;
use Kyslik\ColumnSortable\Sortable;
use App\Models\Catalogs\PaymentTerm;
use App\Models\Catalogs\PaymentMethod;
use Illuminate\Database\Eloquent\Model;
use Hyn\Tenancy\Traits\UsesTenantConnection;

/**
 * App\Models\Sales\CustomerQuotation
 *
 * @property int $id
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property int|null $created_uid
 * @property int|null $updated_uid
 * @property string $name
 * @property string|null $serie
 * @property int|null $folio
 * @property string|null $date
 * @property string|null $date_due
 * @property string|null $expiration_date
 * @property string|null $reference
 * @property int|null $customer_id
 * @property int|null $branch_office_id
 * @property int|null $payment_term_id
 * @property int|null $payment_way_id
 * @property int|null $payment_method_id
 * @property int|null $cfdi_use_id
 * @property int|null $salesperson_id
 * @property int|null $currency_id
 * @property float $currency_value
 * @property float $amount_discount
 * @property float $amount_untaxed
 * @property float $amount_tax
 * @property float $amount_tax_ret
 * @property float $amount_total
 * @property float $balance
 * @property int|null $document_type_id
 * @property string|null $comment
 * @property string|null $terms_of_sale
 * @property bool $mail_sent
 * @property int $sort_order
 * @property bool $status
 * @property int|null $company_id
 * @property string|null $invoice
 * @property-read \App\Models\Base\BranchOffice|null $branchOffice
 * @property-read \App\Models\Catalogs\CfdiUse|null $cfdiUse
 * @property-read \App\Models\Base\Company|null $company
 * @property-read \App\Models\Catalogs\Currency|null $currency
 * @property-read \App\Models\Sales\Customer|null $customer
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Sales\CustomerQuotationLine[] $customerActiveQuotationLines
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Sales\CustomerQuotationLine[] $customerQuotationLines
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Sales\CustomerQuotationTax[] $customerQuotationTaxes
 * @property-read \App\Models\Base\DocumentType|null $documentType
 * @property-read mixed $description_select2
 * @property-read mixed $text_select2
 * @property-read \App\Models\Catalogs\PaymentMethod|null $paymentMethod
 * @property-read \App\Models\Catalogs\PaymentTerm|null $paymentTerm
 * @property-read \App\Models\Catalogs\PaymentWay|null $paymentWay
 * @property-read \App\Models\Sales\Salesperson|null $salesperson
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation filter($input = array())
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation sortable($defaultParameters = null)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation totalDashboard($input = array())
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereAmountDiscount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereAmountTax($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereAmountTaxRet($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereAmountTotal($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereAmountUntaxed($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereBalance($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereBranchOfficeId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereCfdiUseId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereComment($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereCompanyId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereCreatedUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereCurrencyId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereCurrencyValue($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereCustomerId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereDate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereDateDue($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereDocumentTypeId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereExpirationDate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereFolio($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereInvoice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereMailSent($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation wherePaymentMethodId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation wherePaymentTermId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation wherePaymentWayId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereReference($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereSalespersonId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereSerie($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereSortOrder($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereTermsOfSale($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereUpdatedUid($value)
 * @mixin \Eloquent
 * @property-read \App\Models\Sales\CustomerInvoice $customerInvoice
 * @property int|null $project_id
 * @property-read \App\Models\Catalogs\Project|null $project
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Sales\CustomerQuotation whereProjectId($value)
 */
class CustomerQuotation extends Model
{
    use Sortable,UsesTenantConnection;

    protected $table = 'customer_quotations';


    //Por timbrar
    const OPEN = 1; //Activa
    const BILLED = 2; //Facturada
    const CANCEL = 3; //Cancelada

    /**
     * Attributes that should be mass-assignable.
     *
     * @var array
     */
    protected $fillable = [
        'created_uid',
        'updated_uid',
        'name',
        'serie',
        'folio',
        'date',
        'date_due',
        'expiration_date',
        'reference',
        'customer_id',
        'branch_office_id',
        'payment_term_id',
        'payment_way_id',
        'payment_method_id',
        'cfdi_use_id',
        'salesperson_id',
        'currency_id',
        'currency_value',
        'amount_discount',
        'amount_untaxed',
        'amount_tax',
        'amount_tax_ret',
        'amount_total',
        'balance',
        'document_type_id',
        'comment',
        'terms_of_sale',
        'mail_sent',
        'sort_order',
        'status',
        'company_id',
        'invoice',
        'project_id',
        'tax_regimen_customer_id',
    ];

    /**
     * Sortable columns.
     *
     * @var array
     */
    public $sortable = [
        'name',
        'date',
        'date_due',
        'amount_untaxed',
        'amount_total',
        'balance',
        'mail_sent',
        'sort_order',
        'status',
        'invoice'
    ];

    public function scopeFilter($query, array $input = [])
    {
        $query->where(function ($query) {
            $query->where('customer_quotations.company_id', '=', \App\Helpers\Helper::defaultCompany()->id);
        })->where(function($query) use ($input) {
            if (!empty($input['filter_search'])) {
                $search = $input['filter_search'];
                $query->orWhere('name', 'like', '%' . str_replace(' ', '%%', $search) . '%');
            }
            if (!empty($input['filter_document_type_code'])) {
                $filter_document_type_code = $input['filter_document_type_code'];
                $query->WhereHas('documentType', function ($q) use ($filter_document_type_code) {
                    if(is_array($filter_document_type_code)){
                        $q->whereIn('document_types.code', $filter_document_type_code);
                    }else {
                        $q->where('document_types.code', '=', $filter_document_type_code);
                    }
                });
            }
            if (!empty($input['filter_name'])) {
                $name = $input['filter_name'];
                $query->where('name', 'like', '%' . str_replace(' ', '%%', $name) . '%');
            }
            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_payment_way_id'])) {
                $payment_way_id = $input['filter_payment_way_id'];
                $query->where('payment_way_id', '=', $payment_way_id);
            }
            if (!empty($input['filter_customer_id'])) {
                $customer_id = $input['filter_customer_id'];
                $query->where('customer_id', '=', $customer_id);
            }
            if (!empty($input['filter_currency_id'])) {
                $currency_id = $input['filter_currency_id'];
                $query->where('currency_id', '=', $currency_id);
            }
            if (!empty($input['filter_branch_office_id'])) {
                $branch_office_id = $input['filter_branch_office_id'];
                $query->where('branch_office_id', '=', $branch_office_id);
            }
            if (!empty($input['filter_salesperson_id'])) {
                $salesperson_id = $input['filter_salesperson_id'];
                $query->where('salesperson_id', '=', $salesperson_id);
            }
            if (!empty($input['filter_project_id'])) {
                $project_id = $input['filter_project_id'];
                $query->where('project_id', '=', $project_id);
            }
            if (!empty($input['filter_status'])) {
                $status = $input['filter_status'];
                $query->where('status', '=', $status);
            }
        });

        return $query;
    }

    public function scopeTotalDashboard($query, array $input = []){

        $query->where(function ($query) {
            $query->where('company_id', '=', \App\Helpers\Helper::defaultCompany()->id);
        })->where(function($query) use ($input) {
            $query->whereIn('status', [self::OPEN, self::BILLED]);
            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_document_type_code'])) {
                $filter_document_type_code = $input['filter_document_type_code'];
                $query->WhereHas('documentType', function ($q) use ($filter_document_type_code) {
                    $q->where('document_types.code', '=', $filter_document_type_code);
                });
            }
        });

        return $query;
    }

    public function getTextSelect2Attribute()
    {
        return $this->name;
    }

    public function getDescriptionSelect2Attribute()
    {
        return $this->name;
    }

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    public function branchOffice()
    {
        return $this->belongsTo(BranchOffice::class);
    }

    public function paymentTerm()
    {
        return $this->belongsTo(PaymentTerm::class);
    }

    public function paymentWay()
    {
        return $this->belongsTo(PaymentWay::class);
    }

    public function paymentMethod()
    {
        return $this->belongsTo(PaymentMethod::class);
    }

    public function cfdiUse()
    {
        return $this->belongsTo(CfdiUse::class);
    }

    public function salesperson()
    {
        return $this->belongsTo(Salesperson::class);
    }

    public function currency()
    {
        return $this->belongsTo(Currency::class);
    }

    public function documentType()
    {
        return $this->belongsTo(DocumentType::class);
    }

    public function customerQuotationLines()
    {
        return $this->hasMany(CustomerQuotationLine::class);
    }

    public function customerActiveQuotationLines()
    {
        return $this->hasMany(CustomerQuotationLine::class)->where('status','=','1');
    }

    public function customerQuotationTaxes()
    {
        return $this->hasMany(CustomerQuotationTax::class);
    }

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

    public function customerInvoice()
    {
        return $this->hasOne(CustomerInvoice::class)->whereNotIn('status', [CustomerInvoice::DRAFT, CustomerInvoice::CANCEL]);
    }

    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    public function taxRegimenCustomer()
    {
        return $this->belongsTo(TaxRegimen::class, 'tax_regimen_customer_id');
    }

    public function customerRemission()
    {
        return $this->hasOne(CustomerRemission::class)->whereNotIn('status', [CustomerRemission::CANCEL]);
    }
}
