<?php

namespace Mtc\Modules\Members\Classes;

use Mtc\Modules\Members\Models\Member;

/**
 * Class MemberDuplicateCheck
 *
 * @package Mtc\Modules\Members\Classes
 */
class MemberDuplicateCheck
{
    /**
     * Check if data has duplicates in existing member list
     *
     * @param $phone_number
     * @param $address_data
     * @return bool|string
     */
    public function hasDuplicates($phone_number, $address_data)
    {
        //if ($this->hasDuplicateAddress($address_data)) {
        //    return 'address';
        //}

        //if ($this->hasDuplicatePhone($phone_number)) {
        //    return 'phone';
        //}

        return false;
    }

    /**
     * Check if address gets a match
     *
     * @param $address_data
     * @return bool
     */
    private function hasDuplicateAddress($address_data)
    {



        return Member::query()
            ->whereHas('addresses', function ($query) use ($address_data) {
                return $query
                    ->whereRaw("REPLACE(SUBSTR(TRIM(`firstname`), 1, 4), ' ', '') LIKE REPLACE(SUBSTR(TRIM(?), 1, 4), ' ', '')", $address_data['firstname'])
                    ->whereRaw("REPLACE(`postcode`, ' ', '') LIKE REPLACE(?, ' ', '')", $address_data['postcode'])
                    ->whereRaw("REPLACE(`address1`, ' ', '') LIKE REPLACE(?, ' ', '')", $address_data['address1'])
                    ->whereRaw("REPLACE(`address2`, ' ', '') LIKE REPLACE(?, ' ', '')", $address_data['address2'])
                    ->whereRaw("REPLACE(`city`, ' ', '') LIKE REPLACE(?, ' ', '')", $address_data['city']);
            })
            ->exists();
    }

    /**
     * Check if phone number gets matched
     *
     * @param $phone_number
     * @return bool
     */
    private function hasDuplicatePhone($phone_number)
    {
        return !empty($phone_number)
            && Member::query()
                ->whereRaw("REPLACE(TRIM(`contact_no`), ' ', '') LIKE ?", '%' . substr(str_replace(' ', '', $phone_number), -10))
                ->exists();
    }
}
