<?php

namespace App\Http\Controllers\SchoolAdmin\Library;

use App\Http\Controllers\Controller;
use App\Models\Book;
use App\Models\BookLoan;
use App\Models\LibraryFine;
use App\Models\User;
use Illuminate\Http\Request;

class BookLoanController extends Controller
{
    private const FINE_PER_DAY = 5.00; // KES 5 per day overdue

    public function index()
    {
        $loans = BookLoan::with(['book', 'user'])->latest()->paginate(15);
        return view('schooladmin.library.loans.index', compact('loans'));
    }

    public function create()
    {
        $books = Book::where('available_copies', '>', 0)->get();
        $users = User::whereIn('role', ['student', 'teacher'])->get();
        return view('schooladmin.library.loans.create', compact('books', 'users'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'book_id' => 'required|exists:books,id',
            'user_id' => 'required|exists:users,id',
            'due_date' => 'required|date|after:today',
        ]);

        $book = Book::findOrFail($validated['book_id']);

        if ($book->available_copies < 1) {
            return redirect()->back()->with('error', 'No copies available for this book.');
        }

        BookLoan::create([
            'book_id'     => $validated['book_id'],
            'user_id'     => $validated['user_id'],
            'borrowed_at' => now(),
            'due_date'    => $validated['due_date'],
            'status'      => 'active',
        ]);

        $book->decrement('available_copies');

        return redirect()->route('schooladmin.library.loans.index')
            ->with('success', 'Book issued successfully.');
    }

    public function show(BookLoan $loan)
    {
        $loan->load(['book', 'user', 'fines']);
        return view('schooladmin.library.loans.show', compact('loan'));
    }

    public function returnBook(BookLoan $loan)
    {
        if ($loan->status === 'returned') {
            return redirect()->route('schooladmin.library.loans.index')
                ->with('error', 'This book has already been returned.');
        }

        $loan->returned_at = now();
        $loan->status = 'returned';
        $loan->save();

        $loan->book->increment('available_copies');

        // Calculate and create fine if overdue
        if (now()->gt($loan->due_date)) {
            $overdueDays = (int) now()->diffInDays($loan->due_date);
            $fine = $overdueDays * self::FINE_PER_DAY;

            LibraryFine::create([
                'book_loan_id' => $loan->id,
                'user_id'      => $loan->user_id,
                'amount'       => $fine,
                'status'       => 'unpaid',
            ]);

            return redirect()->route('schooladmin.library.loans.index')
                ->with('warning', "Book returned. A fine of KES {$fine} has been charged for {$overdueDays} overdue day(s).");
        }

        return redirect()->route('schooladmin.library.loans.index')
            ->with('success', 'Book returned successfully.');
    }

    // Needed by resource route but not used
    public function edit(BookLoan $loan) { abort(404); }
    public function update(Request $request, BookLoan $loan) { abort(404); }
    public function destroy(BookLoan $loan) { abort(404); }
}
