<?php

namespace Mtc\Modules\BlackList\Classes;

use App\Casts\OptionalEncrypted;
use App\Src\Encryption;
use Illuminate\Database\Eloquent\Model;
use Mtc\Core\UkPostcode;

class BlackList extends Model
{
    public $timestamps = false;

    protected $fillable = [
        'email',
        'telephone',
        'address'
    ];

    protected $casts = [
        'email' => OptionalEncrypted::class,
        'telephone' => OptionalEncrypted::class,
        'address' => OptionalEncrypted::class,
    ];

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

    /**
     * Create hashes on save
     *
     * @return void
     */
    protected static function boot(): void
    {
        parent::boot();

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

    protected $table = 'black_list';

    const SOFT_BLACKLIST_FLAG = 1;
    const HARD_BLACKLIST_FLAG = 2;

    /**
     * @param array $fields
     * @return int
     */
    public function isBlacklisted(array $fields): int
    {
        // TODO:
        // normalize values
        $query = $this->select('id', 'hard_blacklist');
        foreach ($fields as $field => $value) {

            if ($field === 'address') {
                $postcode_normalized = new UkPostcode($value);
                $value = $postcode_normalized;
            }

            // Should not be checking the empty as the blacklist might contain empty DB fields
            if (!empty(trim($value))) {
                $query = $query->orWhere($field . '_hash', Encryption::makeHash($value));
            }
        }
        if ($query->count() === 0) {
            return 0;
        }
        if ($query->first()->hard_blacklist == 1) {
            return 2;
        }
        return 1;
    }
}