<?php namespace Tussendoor\Reloadify\Models\AbandonedCart;

use ReloadifyScoped\Carbon\Carbon;
use ReloadifyScoped\Illuminate\Database\Eloquent\Model;
use Tussendoor\Reloadify\Concerns\Http\IsFilterable;

class AbandonedCart extends Model
{

    use IsFilterable;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'reloadify_carts';
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'hash',
        'currency',
        'price',
        'recovery_url',
        'product_ids',
        'product_data',
        'created_at_gmt',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'hash',
        'product_data',
    ];

    /**
     * Get the meta relationship
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMAny
     */
    public function meta()
    {
        return $this->hasMany(AbandonedCartMeta::class, 'cart_id');
    }
    
    /**
     * Get specific meta data by key
     *
     * @param  string $key
     * @param  string $default
     * @return string
     */
    public function get_meta(string $key, string $default = '') : string
    {
        $meta = $this->meta()->where('meta_key', $key)->first();
        return !empty($meta) ? $meta->meta_value : $default;
    }
    
    /**
     * Return array while getting the product_ids property
     *
     * @param  string $value
     * @return array
     */
    public function getProductIdsAttribute(string $value)
    {
        return json_decode($value, true);
    }

    /**
     * When the updateTimestamps is called by the parent we set the created_at_gmt attribute
     * We also fire the parent method to set the original timestamps
     * 
     * @return void
     */
    public function updateTimestamps()
    {
        parent::updateTimestamps();

        // Set the created_at_gmt attribute when its a new cart and the created_at_gmt is not dirty
        if (!$this->exists && !$this->isDirty('created_at_gmt')) {
            $this->created_at_gmt = Carbon::now('GMT');
        }
    }
}