<?php

namespace App\Http\Controllers;

use App\Models\Payment;
use App\Models\Expense;
use Illuminate\Http\Request;
use Carbon\Carbon;

class PembukuanController extends Controller
{
    public function index(Request $request)
    {
        // ===============================
        // FILTER TANGGAL
        // ===============================
        $startDate = $request->start_date
            ? Carbon::parse($request->start_date)->startOfDay()
            : now()->startOfMonth();

        $endDate = $request->end_date
            ? Carbon::parse($request->end_date)->endOfDay()
            : now()->endOfDay();

        // ===============================
        // AMBIL PEMASUKAN (DARI PAYMENTS)
        // ===============================
        $payments = Payment::with('order')
            ->whereBetween('created_at', [$startDate, $endDate])
            ->get()
            ->map(function ($payment) {
                return [
                    'tanggal' => $payment->created_at,
                    'keterangan' => 'Pembayaran Invoice #' . ($payment->order->invoice_number ?? '-'),
                    'debit' => (float) $payment->amount,
                    'kredit' => 0,
                ];
            });

        // ===============================
        // AMBIL PENGELUARAN (DARI EXPENSES)
        // ===============================
        $expenses = Expense::whereBetween('created_at', [$startDate, $endDate])
            ->get()
            ->map(function ($expense) {
                return [
                    'tanggal' => $expense->created_at,
                    'keterangan' => $expense->keterangan ?? 'Pengeluaran',
                    'debit' => 0,
                    'kredit' => (float) $expense->jumlah,
                ];
            });

        // ===============================
        // GABUNGKAN & URUTKAN
        // ===============================
        $data = $payments
            ->merge($expenses)
            ->sortBy('tanggal')
            ->values();

        // ===============================
        // HITUNG SALDO BERJALAN
        // ===============================
        $saldo = 0;

        $data = $data->map(function ($row) use (&$saldo) {
            $saldo += $row['debit'];
            $saldo -= $row['kredit'];
            $row['saldo'] = $saldo;
            return $row;
        });

        return view('pages.pembukuan.index', [
            'title' => 'Buku Besar',
            'data' => $data,
            'startDate' => $startDate->format('Y-m-d'),
            'endDate' => $endDate->format('Y-m-d'),
        ]);
    }
}