<?php

namespace App\Http\Controllers\SchoolAdmin\Library;

use App\Http\Controllers\Controller;
use App\Models\Book;
use Illuminate\Http\Request;

class BookController extends Controller
{
    public function index()
    {
        $books = Book::latest()->paginate(10);
        return view('schooladmin.library.books.index', compact('books'));
    }

    public function create()
    {
        return view('schooladmin.library.books.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'author' => 'required|string|max:255',
            'isbn' => 'nullable|string|max:255',
            'publisher' => 'nullable|string|max:255',
            'category' => 'nullable|string|max:255',
            'total_copies' => 'required|integer|min:1',
            'location' => 'nullable|string|max:255',
        ]);

        $validated['available_copies'] = $validated['total_copies'];

        Book::create($validated);

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

    public function show(Book $book)
    {
        return view('schooladmin.library.books.show', compact('book'));
    }

    public function edit(Book $book)
    {
        return view('schooladmin.library.books.edit', compact('book'));
    }

    public function update(Request $request, Book $book)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'author' => 'required|string|max:255',
            'isbn' => 'nullable|string|max:255',
            'publisher' => 'nullable|string|max:255',
            'category' => 'nullable|string|max:255',
            'total_copies' => 'required|integer|min:1',
            'location' => 'nullable|string|max:255',
        ]);

        $diff = $validated['total_copies'] - $book->total_copies;
        $validated['available_copies'] = max(0, $book->available_copies + $diff);

        $book->update($validated);

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

    public function destroy(Book $book)
    {
        if ($book->loans()->where('status', 'active')->count() > 0) {
            return redirect()->route('schooladmin.library.books.index')
                ->with('error', 'Cannot delete book. There are active loans.');
        }

        $book->delete();

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