<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProfileUpdateRequest;
use App\Models\Book;
use App\Models\Loan;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;

class ProfileController extends Controller
{
    /**
     * Tampilkan halaman profil user.
     */
    public function index(Request $request): View
    {
        $user = Auth::user();
        if (!$user) {
            return redirect()->route('login');
        }

        $viewData = ['user' => $user];

        if ($user->role === 'penjaga perpus') {
            // Data untuk Penjaga Perpus: Statistik global & aktivitas terkini
            $viewData['statistik'] = [
                ['label' => 'Total Buku', 'value' => Book::count(), 'icon' => 'bi-journal-bookmark-fill', 'color' => 'primary'],
                ['label' => 'Total Anggota', 'value' => User::count(), 'icon' => 'bi-people-fill', 'color' => 'success'],
                ['label' => 'Buku Dipinjam', 'value' => Loan::whereIn('status', ['Dipinjam', 'Terlambat'])->count(), 'icon' => 'bi-arrow-up-right-circle-fill', 'color' => 'warning'],
                ['label' => 'Denda Menunggu', 'value' => Loan::where('status', 'Terlambat')->count(), 'icon' => 'bi-cash-coin', 'color' => 'danger'],
            ];
            $viewData['aktivitasTerakhir'] = Loan::with(['user', 'book'])->latest()->take(4)->get()->map(fn($loan) => [
                'nama' => $loan->user->nama_lengkap ?? 'Unknown',
                'judul_buku' => $loan->book->judul ?? 'Unknown',
                'tipe' => $loan->status === 'Dikembalikan' ? 'Pengembalian' : 'Peminjaman',
                'waktu' => $loan->created_at->diffForHumans(),
                'status' => $loan->status,
            ]);
        } elseif ($user->role === 'guru') {
            // Data untuk Guru
            $loans = Loan::with('book')->where('user_id', $user->id)->whereIn('status', ['Dipinjam', 'Terlambat'])->get();

            $viewData['bukuOffline'] = $loans->map(fn($loan) => [
                'judul' => $loan->book->judul,
                'penulis' => $loan->book->penulis,
                'sisa_hari' => (int) now()->diffInDays(Carbon::parse($loan->due_at), false),
                'cover' => $loan->book->cover,
            ]);

            $viewData['bukuOnline'] = $loans->filter(fn($loan) => in_array('online', $loan->book->tipe_akses ?? []))->map(fn($loan) => [
                'judul' => $loan->book->judul,
                'penulis' => $loan->book->penulis,
                'progress' => 0,
                'cover' => $loan->book->cover,
            ]);

            // Analytics for Guru (simplified for profile view)
            $viewData['laporan'] = [
                'buku_terpopuler' => Book::withCount('loans')->orderBy('loans_count', 'desc')->take(3)->get(),
                'insight' => 'Siswa aktif meminjam buku kategori Sains.'
            ];
        } else {
            // Data untuk Siswa
            $loans = Loan::with('book')->where('user_id', $user->id)->whereIn('status', ['Dipinjam', 'Terlambat'])->get();

            $viewData['bukuOffline'] = $loans->map(fn($loan) => [
                'judul' => $loan->book->judul,
                'penulis' => $loan->book->penulis,
                'sisa_hari' => (int) now()->diffInDays(Carbon::parse($loan->due_at), false),
                'cover' => $loan->book->cover,
            ]);

            $viewData['bukuOnline'] = $loans->filter(fn($loan) => in_array('online', $loan->book->tipe_akses ?? []))->map(fn($loan) => [
                'judul' => $loan->book->judul,
                'penulis' => $loan->book->penulis,
                'progress' => 0,
                'cover' => $loan->book->cover,
            ]);

            $viewData['statistik'] = [
                ['label' => 'Buku dipinjam', 'value' => $loans->count(), 'icon' => 'bi-book-half', 'color' => 'primary'],
                ['label' => 'Tenggat Waktu', 'value' => $viewData['bukuOffline']->where('sisa_hari', '<=', 3)->where('sisa_hari', '>=', 0)->count(), 'icon' => 'bi-clock-history', 'color' => 'danger'],
                ['label' => 'Buku dikembalikan', 'value' => Loan::where('user_id', $user->id)->where('status', 'Dikembalikan')->count(), 'icon' => 'bi-check-circle', 'color' => 'success'],
                ['label' => 'History Baca', 'value' => Loan::where('user_id', $user->id)->count(), 'icon' => 'bi-hourglass-split', 'color' => 'warning'],
            ];
        }

        return view('profile.index', $viewData);
    }

    /**
     * Tampilkan form edit profil.
     */
    public function edit(Request $request): View
    {
        return view('profile.edit', [
            'user' => $request->user(),
        ]);
    }

    /**
     * Update data profil ke Database MySQL.
     */
    public function update(Request $request): RedirectResponse
    {
        $user = $request->user();
        $user->fill($request->validated());
        $user->name = $user->nama_lengkap; // Sync for compatibility

        if ($user->isDirty('email')) {
            $user->email_verified_at = null;
        }

        $user->save();
        $user->save();

        return Redirect::route('profile.edit')->with('status', 'profile-updated');
    }

    /**
     * Hapus akun user.
     */
    public function destroy(Request $request): RedirectResponse
    {
        $request->validateWithBag('userDeletion', [
            'password' => ['required', 'current_password'],
        ]);

        $user = $request->user();

        Auth::logout();

        $user->delete();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return Redirect::to('/');
    }
}
