<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Peminjaman;
use App\Models\PembayaranDenda;
use App\Models\User;
use App\Models\Buku;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\FineExport;
use Carbon\Carbon;

class FineController extends Controller
{
    /**
     * Display denda list with filters and statistics
     */
    public function index(Request $request)
    {
        // Base query with payment summary
        $query = Peminjaman::with(['user', 'asetBuku.buku'])
            ->where('denda', '>', 0);
        
        // Filter by date range (tanggal kembali)
        if ($request->filled('dari_tanggal') && $request->filled('sampai_tanggal')) {
            $query->whereBetween('tanggal_kembali', [
                $request->dari_tanggal,
                $request->sampai_tanggal
            ]);
        }
        
        // Filter by user
        if ($request->filled('id_user')) {
            $query->where('id_user', $request->id_user);
        }
        
        // Filter by book
        if ($request->filled('id_buku')) {
            $query->whereHas('asetBuku', function($q) use ($request) {
                $q->where('id_buku', $request->id_buku);
            });
        }
        
        // Get data with pagination
        $denda = $query->latest('tanggal_kembali')->paginate(50);
        
        // Get payment summary for each item using view
        foreach ($denda as $item) {
            $summary = \DB::table('v_summary_pembayaran_denda')
                ->where('id_peminjaman', $item->id_peminjaman)
                ->first();
            
            $item->total_dibayar = $summary ? $summary->total_dibayar : 0;
            $item->sisa_denda = $summary ? $summary->sisa_denda : $item->denda;
            $item->status_bayar = $summary ? $summary->status_bayar : 'Belum Lunas';
        }
        
        // Filter by payment status (after enrichment)
        if ($request->filled('status')) {
            $denda = $denda->filter(function($item) use ($request) {
                return $item->status_bayar == $request->status;
            });
        }
        
        // Calculate statistics
        $allDenda = Peminjaman::where('denda', '>', 0)->get();
        $stats = [
            'total_denda' => $allDenda->sum('denda'),
            'total_items' => $allDenda->count(),
        ];
        
        // Calculate paid and outstanding from view
        $summaries = \DB::table('v_summary_pembayaran_denda')->get();
        $stats['sudah_dibayar'] = $summaries->sum('total_dibayar');
        $stats['belum_lunas'] = $summaries->where('status_bayar', 'Belum Lunas')->sum('sisa_denda');
        $stats['cicilan'] = $summaries->where('status_bayar', 'Cicilan')->sum('sisa_denda');
        
        // Data for filters
        $users = User::where('role', 'pengunjung')
            ->whereHas('peminjaman', function($q) {
                $q->where('denda', '>', 0);
            })
            ->orderBy('nama')
            ->get(['id_user', 'nama', 'username']);
        
        $buku = Buku::whereHas('asetBuku.peminjaman', function($q) {
                $q->where('denda', '>', 0);
            })
            ->orderBy('judul')
            ->get(['id_buku', 'judul']);
        
        
        // Determine view based on route prefix
        $view = request()->routeIs('petugas.*') ? 'petugas.laporan_denda' : 'admin.laporan.denda';
        $totalDendaBelumLunas = $stats['belum_lunas'] + $stats['cicilan'];
        
        return view($view, compact('denda', 'stats', 'users', 'buku', 'totalDendaBelumLunas'));
    }

    /**
     * Get denda info for modal
     */
    public function getDendaInfo($id_peminjaman)
    {
        $peminjaman = Peminjaman::findOrFail($id_peminjaman);
        
        $summary = \DB::table('v_summary_pembayaran_denda')
            ->where('id_peminjaman', $id_peminjaman)
            ->first();
        
        return response()->json([
            'id_peminjaman' => $id_peminjaman,
            'denda_total' => $peminjaman->denda,
            'sisa_denda' => $summary ? $summary->sisa_denda : $peminjaman->denda,
            'total_dibayar' => $summary ? $summary->total_dibayar : 0,
            'status_bayar' => $summary ? $summary->status_bayar : 'Belum Lunas',
        ]);
    }

