<?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();

        $bukuOnline = $semuaBuku->filter(function ($buku) {
            return in_array('online', $buku->tipe_akses ?? []) && ! $buku->is_arsip;
        });

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

        $bukuArsip = $semuaBuku->filter(function ($buku) {
            return $buku->is_arsip;
        });

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

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

    /**
     * Menampilkan detail buku.
     */
    public function show($id)
    {
        $buku = Book::with('category')->findOrFail($id);

        return view('admin.buku.show', [
            'pageTitle' => 'Detail Buku: ' . $buku->judul,
            'buku' => $buku
        ]);
    }

    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|min:3|max:50',
            'penulis' => 'required|string|min:3|max:50|regex:/^[a-zA-Z\s.,\']+$/',
            'category_id' => 'required|exists:categories,id',
            'tahun' => 'required|integer|min:1900|max:2026',
            'kode_buku' => 'required|numeric|max_digits:10',
            'stok' => 'required|integer|min:0|max:99',
            'tipe_akses' => 'required|array',
            'cover' => 'required|image|mimes:jpeg,png,jpg|max:2048',
            'file_pdf' => 'required|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);
        }

        $validated['status'] = $validated['stok'] <= 0 ? 'Dipinjam' : 'Tersedia';

        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|min:3|max:50',
            'penulis' => 'required|string|min:3|max:50|regex:/^[a-zA-Z\s.,\']+$/',
            'category_id' => 'required|exists:categories,id',
            'tahun' => 'required|integer|min:1900|max:2026',
            'kode_buku' => 'nullable|numeric|max_digits:10',
            'stok' => 'required|integer|min:0|max:99',
            '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);
        }

        $validated['status'] = $validated['stok'] <= 0 ? 'Dipinjam' : 'Tersedia';

        $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.');
    }

    public function arsip(Request $request)
    {
        $buku = Book::findOrFail($request->id);
        $buku->update(['is_arsip' => true]);

        return response()->json(['status' => 'success', 'message' => 'Buku berhasil diarsipkan.']);
    }

    public function pulihkan(Request $request)
    {
        $buku = Book::findOrFail($request->id);
        $buku->update(['is_arsip' => false]);

        return response()->json(['status' => 'success', 'message' => 'Buku berhasil dipulihkan.']);
    }
}
