<?php

namespace App\Http\Controllers;

use App\Services\DummyDataService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PeminjamanController extends Controller
{
    public function index(Request $request)
    {
        $user = \Illuminate\Support\Facades\Auth::user();
        $bukuPinjam = \App\Services\DummyDataService::getBukuPinjamOffline($user);
        $isTelat = collect($bukuPinjam)->contains(function ($buku) {
            return $buku['sisa_hari'] < 0;
        });

        $isBannedManual = $user->is_banned ?? false;

        if (($isTelat || $isBannedManual) && $user->role === 'siswa') {
            return redirect()->route('dashboard')->with('error', 'AKSES DITOLAK: Akun Anda sedang dibekukan karena ada buku terlambat!');
        }

        $filters = $request->only(['search', 'kategori', 'tahun', 'penulis']);
        $filters['tipe_akses'] = 'offline';
        $semuaBuku = DummyDataService::getKatalogBuku($filters);
        $filterOptions = DummyDataService::getFilterOptions();

        return view('katalog.index', [
            'semuaBuku' => $semuaBuku,
            'filterOptions' => $filterOptions,
            'input' => $request->query(),
            'pageTitle' => 'Peminjaman Buku Offline',
            'mode' => 'offline',
        ]);
    }

    public function ringkasan($id)
    {
        $user = Auth::user();
        $buku = DummyDataService::getKatalogBuku()->firstWhere('id', $id);

        return view('katalog.ringkasan', [
            'user' => $user,
            'buku' => $buku,
            'pageTitle' => 'Peminjaman Buku Offline',
            'actionRoute' => 'peminjaman.form',
            'previousRoute' => 'peminjaman.index',
            'actionButtonText' => 'Lanjutkan ke Form Peminjaman',
            'actionButtonIcon' => 'bi-file-earmark-text-fill',
        ]);
    }


    public function form($id)
    {
        $user = Auth::user();
        $buku = DummyDataService::getKatalogBuku()->firstWhere('id', $id);
        $filters = ['tipe_akses' => 'offline'];
        $semuaBuku = DummyDataService::getKatalogBuku($filters);

        return view('peminjaman.form', compact('user', 'buku', 'semuaBuku'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'buku_ids' => 'required|array|min:1|max:3',
            'buku_ids.*' => 'integer'
        ]);

        $bukuIds = $request->input('buku_ids');

        foreach ($bukuIds as $bukuId) {
            // Di backend nanti kayak gini
            // Peminjaman::create([
            //     'user_id' => auth()->id(), 
            //     'book_id' => $bukuId,
            //     'tanggal_pinjam' => now(),
            //     'tanggal_kembali' => now()->addDays(7),
            //     'status' => 'dipinjam'
            // ]);
        }

        return redirect()->route('dashboard')
            ->with('success', 'Berhasil meminjam ' . count($bukuIds) . ' buku!');
    }
}
