<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Instansi;
use App\Models\Absensi;
use Carbon\Carbon;
use Illuminate\Http\Request;

class LaporanController extends Controller
{
    public function index(Request $request)
    {
        $bulan = $request->get('bulan', now()->month);
        $tahun = $request->get('tahun', now()->year);

        $instansis     = Instansi::withCount('karyawans')->get();
        $totalInstansi = $instansis->count();
        $totalKaryawan = $instansis->sum('karyawans_count');

        // Total absensi bulan ini
        $totalAbsensi = Absensi::whereMonth('tanggal', $bulan)
            ->whereYear('tanggal', $tahun)
            ->whereNotNull('jam_masuk')
            ->count();

        // Rekap per instansi
        $rekapInstansi = $instansis->map(function ($inst) use ($bulan, $tahun) {
            $hariKerja  = Carbon::create($tahun, $bulan)->daysInMonth;
            $maxAbsensi = $inst->karyawans_count * $hariKerja;

            $totalHadir = Absensi::whereHas('karyawan', fn($q) => $q->where('instansi_id', $inst->id))
                ->whereMonth('tanggal', $bulan)
                ->whereYear('tanggal', $tahun)
                ->whereNotNull('jam_masuk')
                ->count();

            $persen = $maxAbsensi > 0
                ? round(($totalHadir / $maxAbsensi) * 100)
                : 0;

            return [
                'id'             => $inst->id,
                'nama'           => $inst->nama_instansi,
                'total_karyawan' => $inst->karyawans_count,
                'total_hadir'    => $totalHadir,
                'persen_hadir'   => $persen,
            ];
        });

        // Rata-rata kehadiran
        $rataKehadiran = $rekapInstansi->count() > 0
            ? round($rekapInstansi->avg('persen_hadir'))
            : 0;

        // Data grafik harian
        $hariIni     = Carbon::create($tahun, $bulan)->daysInMonth;
        $chartLabels = [];
        $chartData   = [];

        for ($d = 1; $d <= $hariIni; $d++) {
            $chartLabels[] = $d;
            $chartData[]   = Absensi::whereDate('tanggal', Carbon::create($tahun, $bulan, $d))
                ->whereNotNull('jam_masuk')
                ->count();
        }

        return view('admin.laporan.index', compact(
            'bulan', 'tahun',
            'totalInstansi', 'totalKaryawan', 'totalAbsensi', 'rataKehadiran',
            'rekapInstansi', 'chartLabels', 'chartData'
        ));
    }

    public function exportPdf(Request $request)
    {
        $bulan = $request->get('bulan', now()->month);
        $tahun = $request->get('tahun', now()->year);

        $instansis = Instansi::withCount('karyawans')->get();

        $rekapInstansi = $instansis->map(function ($inst) use ($bulan, $tahun) {
            $hariKerja  = Carbon::create($tahun, $bulan)->daysInMonth;
            $maxAbsensi = $inst->karyawans_count * $hariKerja;

            $totalHadir = Absensi::whereHas('karyawan', fn($q) => $q->where('instansi_id', $inst->id))
                ->whereMonth('tanggal', $bulan)
                ->whereYear('tanggal', $tahun)
                ->whereNotNull('jam_masuk')
                ->count();

            $persen = $maxAbsensi > 0
                ? round(($totalHadir / $maxAbsensi) * 100)
                : 0;

            return [
                'nama'           => $inst->nama_instansi,
                'total_karyawan' => $inst->karyawans_count,
                'total_hadir'    => $totalHadir,
                'persen_hadir'   => $persen,
            ];
        });

        $namaBulan = Carbon::create($tahun, $bulan)->isoFormat('MMMM YYYY');

        $html = view('admin.laporan.pdf', compact('rekapInstansi', 'namaBulan', 'bulan', 'tahun'))->render();
        $pdf  = \Barryvdh\DomPDF\Facade\Pdf::loadHTML($html)->setPaper('a4', 'landscape');

        return $pdf->download("laporan-absensi-{$bulan}-{$tahun}.pdf");
    }

    public function exportExcel(Request $request)
    {
        $bulan = $request->get('bulan', now()->month);
        $tahun = $request->get('tahun', now()->year);

        $instansis = Instansi::withCount('karyawans')->get();

        $rows   = [];
        $rows[] = ['No', 'Nama Instansi', 'Total Karyawan', 'Total Hadir', 'Persen Kehadiran'];

        foreach ($instansis as $i => $inst) {
            $hariKerja  = Carbon::create($tahun, $bulan)->daysInMonth;
            $maxAbsensi = $inst->karyawans_count * $hariKerja;

            $totalHadir = Absensi::whereHas('karyawan', fn($q) => $q->where('instansi_id', $inst->id))
                ->whereMonth('tanggal', $bulan)
                ->whereYear('tanggal', $tahun)
                ->whereNotNull('jam_masuk')
                ->count();

            $persen = $maxAbsensi > 0 ? round(($totalHadir / $maxAbsensi) * 100) : 0;

            $rows[] = [$i + 1, $inst->nama_instansi, $inst->karyawans_count, $totalHadir, $persen . '%'];
        }

        $filename = "laporan-absensi-{$bulan}-{$tahun}.csv";
        $headers  = [
            'Content-Type'        => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
        ];

        $callback = function () use ($rows) {
            $file = fopen('php://output', 'w');
            fprintf($file, chr(0xEF) . chr(0xBB) . chr(0xBF));
            foreach ($rows as $row) {
                fputcsv($file, $row, ';');
            }
            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
}