<?php

namespace Mtc\Plugins\WeightVerification\Src\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Mtc\Modules\Members\Models\Member;
use Mtc\Plugins\Clinic\Src\Models\PatientFile;
use Mtc\Shop\Order;

/**
 * @property int $id
 * @property int $order_id
 * @property int $member_id
 * @property string $status
 * @property int|null $front_file_id
 * @property int|null $side_file_id
 * @property Carbon|null $submitted_at
 * @property Carbon|null $reviewed_at
 * @property int|null $reviewed_by
 * @property string|null $decline_reason
 */
class WeightVerification extends Model
{
    protected $table = 'weight_verifications';

    /**
     * Module tag written to PatientFile.module so weight photos are traceable
     * and findable by the Clinic retention/cleanup (PatientFile::deleteFiles).
     */
    const AUDIT_MODULE = 'WeightVerification';

    protected $fillable = [
        'order_id',
        'member_id',
        'status',
        'front_file_id',
        'side_file_id',
        'submitted_at',
        'reviewed_at',
        'reviewed_by',
        'decline_reason',
    ];

    protected $casts = [
        'submitted_at' => 'datetime',
        'reviewed_at' => 'datetime',
    ];

    /**
     * Awaiting the patient's photos (initial state).
     */
    const STATUS_PENDING = 'pending';

    /**
     * Photos uploaded, awaiting prescriber review.
     */
    const STATUS_SUBMITTED = 'submitted';

    /**
     * Prescriber approved the photos (item approval proceeds).
     */
    const STATUS_APPROVED = 'approved';

    /**
     * Prescriber requested new photos. Patient must resubmit.
     */
    const STATUS_RESUBMIT_REQUIRED = 'resubmit_required';

    /**
     * Statuses that require the patient to take action.
     */
    const ACTION_REQUIRED_STATUSES = [
        self::STATUS_PENDING,
        self::STATUS_RESUBMIT_REQUIRED,
    ];

    public function order(): BelongsTo
    {
        return $this->belongsTo(Order::class, 'order_id');
    }

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

    public function frontFile(): BelongsTo
    {
        return $this->belongsTo(PatientFile::class, 'front_file_id');
    }

    public function sideFile(): BelongsTo
    {
        return $this->belongsTo(PatientFile::class, 'side_file_id');
    }

    /**
     * Whether the patient still needs to do something.
     */
    public function getActionRequiredAttribute(): bool
    {
        return in_array($this->status, self::ACTION_REQUIRED_STATUSES, true);
    }

    /**
     * Whether the photos are uploaded and not (yet) sent back for resubmission.
     */
    public function isSubmitted(): bool
    {
        return in_array($this->status, [self::STATUS_SUBMITTED, self::STATUS_APPROVED], true);
    }

    public function getIsSubmittedAttribute(): bool
    {
        return $this->isSubmitted();
    }

    /**
     * Whether the prescriber has approved the photos.
     */
    public function getIsApprovedAttribute(): bool
    {
        return $this->status === self::STATUS_APPROVED;
    }

    /**
     * Whether the prescriber has sent the photos back for resubmission.
     */
    public function getIsResubmitRequiredAttribute(): bool
    {
        return $this->status === self::STATUS_RESUBMIT_REQUIRED;
    }

    /**
     * Human-readable status, e.g. "Resubmit Required".
     */
    public function getStatusLabelAttribute(): string
    {
        return ucwords(str_replace('_', ' ', (string) $this->status));
    }

    /**
     * Secure (admin-only) inline URL for the front photo.
     *
     * Root-relative on purpose: this is rendered from the legacy admin bootstrap
     * (shop/admin/ajax.php) where the absolute URL root wrongly includes the
     * current script path.
     */
    public function getFrontUrlAttribute(): ?string
    {
        return $this->front_file_id ? route('admin-file-get', [$this->front_file_id], false) : null;
    }

    /**
     * Secure (admin-only) inline URL for the side photo.
     */
    public function getSideUrlAttribute(): ?string
    {
        return $this->side_file_id ? route('admin-file-get', [$this->side_file_id], false) : null;
    }

    /**
     * Latest verification for a member.
     */
    public function scopeForMember(Builder $query, int $memberId): Builder
    {
        return $query->where('member_id', $memberId)
            ->orderByDesc('id');
    }
}
