<?php

namespace App\Models\Accounts\Income;

use App\Traits\Media;
use App\Traits\Incomes;
use App\Traits\DateTime;
use App\Traits\Currencies;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Invoice extends Model
{
    use HasFactory, Currencies, DateTime, Incomes, Media, Sortable;

    protected $table = 'invoices';

    public function getRouteKeyName()
    {

        return 'id';
    }

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['attachment'];

    protected $dates = ['deleted_at', 'invoiced_at', 'due_at'];

    /**
     * Attributes that should be mass-assignable.
     *
     * @var array
     */
    protected $fillable = ['company_id', 'invoice_number', 'order_number', 'invoice_status_code', 'invoiced_at', 'due_at', 'amount', 'currency_code', 'currency_rate', 'customer_id', 'customer_name', 'customer_email', 'customer_tax_number', 'customer_phone', 'customer_address', 'notes','cc_email','bcc_email','sendlater','net_term','customer_name_with_parent','shipping_address'];

    /**
     * Sortable columns.
     *
     * @var array
     */
    public $sortable = ['invoice_number', 'customer_name', 'amount', 'status' , 'invoiced_at', 'due_at', 'invoice_status_code'];

    /**
     * Searchable rules.
     *
     * @var array
     */
    protected $searchableColumns = [
        'invoice_number'   => 10,
        'invoiced_at'      => 10,
        'due_at'           => 10,
        'customer_name'    => 10,
        'customer_name_with_parent' => 10,
        'customer_email'   => 5,
        'customer_phone'   => 2,
        'customer_address' => 1,
        'notes'            => 2,
    ];

    /**
     * Clonable relationships.
     *
     * @var array
     */
    protected $cloneable_relations = ['items', 'totals','customer'];

    public function customer()
    {
        return $this->belongsTo('App\Models\Accounts\Income\Customer');
    }

    public function currency()
    {
        return $this->belongsTo('App\Models\Accounts\Setting\Currency', 'currency_code', 'code');
    }

    public function status()
    {
        return $this->belongsTo('App\Models\Accounts\Income\InvoiceStatus', 'invoice_status_code', 'code');
    }

    public function items()
    {
        return $this->hasMany('App\Models\Accounts\Income\InvoiceItem');
    }

    public function totals()
    {
        return $this->hasMany('App\Models\Accounts\Income\InvoiceTotal');
    }

    public function payments()
    {
        return $this->hasMany('App\Models\Accounts\Income\InvoicePayment');
    }

    public function discounts(){
        return $this->hasMany('App\Models\Accounts\Income\InvoiceDiscount');
    }

    public function payments_total()
    {
        return $this->payments()->selectRaw('invoice_payments.invoice_id , sum(amount) as paid_amount')->groupBy('invoice_payments.invoice_id');
    }

    public function invoice_customer()
    {
        return $this->hasMany('App\Models\Accounts\Income\InvoiceCustomers');
    }

    public function invoice_timesheet()
    {
        return $this->hasMany('App\Models\Accounts\Income\InvoiceTimesheet');
    }

    public function histories()
    {
        return $this->hasMany('App\Models\Accounts\Income\InvoiceHistory');
    }

    public function scopeDue($query, $date)
    {
        return $query->where('due_at', '=', $date);
    }

    public function scopeLatest($query)
    {
        return $query->orderBy('paid_at', 'desc');
    }

    public function scopeAccrued($query)
    {
        return $query->where('invoice_status_code', '<>', 'draft');
    }

    public function scopePaid($query)
    {
        return $query->where('invoice_status_code', '=', 'paid');
    }

    public function scopeNotPaid($query)
    {
        return $query->where('invoice_status_code', '<>', 'paid');
    }

    public function onCloning($src, $child = null)
    {
        $this->invoice_status_code = 'draft';
        $this->invoice_number = $this->getNextInvoiceNumber();
    }

    /**
     * Convert amount to double.
     *
     * @param  string  $value
     * @return void
     */
    public function setAmountAttribute($value)
    {
        $this->attributes['amount'] = (double) $value;
    }

    /**
     * Convert currency rate to double.
     *
     * @param  string  $value
     * @return void
     */
    public function setCurrencyRateAttribute($value)
    {
        $this->attributes['currency_rate'] = (double) $value;
    }

    /**
     * Get the current balance.
     *
     * @return string
     */
    public function getAttachmentAttribute($value)
    {
        if (!empty($value) && !$this->hasMedia('attachment')) {
            return $value;
        } elseif (!$this->hasMedia('attachment')) {
            return false;
        }

        return $this->getMedia('attachment')->last();
    }

    /* 
    * Get Parent Customer. 
    */

   // public function 

    public function modelFilter()
    {
        list($folder, $file) = explode('/', \Route::current()->uri());

        if (empty($folder) || empty($file)) {
            return $this->provideFilter();
        }

        $class = '\App\Filters\\' . ucfirst($folder) .'\\' . ucfirst($file);

        return $this->provideFilter($class);
    }

    public function scopeCollect($query, $sort = '')
    {
        $request = request();

        $input = $request->input();
        $limit = $request->get('limit', setting('general.list_limit', '25'));

        return $query->filter($input)->sortable($sort)->paginate($limit);
    }
}
