<?php

namespace App\Http\Controllers;

use App\Models\Loan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Auth;

class RiwayatController extends Controller
{
    public function offlineIndex()
    {
        $user = Auth::user();

        $loans = Loan::with('book.category')
            ->where('user_id', $user->id)
            ->whereIn('status', ['Dipinjam', 'Dikembalikan', 'Terlambat'])
            ->latest()
            ->get();

        $riwayatOffline = $loans->map(fn($loan) => [
            'id' => $loan->id,
            'id_peminjaman' => $loan->loan_code,
            'kode_buku' => $loan->book->kode_buku,
            'judul_utama' => $loan->book->judul,
            'tanggal_pinjam' => $loan->borrowed_at->format('d/m/Y'),
            'tanggal_kembali' => $loan->due_at ? $loan->due_at->format('d/m/Y') : '-',
            'status' => $loan->status,
            'books' => [
                [
                    'id' => $loan->book->id,
                    'judul' => $loan->book->judul,
                    'kode_buku' => $loan->book->kode_buku,
                    'cover' => $loan->book->cover,
                    'deskripsi' => 'Buku ' . $loan->book->judul,
                    'kategori' => $loan->book->category->name ?? 'Tanpa Kategori',
                    'tahun' => $loan->book->tahun,
                    'keterangan' => $loan->status === 'Terlambat' ? 'Buku Terlambat' : null,
                ]
            ]
        ]);

        return view('riwayat.offline', [
            'pageTitle' => 'Riwayat Peminjaman Offline',
            'riwayatOffline' => $riwayatOffline,
        ]);
    }

    public function onlineIndex()
    {
        $user = Auth::user();

        $loans = Loan::with('book.category')
            ->where('user_id', $user->id)
            ->where('status', 'Online')
            ->latest()
            ->get();

        $riwayatOnline = $loans->map(fn($loan) => [
            'id' => $loan->id,
            'id_baca' => $loan->loan_code,
            'judul_buku' => $loan->book->judul,
            'tanggal_akses' => $loan->borrowed_at->format('d/m/Y'),
            'status' => 'Selesai',
            'books' => [
                [
                    'id' => $loan->book->id,
                    'judul' => $loan->book->judul,
                    'cover' => $loan->book->cover,
                    'deskripsi' => 'Buku ' . $loan->book->judul,
                    'kategori' => $loan->book->category->name ?? 'Tanpa Kategori',
                    'tahun' => $loan->book->tahun,
                    'keterangan' => null
                ]
            ]
        ]);

        return view('riwayat.online', [
            'pageTitle' => 'Riwayat Baca Online',
            'riwayatOnline' => $riwayatOnline,
        ]);
    }
}
