<?php

namespace Mtc\Plugins\Clinic\Src\Models;

use App\Casts\OptionalEncrypted;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Mtc\Modules\Members\Models\Member;
use Mtc\Shop\Item;

/**
 * Accessors
 *
 * @property int $id
 * @property int $member_id
 * @property int $item_id
 * @property string $date_from
 * @property string $date_to
 * @property string $notes
 *
 * @property Carbon $created_at
 * @property Carbon $updated_at
 *
 * @property Member $member
 * @property Item $item
 * @property Item\Size $size
 */
class Treatment extends Model
{
    protected $table = 'patient_treatments';

    protected $fillable = [
        'member_id',
        'item_id',
        'size_id',
        'date_from',
        'date_to',
        'notes',
    ];

    protected $casts = [
        'notes' => OptionalEncrypted::class,
    ];

    const STATUS_ACTIVE = 'active';
    const STATUS_PAST = 'past';
    const STATUS_FUTURE = 'future';

    /**
     * @return BelongsTo
     */
    public function member(): BelongsTo
    {
        return $this->belongsTo(Member::class, 'member_id');
    }

    /**
     * @return BelongsTo
     */
    public function item(): BelongsTo
    {
        return $this->belongsTo(Item::class, 'item_id');
    }

    /**
     * @return BelongsTo
     */
    public function size(): BelongsTo
    {
        return $this->belongsTo(Item\Size::class, 'size_id');
    }

    /**
     * Simple validator
     *
     * @param array $input
     * @return array
     */
    public static function validate(array $input): array
    {
        $required = [
            'member_id',
            'item_id',
            'date_from',
        ];

        $errors = [];

        foreach ($required as $field) {
            if (empty($input[$field])) {
                $errors[$field] = 'This field is required';
            }
        }
        if (!empty($errors)) {
            return $errors;
        }
        if (empty($input['date_to'])) {
            return [];
        }

        $dateFrom = Carbon::createFromFormat('d/m/Y', $input['date_from']);
        $dateTo = Carbon::createFromFormat('d/m/Y', $input['date_to']);
        if ($dateTo < $dateFrom) {
            $errors['date_to'] = 'End date cannot be before start date!';
        }
        return $errors;
    }

    /**
     * Resolve status based on dates
     *
     * @return string
     */
    public function getStatus(): string
    {
        $today = Carbon::now()->format('Y-m-d');
        if (!empty($this->date_to)) {
            if ($this->date_to < $today) {
                return self::STATUS_PAST;
            }
        }
        if ($this->date_from > $today) {
            return self::STATUS_FUTURE;
        }
        return self::STATUS_ACTIVE;
    }
}