<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\Absensi;
use App\Models\RekapLembur;
use Carbon\Carbon;
use Maatwebsite\Excel\Facades\Excel;
use Barryvdh\DomPDF\Facade\Pdf;

class LaporanController extends Controller
{
    public function index()
    {
        // Ambil data absensi dengan relasi user
        $absensi = Absensi::with('user')
            ->orderBy('tanggal', 'desc')
            ->get();

        // Ambil data rekap lembur
        $rekapLembur = RekapLembur::with('user')
            ->orderBy('tanggal', 'desc')
            ->get();

        return view('admin.laporan', compact('absensi', 'rekapLembur'));
    }

    public function exportExcel()
    {
        $absensi = Absensi::with('user')
            ->orderBy('tanggal', 'desc')
            ->get();

        return Excel::download(new class($absensi) implements \Maatwebsite\Excel\Concerns\FromCollection, \Maatwebsite\Excel\Concerns\WithHeadings {
            private $absensi;

            public function __construct($absensi)
            {
                $this->absensi = $absensi;
            }

            public function collection()
            {
                return $this->absensi->map(function ($item) {
                    return [
                        'Nama' => $item->user->name ?? $item->nama_karyawan,
                        'Tanggal' => $item->tanggal->format('d/m/Y'),
                        'Jam Masuk' => $item->jam_masuk ? Carbon::parse($item->jam_masuk)->format('H:i') : '-',
                        'Jam Pulang' => $item->jam_pulang ? Carbon::parse($item->jam_pulang)->format('H:i') : '-',
                        'Total Jam' => $item->total_jam ? $item->getTotalJamFormatted() : '-',
                        'Jam Lembur' => $item->jam_lembur > 0 ? $item->getJamLemburFormatted() : '-',
                        'Status' => ucfirst($item->status),
                    ];
                });
            }

            public function headings(): array
            {
                return ['Nama', 'Tanggal', 'Jam Masuk', 'Jam Pulang', 'Total Jam', 'Jam Lembur', 'Status'];
            }
        }, 'laporan_absensi.xlsx');
    }

    public function exportPdf()
    {
        $absensi = Absensi::with('user')
            ->orderBy('tanggal', 'desc')
            ->get();

        $pdf = Pdf::loadView('admin.laporan-pdf', compact('absensi'));
        return $pdf->download('laporan_absensi.pdf');
    }
}
