<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ProofSubmission extends Model
{
    use HasFactory;

    protected $fillable = [
        'booking_item_id',
        'submitted_by',
        'reference',
        'attempt_number',
        'sla_due_at',
        'sla_met',
        'captured_at',
        'latitude',
        'longitude',
        'status',
        'notes',
        'reviewed_by',
        'reviewed_at',
        'review_notes',
    ];

    protected $casts = [
        'sla_due_at'  => 'datetime',
        'captured_at' => 'datetime',
        'reviewed_at' => 'datetime',
        'sla_met'     => 'boolean',
        'latitude'    => 'decimal:7',
        'longitude'   => 'decimal:7',
    ];

    // ============================================================
    // Boot — auto generate reference
    // ============================================================
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($proof) {
            if (empty($proof->reference)) {
                $latest = static::latest('id')->first();
                $next   = $latest ? $latest->id + 1 : 1;
                $proof->reference = 'PRF-' . str_pad($next, 6, '0', STR_PAD_LEFT);
            }
        });
    }

    // ============================================================
    // Scopes
    // ============================================================
    public function scopePassed($query)
    {
        return $query->where('status', 'passed');
    }

    public function scopeFailed($query)
    {
        return $query->where('status', 'failed');
    }

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeManualReview($query)
    {
        return $query->where('status', 'manual_review');
    }

    // ============================================================
    // Helpers
    // ============================================================
    public function isPassed(): bool
    {
        return $this->status === 'passed';
    }

    public function isFailed(): bool
    {
        return $this->status === 'failed';
    }

    public function isPending(): bool
    {
        return $this->status === 'pending';
    }

    public function isUnderReview(): bool
    {
        return $this->status === 'manual_review';
    }

    public function isSlaBreached(): bool
    {
        if (!$this->sla_due_at) return false;
        $submittedAt = $this->created_at;
        return $submittedAt->isAfter($this->sla_due_at);
    }

    public function getStatusBadgeClass(): string
    {
        return match($this->status) {
            'passed',
            'approved'       => 'nx-badge-good',
            'pending',
            'submitted',
            'auto_validating',
            'manual_review'  => 'nx-badge-warn',
            'failed',
            'rejected'       => 'nx-badge-danger',
            default          => 'nx-badge',
        };
    }

    public function getPhotoCount(): int
    {
        return $this->media()->where('type', 'photo')->count();
    }

    public function hasPlaybackLog(): bool
    {
        return $this->media()->where('type', 'playback_log')->exists();
    }

    public function allValidationsPassed(): bool
    {
        return $this->validations()->where('passed', false)->doesntExist();
    }

    // ============================================================
    // Relationships
    // ============================================================
    public function bookingItem()
    {
        return $this->belongsTo(BookingItem::class);
    }

    public function submittedBy()
    {
        return $this->belongsTo(User::class, 'submitted_by');
    }

    public function reviewedBy()
    {
        return $this->belongsTo(User::class, 'reviewed_by');
    }

    public function media()
    {
        return $this->hasMany(ProofMedia::class);
    }

    public function validations()
    {
        return $this->hasMany(ProofValidation::class);
    }

    public function verificationReview()
    {
        return $this->hasOne(VerificationReview::class);
    }
}