<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\User;

class Pesanan extends Model
{
    protected $table = 'pesanans';

    protected $fillable = [
        'user_id',
        'ekspedisi_id',
        'kurir_id',
        'provinsi_id',
        'kota_id',
        'kecamatan_id',
        'desa_id',
        'kode_pos',
        'no_resi',           // ← tambah no_resi
        'alamat_tujuan',     // ← tambah
        'kota',              // ← tambah
        'tanggal_pesanan',
        'total_harga',
        'status',
        'metode_pembayaran',
    ];

    // ── Relasi customer ──────────────────────────────────────
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // ── Relasi kurir/ekspedisi ───────────────────────────────
    public function ekspedisi()
    {
        return $this->belongsTo(\App\Models\Ekspedisi::class, 'ekspedisi_id'); // Atau hapus jika tak dipakai
    }

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

    // ── Relasi Wilayah (IndoRegion) ────────────────────────────
    public function provinsi()
    {
        return $this->belongsTo(\App\Models\Province::class, 'provinsi_id');
    }

    public function regency()
    {
        return $this->belongsTo(\App\Models\Regency::class, 'kota_id');
    }

    public function kecamatan()
    {
        return $this->belongsTo(\App\Models\District::class, 'kecamatan_id');
    }

    public function desa()
    {
        return $this->belongsTo(\App\Models\Village::class, 'desa_id');
    }

    // ── Relasi detail & pembayaran ───────────────────────────
    public function detailPesanans()
    {
        return $this->hasMany(DetailPesanan::class);
    }

    public function pembayaran()
    {
        return $this->hasOne(Pembayaran::class);
    }

    // ── Scope status ─────────────────────────────────────────
    public function scopeMenunggu($query)
    {
        return $query->where('status', 'menunggu');
    }

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

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

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