<?php

namespace MtcPharmacy\OutOfStockNotify\Classes;

use Illuminate\Database\Eloquent\Model;
use Mtc\Shop\Item as ShopItem;
use Mtc\Shop\Item\BelongsToItem;


class OutOfStockNotification extends Model
{
    use BelongsToItem;

    protected $table = 'items__out_of_stock_notifications';


    public function scopePending($query)
    {
        return $query->whereNull('notified_at');
    }


    public function markNotified()
    {
        $this->notified_at = date('c');
        $this->save();
    }


    public function validate() : array
    {
        $errors = [];

        if (! filter_var($this->email, FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = 'Invalid email.';
        }

        $shop_item = ShopItem::find($this->item_id);
        if (! $shop_item) {
            $errors['item_id'] = 'Invalid item ID.';
        }

        if (! isset($_COOKIE[config('session.cookie')])) {
            $errors['request'] = 'Invalid.';
        }

        return $errors;
    }
}
