<?php

namespace App\Http\Controllers;

use App\Models\Transaksi;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class UserPernyataanController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * ===============================
     * PERNYATAAN / STATEMENT USER
     * ===============================
     */
    public function index(Request $request)
    {
        $userId = Auth::id();

        $transaksi     = collect();
        $totalDebit    = 0; // 🔴 uang keluar (withdraw)
        $totalKredit   = 0; // 🟢 uang masuk (deposit)

        Log::info('📄 Pernyataan dibuka', [
            'user_id' => $userId,
            'range'   => $request->daterange
        ]);

        if ($request->filled('daterange')) {

            try {
                [$startDate, $endDate] = explode(' - ', $request->daterange);

                $start = $this->parseDate($startDate)->startOfDay();
                $end   = $this->parseDate($endDate)->endOfDay();

                // ===============================
                // LIST TRANSAKSI
                // ===============================
                $transaksi = Transaksi::where('user_id', $userId)
                    ->whereBetween('created_at', [$start, $end])
                    ->orderByDesc('created_at')
                    ->paginate(20);

                // ===============================
                // KREDIT = DEPOSIT
                // ===============================
                $totalKredit = Transaksi::where('user_id', $userId)
                    ->where('type', 1) // deposit
                    ->whereBetween('created_at', [$start, $end])
                    ->sum('nominal');

                // ===============================
                // DEBIT = WITHDRAW
                // ===============================
                $totalDebit = Transaksi::where('user_id', $userId)
                    ->where('type', 2) // withdraw
                    ->whereBetween('created_at', [$start, $end])
                    ->sum('nominal');

                Log::info('📊 Rekap pernyataan', [
                    'user_id' => $userId,
                    'kredit'  => $totalKredit,
                    'debit'   => $totalDebit,
                ]);

            } catch (\Throwable $e) {

                Log::error('❌ Error pernyataan', [
                    'user_id' => $userId,
                    'error'   => $e->getMessage()
                ]);

                $transaksi   = collect();
                $totalDebit  = 0;
                $totalKredit = 0;
            }
        }

        return view('pernyataan', [
            'transaksi'    => $transaksi,
            'totalDebit'   => $totalDebit,     // withdraw
            'totalKredit'  => $totalKredit,    // deposit
            'saldoAkhir'   => $totalKredit - $totalDebit
        ]);
    }

    /**
     * ===============================
     * PARSE DATE
     * ===============================
     */
    private function parseDate(string $date): Carbon
    {
        foreach (['Y/m/d', 'd/m/Y'] as $format) {
            try {
                return Carbon::createFromFormat($format, trim($date));
            } catch (\Throwable $e) {}
        }

        throw new \Exception('Format tanggal tidak valid');
    }
}