    /**
     * Input payment for denda
     */
    public function inputPembayaran(Request $request, $id_peminjaman)
    {
        $request->validate([
            'nominal_bayar' => 'required|integer|min:1',
            'keterangan' => 'nullable|string|max:255',
        ]);
        
        $peminjaman = Peminjaman::findOrFail($id_peminjaman);
        
        // Get sisa denda dari view
        $summary = \DB::table('v_summary_pembayaran_denda')
            ->where('id_peminjaman', $id_peminjaman)
            ->first();
        
        $sisaDenda = $summary ? $summary->sisa_denda : $peminjaman->denda;
        
        // Validasi nominal tidak melebihi sisa
        if ($request->nominal_bayar > $sisaDenda) {
            return back()->with('error', 'Nominal pembayaran melebihi sisa denda!');
        }
        
        // Generate nomor kwitansi
        $nomorKwitansi = 'KWT-' . date('Ymd') . '-' . str_pad(
            \DB::table('pembayaran_denda')->whereDate('tanggal_bayar', today())->count() + 1,
            3, '0', STR_PAD_LEFT
        );
        
        // Insert pembayaran
        PembayaranDenda::create([
            'id_peminjaman' => $id_peminjaman,
            'nominal_bayar' => $request->nominal_bayar,
            'tanggal_bayar' => now(),
            'nomor_kwitansi' => $nomorKwitansi,
            'metode_bayar' => 'Cash',
            'diterima_oleh' => auth()->id(),
            'keterangan' => $request->keterangan ?? 'Pembayaran denda',
        ]);
        
        return back()->with('success', "Pembayaran berhasil! Nomor Kwitansi: {$nomorKwitansi}");
    }

    /**
     * Export to Excel
     */
    public function exportExcel(Request $request)
    {
        $query = Peminjaman::with(['user', 'asetBuku.buku'])
            ->where('denda', '>', 0);
        
        // Apply same filters
        if ($request->filled('dari_tanggal') && $request->filled('sampai_tanggal')) {
            $query->whereBetween('tanggal_kembali', [
                $request->dari_tanggal,
                $request->sampai_tanggal
            ]);
        }
        
        if ($request->filled('id_user')) {
            $query->where('id_user', $request->id_user);
        }
        
        if ($request->filled('id_buku')) {
            $query->whereHas('asetBuku', function($q) use ($request) {
                $q->where('id_buku', $request->id_buku);
            });
        }
        
        $denda = $query->latest('tanggal_kembali')->get();
        
        $filename = 'Laporan_Denda_' . date('YmdHis') . '.xlsx';
        
        return Excel::download(new FineExport($denda), $filename);
    }

    /**
     * Export to PDF
     */
    public function exportPDF(Request $request)
    {
        $query = Peminjaman::with(['user', 'asetBuku.buku'])
            ->where('denda', '>', 0);
        
        // Apply filters
        if ($request->filled('dari_tanggal') && $request->filled('sampai_tanggal')) {
            $query->whereBetween('tanggal_kembali', [
                $request->dari_tanggal,
                $request->sampai_tanggal
            ]);
        }
        
        if ($request->filled('id_user')) {
            $query->where('id_user', $request->id_user);
        }
        
        if ($request->filled('id_buku')) {
            $query->whereHas('asetBuku', function($q) use ($request) {
                $q->where('id_buku', $request->id_buku);
            });
        }
        
        $denda = $query->latest('tanggal_kembali')->get();
        
        // Enrich with payment data
        foreach ($denda as $item) {
            $summary = \DB::table('v_summary_pembayaran_denda')
                ->where('id_peminjaman', $item->id_peminjaman)
                ->first();
            
            $item->total_dibayar = $summary ? $summary->total_dibayar : 0;
            $item->sisa_denda = $summary ? $summary->sisa_denda : $item->denda;
            $item->status_bayar = $summary ? $summary->status_bayar : 'Belum Lunas';
        }
        
        $pdf = \PDF::loadView('admin.laporan.pdf.denda', [
            'denda' => $denda,
            'tanggal_cetak' => Carbon::now()->format('d/m/Y H:i')
        ]);
        
        $filename = 'Laporan_Denda_' . date('YmdHis') . '.pdf';
        
        return $pdf->download($filename);
    }
}
