<?php

namespace App\Http\Controllers\Admin;

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

class LaporanPeminjamanController extends Controller
{
    /**
     * Display active borrowing report
     */
    public function index(Request $request)
    {
        $query = Peminjaman::with(['user', 'asetBuku.buku'])
            ->where('status_peminjaman', 'Dipinjam');
        
        // Filter by date range
        if ($request->filled('dari_tanggal') && $request->filled('sampai_tanggal')) {
            $query->whereBetween('tanggal_pinjam', [
                $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);
            });
        }
        
        // Filter by status (jatuh tempo)
        if ($request->filled('status_jatuh_tempo')) {
            $now = Carbon::now();
            if ($request->status_jatuh_tempo == 'akan_jatuh_tempo') {
                // Akan jatuh tempo dalam 3 hari
                $query->whereBetween('tanggal_jatuh_tempo', [
                    $now,
                    $now->copy()->addDays(3)
                ]);
            } elseif ($request->status_jatuh_tempo == 'sudah_jatuh_tempo') {
                // Sudah jatuh tempo
                $query->where('tanggal_jatuh_tempo', '<', $now);
            }
        }
        
        $peminjaman = $query->latest('tanggal_pinjam')->paginate(50);
        
        // Data for filters
        $users = User::where('role', 'pengunjung')
            ->orderBy('nama')
            ->get(['id_user', 'nama', 'username']);
        
        $buku = Buku::orderBy('judul')->get(['id_buku', 'judul']);
        
        // Determine view based on route prefix
        $view = request()->routeIs('petugas.*') ? 'petugas.laporan_peminjaman' : 'admin.laporan.peminjaman';
        
        return view($view, compact('peminjaman', 'users', 'buku'));
    }
    
    /**
     * Display borrowing history (all records)
     */
    public function riwayat(Request $request)
    {
        $query = Peminjaman::with(['user', 'asetBuku.buku']);
        
        // Filter by date range
        if ($request->filled('dari_tanggal') && $request->filled('sampai_tanggal')) {
            $query->whereBetween('tanggal_pinjam', [
                $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);
            });
        }
        
        // Filter by status
        if ($request->filled('status')) {
            $query->where('status_peminjaman', $request->status);
        }
        
        $peminjaman = $query->latest('tanggal_pinjam')->paginate(50);
        
        // Calculate statistics
        $stats = [
            'total' => $query->count(),
            'dipinjam' => Peminjaman::where('status_peminjaman', 'Dipinjam')->count(),
            'dikembalikan' => Peminjaman::where('status_peminjaman', 'Dikembalikan')->count(),
        ];
        
        // Data for filters
        $users = User::where('role', 'pengunjung')
            ->orderBy('nama')
            ->get(['id_user', 'nama', 'username']);
        
        $buku = Buku::orderBy('judul')->get(['id_buku', 'judul']);
        
        // Determine view based on route prefix
        $view = request()->routeIs('petugas.*') ? 'petugas.laporan_riwayat' : 'admin.laporan.riwayat_peminjaman';
        
        return view($view, compact('peminjaman', 'users', 'buku', 'stats'));
    }
    
    /**
     * Export to Excel
     */
    public function exportExcel(Request $request)
    {
        $jenis = $request->jenis ?? 'aktif'; // aktif atau riwayat
        
        $query = Peminjaman::with(['user', 'asetBuku.buku']);
        
        if ($jenis == 'aktif') {
            $query->where('status_peminjaman', 'Dipinjam');
        }
        
        // Apply same filters
        if ($request->filled('dari_tanggal') && $request->filled('sampai_tanggal')) {
            $query->whereBetween('tanggal_pinjam', [
                $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);
            });
        }
        
        $peminjaman = $query->latest('tanggal_pinjam')->get();
        
        $filename = 'Laporan_Peminjaman_' . ($jenis == 'aktif' ? 'Aktif' : 'Riwayat') . '_' . date('YmdHis') . '.xlsx';
        
        return Excel::download(new PeminjamanExport($peminjaman), $filename);
    }
    
    /**
     * Export to PDF
     */
    public function exportPDF(Request $request)
    {
        $jenis = $request->jenis ?? 'aktif';
        
        $query = Peminjaman::with(['user', 'asetBuku.buku']);
        
        if ($jenis == 'aktif') {
            $query->where('status_peminjaman', 'Dipinjam');
        }
        
        // Apply filters
        if ($request->filled('dari_tanggal') && $request->filled('sampai_tanggal')) {
            $query->whereBetween('tanggal_pinjam', [
                $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);
            });
        }
        
        $peminjaman = $query->latest('tanggal_pinjam')->get();
        
        $pdf = \PDF::loadView('admin.laporan.pdf.peminjaman', [
            'peminjaman' => $peminjaman,
            'jenis' => $jenis,
            'tanggal_cetak' => Carbon::now()->format('d/m/Y H:i')
        ]);
        
        $filename = 'Laporan_Peminjaman_' . ($jenis == 'aktif' ? 'Aktif' : 'Riwayat') . '_' . date('YmdHis') . '.pdf';
        
        return $pdf->download($filename);
    }
}
