<?php

namespace Mtc\Core;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Mtc\Core\Models\CountryState;

/**
 * Generic Address Eloquent Model.
 *
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 * @version 17.10.2016.
 */
abstract class Address extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'type',
        'gender',
        'title',
        'firstname',
        'middle_name',
        'lastname',
        'address1',
        'address2',
        'city',
        'state',
        'country',
        'postcode',
        'notes'
    ];

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    // SCOPES

    /**
     * scope billing(). Filters billing addresses
     * @param $query
     * @return Builder
     */
    public function scopeBilling($query)
    {
        return $query->where('type', 'billing');
    }

    /**
     * scope shipping. Filters shipping addresses
     * @param $query
     * @return Builder
     */
    public function scopeShipping($query)
    {
        return $query->where('type', 'shipping');
    }


    /**
     * Validates Address to ensure input is valid
     * This is a standalone version of address validation
     * and does not consider a type as required.
     *
     * @param string[] $address Address input array
     * @return array list of validation errors
     * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
     * @version 25.01.2017.
     */
    public static function validate($address)
    {
        $errors = [];

        // The required values - these cannot be empty
        $required = [
            'firstname' => 'first name',
            'lastname' => 'last name',
            'address1' => 'address',
            'city' => 'city',
            'postcode' => 'postcode',
            'country' => 'country',
        ];

        $states = CountryState::getCountryStateList();

        //When dealing with a US address the state is required
        if (!empty($states[$address['country']])) {
            $required['billing_state'] = 'state';
        }

        //Required Fields checks
        foreach ($required as $key => $label) {
            $address[$key] = trim($address[$key]);
            if (empty($address[$key])) {
                $errors[$key] =  "Please enter your " . $label;
            }
        }

        //validate postcode
        if (empty($errors['postcode']) && preg_match('/[^ a-z0-9-]/i', $address['postcode'])) {
            $errors['postcode'] = 'Please enter a valid post code';
        }

        return $errors;
    }
}
