<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Validator;

class LicenseKey extends BaseModel
{
    use HasFactory, Notifiable;

    protected $table = 'license_keys';
    protected $fillable = ['id', 'resource', 'key', 'start_date', 'end_date'];

    public function PostKey($formvalues, $userid, $now)
    {
        $status = [];
        $formvalues['id'] = null;
        $rules = [
            'resource' => 'required|string|max:255',
            'key' => 'required|string|max:255|unique:license_keys,key',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
        ];

        $validator = Validator::make($formvalues, $rules);

        if ($validator->fails()) {
            $status['error_message'] = "Validation failed";
            $status['errors'] = $validator->errors();
            return $status;
        }
        self::where('resource', $formvalues['resource'])->delete();
        $savekey = $this->processPost($this, $formvalues, $userid, $now);

        if ($savekey) {
            $status['success_message'] = "License Key saving is successful";
        } else {
            $status['error_message'] = "License Key saving failed";
        }

        return $status;
    }
}
