<?php
/**
 * Order Info Object Eloquent model.
 * @version 27/10/16
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */

namespace Mtc\Shop\Order;

use App\Casts\OptionalEncrypted;
use App\Src\Encryption;
use Illuminate\Database\Eloquent\Model;
use Mtc\Shop\Order as ShopOrder;
use MtcPharmacy\Multisite\Classes\MultisiteSite;
use Mtc\Shop\Assessment\Assessment;


/**
 * Order Info Object Eloquent model.
 * Implements functionality for managing Shop Order Customer Info
 *
 * @version 27/10/16
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
class Info extends Model
{
    // Use trait that defines relationship to order
    use BelongsToOrder;

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

    /**
     * @var array The attributes that are mass assignable.
     */
    protected $fillable = [
        'order_id',
        'email',
        'phone_prefix',
        'contact_no',
        'message',
        'member_allergies',
        'member_medications',
        'member_conditions',
        'newsletter',
        'how_did_you_hear_about_us',
        'how_did_you_hear_about_us_text',
        'dob',
        'assessment_ids',
        'multisite__site_id',
    ];

    protected $casts = [
        'email' => OptionalEncrypted::class,
        'contact_no' => OptionalEncrypted::class,
        'dob' => OptionalEncrypted::class,
        'message' => OptionalEncrypted::class,
        'member_allergies' => OptionalEncrypted::class,
        'member_medications' => OptionalEncrypted::class,
        'member_conditions' => OptionalEncrypted::class,
    ];

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

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

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


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


    protected function site()
    {
        return $this->belongsTo(MultisiteSite::class, 'multisite__site_id');
    }


    public function getDisplayMemberMedications()
    {
        return implode(json_decode($this->member_medications, true), ', ');
    }


    public function getSiteOfOrigin() : string
    {
        return $this->site->name ?? '-';
    }


    public function getAssessments()
    {
        $assessments = [];

        if ($this->assessment_ids) {
            $records = (array)json_decode($this->assessment_ids);
            foreach ($records as $record) {
                $temp_assessment = Assessment::find($record->id);
                $assessments[] = $temp_assessment;
            }
        }

        return $assessments;
    }
}
