<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\ApprovalHierarchies;
use App\Models\ConstructionDepartment\ConstructionRoadCutting;

class Status extends Model
{
    use HasFactory;

    protected $table = 'statuses';
    protected $primaryKey = 'id';
    public $timestamps = true;

    protected $fillable = [
        'service_id',
        'table_id',
        'department_id',
        'user_id',
        'status',
        'defect_factor',
        'offlinereceipt',
        'document_upload',
        'receipt_status',          // 0 = pending, 1 = verified, 2 = rejected
        'receipt_remark',          // remarks for verification
        'receipt_verifier_id',     // assigned verifier
        'receipt_verified_by',      // actual verifier
        'receipt_uploaded_at',
        'fees_amount',
    ];

    public function constructionRoadCutting()
    {
        return $this->belongsTo(ConstructionRoadCutting::class, 'table_id', 'id');
    }

    public function approvalhierarchies()
    {
        return $this->hasMany(ApprovalHierarchies::class, 'status_id', 'id');
    }

    public function latestApprovalHierarchies()
    {
        return $this->hasMany(ApprovalHierarchies::class, 'status_id', 'id')
            ->where('status', 1)
            ->orderBy('created_at', 'desc');
    }

    public function getStatusBadgeAttribute()
    {
        switch ($this->status) {
            case 1:
                return '<span class="badge bg-success">Approved</span>';
            case 2:
                return '<span class="badge bg-danger">Rejected</span>';
            default:
                return '<span class="badge bg-warning text-dark">Pending</span>';
        }
    }

    public function serviceName()
    {
        return $this->belongsTo(ServiceName::class, 'service_id', 'service_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }


    public function receiptVerifier()
    {
        return $this->belongsTo(User::class, 'receipt_verifier_id', 'id');
    }

    public function receiptVerifiedBy()
    {
        return $this->belongsTo(User::class, 'receipt_verified_by', 'id');
    }

    public function getReceiptBadgeAttribute()
    {
        return match($this->receipt_status) {
            1 => '<span class="badge bg-success">Verified</span>',
            2 => '<span class="badge bg-danger">Rejected</span>',
            default => '<span class="badge bg-warning text-dark">Verification Pending</span>',
        };
    }


}
