<?php

namespace Mtc\Plugins\NewsletterSignup\Classes;

use App\Casts\OptionalEncrypted;
use App\Src\Encryption;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * Class MailList
 * Eloquent model for newsletter subscriber table
 *
 * @package Mtc\Plugins\NewsletterSignup\Classes
 */
class MailList extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'emails_lists_mails';

    /**
     * @var string[] $fillable mass assignable variables
     */
    protected $fillable = [
        'list_id',
        'email',
        'firstname',
        'surname',
    ];

    protected $casts = [
        'email' => OptionalEncrypted::class,
        'firstname' => OptionalEncrypted::class,
        'surname' => OptionalEncrypted::class,
    ];

    public static $searchable = [
        'email',
    ];

    /**
     * No timestamps on model
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * Extend object boot
     */
    public static function boot() : void
    {
        parent::boot();

        self::saved(function (self $model) {
            Encryption::updateHashes($model);
        });
    }

    /**
     * Add the scope of validating the hash
     *
     * @param Builder $query query builder
     * @param string $hash provided hash
     * @return $this|Builder
     */
    public function scopeWithHash(Builder $query, $hash)
    {
        return $query->whereRaw("MD5(CONCAT(email_hash,'" . NewsletterSignUp::$salt . "')) = ?", [$hash]);
    }

}