<?php

namespace App\Models\Accounts\Company;

use App\Traits\Media;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Company extends Model
{
    use HasFactory, SoftDeletes, Sortable, Media;

    protected $table = 'ac_companies';

    protected $dates = ['deleted_at'];

    protected $fillable = ['domain', 'enabled'];

    /**
     * Sortable columns.
     *
     * @var array
     */
    public $sortable = ['name', 'domain', 'email', 'enabled', 'created_at'];

    public function accounts()
    {
        return $this->hasMany('App\Models\Accounts\Banking\Account');
    }

    public function bill_histories()
    {
        return $this->hasMany('App\Models\Accounts\Expense\BillHistory');
    }

    public function bill_items()
    {
        return $this->hasMany('App\Models\Accounts\Expense\BillItem');
    }

    public function bill_payments()
    {
        return $this->hasMany('App\Models\Accounts\Expense\BillPayment');
    }

    public function bill_statuses()
    {
        return $this->hasMany('App\Models\Accounts\Expense\BillStatus');
    }

    public function bills()
    {
        return $this->hasMany('App\Models\Accounts\Expense\Bill');
    }

    public function categories()
    {
        return $this->hasMany('App\Models\Accounts\Setting\Category');
    }

    public function currencies()
    {
        return $this->hasMany('App\Models\Accounts\Setting\Currency');
    }

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

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

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

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

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

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

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

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

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

    public function settings()
    {
        return $this->hasMany('App\Models\Accounts\Setting\Setting');
    }

    public function taxes()
    {
        return $this->hasMany('App\Models\Accounts\Setting\Tax');
    }

    public function transfers()
    {
        return $this->hasMany('App\Models\Accounts\Banking\Transfer');
    }

    public function users()
    {
        return $this->morphedByMany('App\User', 'user', 'ac_user_companies', 'company_id', 'user_id');
    }

    public function vendors()
    {
        return $this->hasMany('App\Models\Accounts\Expense\Vendor');
    }

     public function scopeEnabled($query)
    {
        return $query->where('enabled', 1);
    }

    public function setSettings()
    {
        
        $settings = $this->settings;

        foreach ($settings as $setting) {
            list($group, $key) = explode('.', $setting->getAttribute('key'));

            // Load only general settings
            if ($group != 'general') {
                continue;
            }

            $value = $setting->getAttribute('value');

            if (($key == 'company_logo') && empty($value)) {
                $value = 'public/img/company.png';
            }

            $this->setAttribute($key, $value);
        }

        // Set default default company logo if empty
        if ($this->getAttribute('company_logo') == '') {
            $this->setAttribute('company_logo', 'public/img/company.png');
        }
    }

    /**
     * Define the filter provider globally.
     *
     * @return ModelFilter
     */
    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);
    }

    /**
     * Scope to get all rows filtered, sorted and paginated.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param $sort
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeCollect($query, $sort = 'name')
    {
        $request = request();

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

        return Company::select('ac_companies.*','ac_user_companies.user_id as pivot_user_id','ac_user_companies.company_id as pivot_company_id')->join('ac_user_companies','ac_companies.id','=','ac_user_companies.company_id')->where('ac_user_companies.user_id',Auth::user()->id)->filter($input)->sortable($sort)->paginate($limit);
    }

    /**
     * Sort by company name
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param $direction
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function nameSortable($query, $direction)
    {
        return $query->join('ac_settings', 'ac_companies.id', '=', 'ac_settings.company_id')
            ->where('key', 'general.company_name')
            ->orderBy('value', $direction)
            ->select('ac_companies.*');
    }

    /**
     * Sort by company email
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param $direction
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function emailSortable($query, $direction)
    {
        return $query->join('ac_settings', 'companies.id', '=', 'ac_settings.company_id')
            ->where('key', 'general.company_email')
            ->orderBy('value', $direction)
            ->select('companies.*');
    }

    /**
     * Get the current balance.
     *
     * @return string
     */
    public function getCompanyLogoAttribute()
    {
        return $this->getMedia('company_logo')->last();
    }
}
