<?php

namespace App\Http\Controllers;

use App\Services\DummyDataService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Str;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class BacaOnlineController extends Controller
{
    public function index(Request $request): View
    {
        $filters = $request->only(['search', 'kategori', 'tahun', 'penulis']);
        $filters['tipe_akses'] = 'online';
        $semuaBuku = DummyDataService::getKatalogBuku($filters);
        $filterOptions = DummyDataService::getFilterOptions();

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

    public function ringkasan(int $id): View
    {
        $book = $this->getBookOrFail($id);

        return view('katalog.ringkasan', [
            'buku' => $book,
            'pageTitle' => 'Baca Buku Online',
            'actionRoute' => 'baca.request_code',
            'previousRoute' => 'baca.index',
            'actionButtonText' => 'Baca Sekarang',
            'actionButtonIcon' => 'bi-book-half',
        ]);
    }

    public function showCodeRequestPage(int $id): View
    {
        $book = $this->getBookOrFail($id);
        $sessionKey = 'access_code_for_book_' . $id;

        if (session()->has($sessionKey)) {
            $accessCode = session($sessionKey);
        } else {
            $accessCode = 'BCO-' . date('Ymd') . '-' . $book['id'] . '-' . Str::upper(Str::random(4));
            session([$sessionKey => $accessCode]);
        }

        session(['book_verified_' . $id => false]);

        return view('baca.request_code', [
            'book' => $book,
            'accessCode' => $accessCode
        ]);
    }

    public function verifyCode(Request $request, int $id): RedirectResponse
    {
        $request->validate(['kode_akses' => 'required|string']);
        $correctCode = session('access_code_for_book_' . $id);

        if ($request->input('kode_akses') === $correctCode) {
            session(['book_verified_' . $id => true]);
            session()->forget('access_code_for_book_' . $id);
            return redirect()->route('baca.view_book', ['id' => $id]);
        }

        return back()->with('error', 'Kode akses yang Anda masukkan salah!');
    }

    public function viewBook(int $id): View|RedirectResponse
    {
        if (!session('book_verified_' . $id, false)) {
            return redirect()->route('baca.request_code', ['id' => $id])
                ->with('error', 'Silakan masukkan kode akses terlebih dahulu.');
        }
        $book = $this->getBookOrFail($id);
        return view('baca.view_book', ['book' => $book]);
    }

    public function streamPdf(int $id): BinaryFileResponse|Response
    {
        if (!session('book_verified_' . $id, false)) {
            abort(403, 'Akses Ditolak.');
        }
        $book = $this->getBookOrFail($id);
        $filePath = 'books/' . $book['file_pdf'];
        $absolutePath = storage_path('app/' . $filePath);

        if (!file_exists($absolutePath)) {
            abort(404, 'GAGAL - PHP tidak dapat menemukan file di: ' . $absolutePath);
        }

        return response()->file($absolutePath);
    }

    private function getBookOrFail(int $id): array
    {
        $book = DummyDataService::getKatalogBuku()->firstWhere('id', $id);
        if (!$book) {
            abort(404, 'Buku tidak ditemukan.');
        }
        return $book;
    }
}
