<?php

namespace Modules\Lpj\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\Lpj\Models\CategoryDaftarPustaka;
use Modules\Lpj\Services\DaftarPustakaService;
use Modules\Lpj\Http\Requests\DaftarPustakaRequest;
use Exception;
use Illuminate\Support\Facades\Log;

class DaftarPustakaController extends Controller
{
    private $daftarPustaka;

    public function __construct()
    {
        $this->daftarPustaka = app(DaftarPustakaService::class);
    }

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
{
    // Get categories with count of daftar pustaka
    try {
        $categories = CategoryDaftarPustaka::withCount('daftarPustaka')->get();
    } catch (\Exception $e) {
        // Handle jika tabel belum ada atau error lainnya
        Log::warning('Error loading categories with count: ' . $e->getMessage());
        $categories = CategoryDaftarPustaka::get(); // Fallback tanpa count
    }

    $daftar_pustaka = $this->daftarPustaka->getAllDaftarPustaka($request);

    return view('lpj::daftar-pustaka.index', [
        'categories' => $categories,
        'daftar_pustaka' => $daftar_pustaka,
        'page' => $daftar_pustaka->currentPage(),
        'pageCount' => $daftar_pustaka->lastPage(),
        'limit' => $daftar_pustaka->perPage(),
        'total' => $daftar_pustaka->total(),
    ]);
}


    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $categories = CategoryDaftarPustaka::all();
        // dd($categories);
        return view('lpj::daftar-pustaka.create', compact('categories'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(DaftarPustakaRequest $request)
    {

        $validate = $request->validated();
        // dd($validate);
        $file = $request->file('attachment');
        if ($validate) {
            try {
                // Save to database
                $this->daftarPustaka->storeDaftarPustaka($validate, $file);
                return redirect()
                    ->route('daftar-pustaka.index')
                    ->with('success', 'Daftar Pustaka created successfully');
            } catch (Exception $e) {
                return redirect()
                    ->route('daftar-pustaka.create')
                    ->with('error', 'Failed to create daftar pustaka');
            }
        }

    }

    /**
     * Show the specified resource.
     */
    public function show($id)
    {
        $daftarPustaka = $this->daftarPustaka->getDaftarPustakaById($id);
        $categories = CategoryDaftarPustaka::all();

        return view('lpj::daftar-pustaka.show', compact('daftarPustaka', 'categories'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $daftarPustaka = $this->daftarPustaka->getDaftarPustakaById($id);
        $categories = CategoryDaftarPustaka::all();
        return view('lpj::daftar-pustaka.create', compact('daftarPustaka', 'categories'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(DaftarPustakaRequest $request, $id)
    {
        $validate = $request->validated();
        if ($validate) {
            try {
                // Save to database
                $file = $request->file('attachment');
                $this->daftarPustaka->updateDaftarPustaka($validate, $file, $id);
                return redirect()
                    ->route('daftar-pustaka.index')
                    ->with('success', 'Daftar Pustaka updated successfully');
            } catch (Exception $e) {
                return redirect()
                    ->route('daftar-pustaka.create')
                    ->with('error', 'Failed to update daftar pustaka');
            }
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        try {
            $this->daftarPustaka->deleteDaftarPustaka($id);
            return response()->json(['success' => true, 'message' => 'Daftar Pustaka deleted successfully']);
        } catch (Exception $e) {
            return response()->json(['success' => false, 'message' => 'Failed to delete daftar pustaka']);
        }
    }
}
