<?php

namespace App\Http\Controllers;

use App\Models\Book;
use App\Models\Category;
use App\Models\Loan;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class KatalogController extends Controller
{
    public function index(Request $request)
    {
        $user = Auth::user();

        $isBanned = false;
        if ($user && $user->role === 'siswa') {
            // Check for overdue loans
            $hasOverdue = Loan::where('user_id', $user->id)
                ->whereIn('status', ['Dipinjam', 'Terlambat'])
                ->where('due_at', '<', now())
                ->exists();

            $isBanned = $hasOverdue || ($user->is_banned ?? false);
        }

        $filters = $request->only(['search', 'kategori', 'tahun', 'penulis']);
        
        // Query books with filters
        $query = Book::with('category');

        if ($request->filled('search')) {
            $query->where('judul', 'like', '%' . $request->search . '%');
        }

        if ($request->filled('kategori')) {
            $query->whereHas('category', function($q) use ($request) {
                $q->where('name', $request->kategori);
            });
        }

        if ($request->filled('tahun')) {
            $query->where('tahun', $request->tahun);
        }

        if ($request->filled('penulis')) {
            $query->where('penulis', $request->penulis);
        }

        $semuaBuku = $query->latest()->get();

        // Get filter options dynamically
        $filterOptions = [
            'kategori' => Category::pluck('name')->unique()->sort()->values(),
            'tahun' => Book::pluck('tahun')->unique()->sortDesc()->values(),
            'penulis' => Book::pluck('penulis')->unique()->sort()->values(),
        ];

        return view('katalog.index', [
            'semuaBuku' => $semuaBuku,
            'filterOptions' => $filterOptions,
            'input' => $filters,
            'pageTitle' => 'Katalog Buku',
            'mode' => 'umum',
            'isBanned' => $isBanned,
        ]);
    }
}