<?php

namespace App\Models;

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

class Address extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'province_code',
        'city_code',
        'district_code',
        'village_code',
        'street',
        'address_detail',
        'latitude',
        'longitude',
        'recipient_name',
        'phone',
    ];

    protected $casts = [
        'latitude' => 'float',
        'longitude' => 'float',
    ];

    /**
     * Relasi ke User
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * RELASI INDONESIA REGION (LARAVOLT)
     */
    public function province(): BelongsTo
    {
        return $this->belongsTo(\Laravolt\Indonesia\Models\Province::class, 'province_code', 'code');
    }

    public function city(): BelongsTo
    {
        return $this->belongsTo(\Laravolt\Indonesia\Models\City::class, 'city_code', 'code');
    }

    public function district(): BelongsTo
    {
        return $this->belongsTo(\Laravolt\Indonesia\Models\District::class, 'district_code', 'code');
    }

    public function village(): BelongsTo
    {
        return $this->belongsTo(\Laravolt\Indonesia\Models\Village::class, 'village_code', 'code');
    }

    /**
     * Helper: alamat lengkap
     */
    public function getFullAddressAttribute(): string
    {
        $parts = [
            $this->street,
            $this->address_detail,
            optional($this->village)->name,
            optional($this->district)->name,
            optional($this->city)->name,
            optional($this->province)->name,
        ];

        return implode(', ', array_filter($parts));
    }

    /**
     * Helper: nama penerima dengan nomor telepon
     */
    public function getRecipientInfoAttribute(): string
    {
        return $this->recipient_name . ' - ' . $this->phone;
    }
}
