<?php

namespace App\Observers;

use App\Models\PurchaseReturn;
use App\Models\Account;
use App\Models\CashTransaction;
use App\Models\Purchase;
use Illuminate\Support\Facades\Log;

class PurchaseReturnObserver
{
    /**
     * Handle the PurchaseReturn "created" event.
     * Dijalankan setelah Retur tersimpan di database.
     */
    public function created(PurchaseReturn $purchaseReturn): void
    {
        try {
            // 1. Siapkan Akun
            // Akun Hutang Usaha (Liability) - Kode 2-1001
            $akunHutang = Account::where('code', '2-1001')->first();
            // Akun Persediaan Barang (Asset) - Kode 1-3001
            $akunPersediaan = Account::where('code', '1-3001')->first();

            if (!$akunHutang || !$akunPersediaan) {
                Log::error("Gagal Jurnal Retur: Akun 2-1001 atau 1-3001 tidak ditemukan.");
                return;
            }

            // 2. Buat Jurnal: DEBIT Hutang, KREDIT Persediaan
            // Karena kita pakai CashTransaction yang strukturnya (Source -> Dest),
            // Source = Kredit (Berkurang), Destination = Debit (Bertambah/Berkurang Pasiva)
            
            // Logika: Persediaan Berkurang (Source), Hutang Berkurang (Destination - Debit Pasiva)
            CashTransaction::create([
                'branch_id' => $purchaseReturn->branch_id,
                'transaction_date' => $purchaseReturn->return_date,
                'transaction_number' => $purchaseReturn->return_number,
                'type' => 'income', // Type Income agar Destination di-Debit
                'amount' => $purchaseReturn->total_amount,
                'source_account_id' => $akunPersediaan->id, // Kredit: Stok Keluar
                'destination_account_id' => $akunHutang->id, // Debit: Hutang Berkurang
                'note' => 'Retur Pembelian: ' . $purchaseReturn->return_number,
                'user_id' => auth()->id() ?? 1,
            ]);

            // 3. Update Sisa Hutang di Faktur Pembelian Asli (Jika ada referensinya)
            if ($purchaseReturn->purchase_id) {
                $purchase = Purchase::find($purchaseReturn->purchase_id);
                if ($purchase) {
                    // Kurangi sisa tagihan di tabel pembelian (asumsi ada kolom remaining_amount)
                    // Jika tidak ada kolom ini, berarti Bapak pakai tabel debt_payments terpisah
                    
                    // OPSI A: Jika pakai Payment, kita buat "Payment Dumy" bertipe Retur
                    /*
                    \App\Models\DebtPayment::create([
                        'purchase_id' => $purchase->id,
                        'amount' => $purchaseReturn->total_amount,
                        'payment_method' => 'return',
                        'note' => 'Potong Hutang via Retur ' . $purchaseReturn->return_number,
                        // ... field lain
                    ]);
                    */
                }
            }

        } catch (\Exception $e) {
            Log::error("Error Observer Retur: " . $e->getMessage());
        }
    }
}