<?php

namespace App;

use DB;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Order extends Model
{
    protected $fillable = [
        'user_id',
        'first_name',
        'last_name',
        'document',
        'phone',
        'address',
        'city',
        'email',
        'feedback',
        'shipping_data',
        'shipping_method',
        'shipping_price',
        'payment_method',
        'payment_feedback',
        'status_id',
    ];

    protected $casts = [
        'shipping_data' => 'array',
    ];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function scopeConfirmed(Builder $query) {
        return $query->where('status_id', '!=', 0);
    }
    public function items()
    {
        return $this->hasMany('App\Item');
    }

    public function payment_method()
    {
        return $this->belongsTo('App\PaymentMethod');
    }

    public function getStatusAttribute()
    {
        return config('cms.statuses')[$this->status_id] ?? null;
    }

    public function getShortDateAttribute()
    {
        return $this->created_at->format('d/m/Y H:i');
    }

    public function getShortUpdatedDateAttribute()
    {
        return $this->updated_at->format('d/m/Y H:i');
    }

    public function getSubtotalAttribute()
    {
        return $this->items->sum(function($t) {
            return $t->qty * $t->price;
        });
    }

    public function getTotalAttribute()
    {
        return $this->subtotal + $this->shipping_price;
    }

    public function getSuccessAttribute()
    {
        return $this->status_id;
    }

    public function canProcess()
    {
        return $this->status_id < array_key_last(config('cms.statuses'));
    }

    public function getBancardAttribute()
    {
        return DB::table('bancard')->where('shop_process_id', $this->id)->first();
    }

    public function getFullNameAttribute()
    {
        return implode(' ', [$this->first_name, $this->last_name]);
    }
}
