<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Koleksi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class KoleksiController extends Controller
{
    
    public function index(Request $request)
    {
        $query = Koleksi::with('borrowTransactions');

        
        if ($request->filled('search')) {
            $kategori = $request->input('kategori');
            $search = $request->input('search');

            switch ($kategori) {
                case 'judul':
                    $query->where('title', 'like', "%{$search}%");
                    break;
                case 'pengarang':
                    $query->where('sor', 'like', "%{$search}%");
                    break;
                case 'isbn':
                    $query->where(function ($q) use ($search) {
                        $q->where('isbn_issn', 'like', "%{$search}%")
                          ->orWhere('kode_eksemplar', 'like', "%{$search}%");
                    });
                    break;
                default:
                    $query->where(function ($q) use ($search) {
                        $q->where('title', 'like', "%{$search}%")
                          ->orWhere('sor', 'like', "%{$search}%")
                          ->orWhere('isbn_issn', 'like', "%{$search}%")
                          ->orWhere('kode_eksemplar', 'like', "%{$search}%");
                    });
                    break;
            }
        }

      
        if ($request->filled('tipe')) {
            $query->where('tipe', $request->input('tipe'));
        }

        if ($request->filled('bahasa')) {
            $query->where('bahasa', $request->input('bahasa'));
        }

        if ($request->filled('subjek')) {
            $query->where('subjek', $request->input('subjek'));
        }

        if ($request->filled('tahun_min')) {
            $query->where('publish_year', '>=', $request->input('tahun_min'));
        }

        if ($request->filled('tahun_max')) {
            $query->where('publish_year', '<=', $request->input('tahun_max'));
        }

        if ($request->filled('lokasi')) {
            $query->where('lokasi', $request->input('lokasi'));
        }

       
        if ($request->filled('status')) {
            $status = $request->input('status');

            if ($status === 'tersedia') {
                $query->whereDoesntHave('borrowTransactions', function ($q) {
                    $q->whereIn('status', [
                        'menunggu', 
                        'disetujui', 
                        'dipinjam', 
                        'pengembalian_menunggu'
                    ]);
                });
            } elseif ($status === 'dipinjam') {
                $query->whereHas('borrowTransactions', function ($q) {
                    $q->whereIn('status', [
                        'menunggu', 
                        'disetujui', 
                        'dipinjam', 
                        'pengembalian_menunggu'
                    ]);
                });
            }
        }

      
        $koleksi = $query->orderBy('input_date', 'desc')
                        ->paginate(10)
                        ->withQueryString();

        $jumlahJilid = Koleksi::count();

        return view('user.koleksi', compact('koleksi', 'jumlahJilid'));
    }

   public function show(Koleksi $koleksi)
{
    return view('user.koleksi.show', compact('koleksi'));
}



    
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'sor' => 'nullable|string|max:255',
            'publisher_id' => 'nullable|string|max:255',
            'publish_place_id' => 'nullable|string|max:255',
            'publish_year' => 'nullable|integer',
            'kode_eksemplar' => 'nullable|string|max:100',
            'tipe' => 'nullable|string|max:100',
            'bahasa' => 'nullable|string|max:100',
            'subjek' => 'nullable|string|max:100',
            'lokasi' => 'nullable|string|max:100',
            'isbn_issn' => 'nullable|string|max:100',
            'image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
        ]);

        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $filename = time() . '_' . $file->getClientOriginalName();
            $path = storage_path('app/public/image/' . $filename);

            Image::make($file)
                ->resize(300, null, function ($constraint) {
                    $constraint->aspectRatio();
                })
                ->save($path);

            $validated['image'] = 'image/' . $filename;
        }

        Koleksi::create($validated);

        return redirect()->route('user.koleksi')
            ->with('success', 'Data buku berhasil ditambahkan.');
    }

   
    public function update(Request $request, $id)
    {
        $koleksi = Koleksi::findOrFail($id);

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'sor' => 'nullable|string|max:255',
            'publisher_id' => 'nullable|string|max:255',
            'publish_place_id' => 'nullable|string|max:255',
            'publish_year' => 'nullable|integer',
            'kode_eksemplar' => 'nullable|string|max:100',
            'tipe' => 'nullable|string|max:100',
            'bahasa' => 'nullable|string|max:100',
            'subjek' => 'nullable|string|max:100',
            'lokasi' => 'nullable|string|max:100',
            'isbn_issn' => 'nullable|string|max:100',
            'image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
        ]);

        if ($request->hasFile('image')) {
            if ($koleksi->image && Storage::exists('public/' . $koleksi->image)) {
                Storage::delete('public/' . $koleksi->image);
            }

            $file = $request->file('image');
            $filename = time() . '_' . $file->getClientOriginalName();
            $path = storage_path('app/public/image/' . $filename);

            Image::make($file)
                ->resize(300, null, function ($constraint) {
                    $constraint->aspectRatio();
                })
                ->save($path);

            $validated['image'] = 'image/' . $filename;
        }

        $koleksi->update($validated);

        return redirect()->route('user.koleksi')
            ->with('success', 'Data buku berhasil diperbarui.');
    }

    public function homepage()
    {
        $jumlahJilid = Koleksi::count('title');
        return view('home', compact('jumlahJilid'));
    }

   
    public function getPengarang(Request $request)
    {
        $judul = $request->query('judul');

        if (!$judul) {
            return response()->json(['pengarang' => '']);
        }

        $buku = Koleksi::where('title', 'like', '%' . $judul . '%')->first();

        return response()->json([
            'pengarang' => $buku->sor ?? ''
        ]);
    }
}

