<?php

namespace App\Http\Controllers\Admin;

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

class BookController extends Controller
{
    public function index(Request $request)
    {
        $filters = $request->only(['search']);
        
        $query = Book::with('category');

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

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

        // Memisahkan buku menjadi dua koleksi: online dan offline secara independen
        $bukuOnline = $semuaBuku->filter(function ($buku) {
            return in_array('online', $buku->tipe_akses ?? []);
        });

        $bukuOffline = $semuaBuku->filter(function ($buku) {
            return in_array('offline', $buku->tipe_akses ?? []);
        });

        return view('admin.buku.index', [
            'pageTitle' => 'Manajemen Buku',
            'bukuOnline' => $bukuOnline,
            'bukuOffline' => $bukuOffline,
            'input' => $filters
        ]);
    }

    /**
     * Menampilkan halaman form untuk menambah buku baru.
     */
    public function create()
    {
        return view('admin.buku.create', [
            'pageTitle' => 'Tambah Buku Baru',
            'categories' => Category::all()
        ]);
    }

    public function edit($id)
    {
        $buku = Book::with('category')->findOrFail($id);

        return view('admin.buku.edit', [
            'pageTitle' => 'Edit Buku: ' . $buku->judul,
            'buku' => $buku,
            'categories' => Category::all()
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'judul' => 'required|string|max:255',
            'penulis' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'tahun' => 'required|integer',
            'kode_buku' => 'nullable|string',
            'tipe_akses' => 'required|array',
            'cover' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'file_pdf' => 'nullable|mimes:pdf|max:10240',
        ]);

        if ($request->hasFile('cover')) {
            $path = $request->file('cover')->store('covers', 'public');
            $validated['cover'] = 'storage/' . $path;
        }

        if ($request->hasFile('file_pdf')) {
            $path = $request->file('file_pdf')->store('books', 'local');
            $validated['file_pdf'] = basename($path);
        }

        Book::create($validated);

        return redirect()->route('admin.buku.index')->with('success', 'Buku berhasil ditambahkan.');
    }

    public function update(Request $request, $id)
    {
        $buku = Book::findOrFail($id);

        $validated = $request->validate([
            'judul' => 'required|string|max:255',
            'penulis' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'tahun' => 'required|integer',
            'kode_buku' => 'nullable|string',
            'tipe_akses' => 'required|array',
            'cover' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'file_pdf' => 'nullable|mimes:pdf|max:10240',
        ]);

        if ($request->hasFile('cover')) {
            $path = $request->file('cover')->store('covers', 'public');
            $validated['cover'] = 'storage/' . $path;
        }

        if ($request->hasFile('file_pdf')) {
            $path = $request->file('file_pdf')->store('books', 'local');
            $validated['file_pdf'] = basename($path);
        }

        $buku->update($validated);

        return redirect()->route('admin.buku.index')->with('success', 'Buku berhasil diperbarui.');
    }

    public function destroy($id)
    {
        $buku = Book::findOrFail($id);
        $buku->delete();

        return redirect()->route('admin.buku.index')->with('success', 'Buku berhasil dihapus.');
    }
}