<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use App\Models\FinancialLedger; // KUNCI UTAMA 1: Import Model Buku Kas
use App\Models\Room; // Pastikan Model Room juga ter-import

#[Fillable([
    'booking_code',
    'user_id',
    'room_id',
    'survey_date',
    'booking_fee',
    'payment_method',
    'payment_status',
    'survey_status',
    'payment_expired_at',
    'kategori_properti',
    'refund_status',
    'refund_proof',
])]

class Transaction extends Model
{
    use HasFactory;

    protected static function booted()
    {
        // 1. EVENT SAVING: Terjadi SEBELUM data disimpan ke database
        static::saving(function ($transaction) {
            // Jika admin ubah status bayar jadi LUNAS, dan survei masih pending/kosong
            if (
                (str_contains($transaction->payment_status, 'Lunas') || $transaction->payment_status === 'lunas') &&
                ($transaction->survey_status === 'pending' || empty($transaction->survey_status))
            ) {
                // Otomatis ubah status surveinya
                $transaction->survey_status = 'Dalam Proses Booking (Menunggu Jadwal Survei)';
            }
        });

        // 2. EVENT UPDATED: Terjadi SETELAH data berhasil diperbarui di database
        static::updated(function ($transaction) {

            // A. LOGIKA LAMA: Buka kembali gembok kamar jika batal atau gagal bayar
            if (
                str_contains($transaction->survey_status, 'Batal') ||
                str_contains($transaction->payment_status, 'Kedaluwarsa') ||
                $transaction->payment_status === 'failed' ||
                in_array($transaction->survey_status, ['batal_tenant', 'batal_owner', 'batal_no_show'])
            ) {
                if ($transaction->room_id) {
                    Room::where('id', $transaction->room_id)->update(['is_available' => true]);
                }
            }

            // B. LOGIKA BARU: Pencatatan Uang Masuk ke Buku Kas (Booking Fee)
            if ($transaction->isDirty('payment_status') && $transaction->payment_status === 'lunas') {
                FinancialLedger::create([
                    'transaction_date' => now(),
                    'reference_code' => $transaction->booking_code,
                    'type' => 'in', // Arus kas masuk
                    'category' => 'booking_fee',
                    'amount' => $transaction->booking_fee,
                    'description' => "Booking Fee Masuk - Properti: {$transaction->boardingHouse->name} (Penyewa: {$transaction->user->name})",
                ]);
            }

            // C. LOGIKA BARU: Pencatatan Uang Keluar ke Buku Kas (Refund)
            if ($transaction->isDirty('refund_status') && $transaction->refund_status === 'selesai') {

                // Kalkulasi Refund: Jika Batal Tenant (Tidak Cocok) = 50%, Selain itu = 100%
                $refundAmount = ($transaction->survey_status === 'batal_tenant')
                    ? ($transaction->booking_fee / 2)
                    : $transaction->booking_fee;

                FinancialLedger::create([
                    'transaction_date' => now(),
                    'reference_code' => $transaction->booking_code,
                    'type' => 'out', // Arus kas keluar
                    'category' => 'refund_tenant',
                    'amount' => $refundAmount,
                    'description' => "Refund Booking - Properti: {$transaction->boardingHouse->name} (Penyewa: {$transaction->user->name})",
                ]);
            }
        });
    }

    protected function casts(): array
    {
        return [
            'survey_date' => 'date',
            'payment_expired_at' => 'datetime',
        ];
    }

    // Hubungan ke data penyewa (User)
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // Relasi ke Properti Kos / Kontrakan
    public function boardingHouse()
    {
        return $this->belongsTo(BoardingHouse::class);
    }

    // Hubungan ke data kamar (Room)
    public function room()
    {
        return $this->belongsTo(Room::class);
    }
}
