<?php

namespace App\Http\Controllers\Api;

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

class BookController extends Controller
{
    // Get all books
/**
 * Get all books
 */
public function index()
{
    $books = Book::with('category')->get()->map(function ($book) {
        return [
            'id' => $book->id,
            'title' => $book->title,
            'author' => $book->author,
            'publisher' => $book->publisher,
            'category' => $book->category->name,
            'file_url' => $book->file ? url($book->file) : null,
            'cover_image_url' => $book->cover_image ? url($book->cover_image) : null,
            'category_id' => $book->category_id,
            'created_at' => $book->created_at,
            'updated_at' => $book->updated_at
        ];
    });

    return response()->json([
        'success' => true,
        'data' => $books,
    ]);
}

/**
 * Get a specific book
 */
public function show($id)
{
    $book = Book::with('category')->find($id);
    
    if (!$book) {
        return response()->json([
            'success' => false,
            'message' => 'Book not found',
        ], 404);
    }

    return response()->json([
        'success' => true,
        'data' => [
            'id' => $book->id,
            'title' => $book->title,
            'author' => $book->author,
            'publisher' => $book->publisher,
            'category' => $book->category->name,
            'file_url' => $book->file ? url($book->file) : null,
            'cover_image_url' => $book->cover_image ? url($book->cover_image) : null,
            'category_id' => $book->category_id,
            'created_at' => $book->created_at,
            'updated_at' => $book->updated_at
        ]
    ]);
}

/**
 * Get books by category ID
 */
public function byCategory($categoryId)
{
    $books = Book::where('category_id', $categoryId)
                ->with('category')
                ->get()
                ->map(function ($book) {
                    return [
                        'id' => $book->id,
                        'title' => $book->title,
                        'author' => $book->author,
                        'publisher' => $book->publisher,
                        'category' => $book->category->name,
                        'file_url' => $book->file ? url($book->file) : null,
                        'cover_image_url' => $book->cover_image ? url($book->cover_image) : null,
                        'category_id' => $book->category_id,
                        'created_at' => $book->created_at,
                        'updated_at' => $book->updated_at
                    ];
                });

    if ($books->isEmpty()) {
        return response()->json([
            'success' => false,
            'message' => 'No books found for this category',
        ], 404);
    }

    return response()->json([
        'success' => true,
        'data' => $books,
    ]);
}

 
}
