<?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 DoubleOptInEmail
 * Eloquent model for double opt in email table
 *
 * @package Mtc\Plugins\NewsletterSignup\Classes
 */
class DoubleOptInEmail extends Model
{

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'emails_double_optin';

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

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

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

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

        self::created(function ($double_opt_in) {
            // When new double opt-in is created we need to send out an invite
            try {
                NewsletterSignUp::sendActivationEmail($double_opt_in);
            } catch (\Exception $exception) {
                error_log($exception->getMessage());
            }
        });

        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,'" . NewsletterSignUp::$salt . "')) = ?", [$hash]);
    }

}
