<?php

namespace App\Http\Controllers\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Models\User;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class LaporanController extends Controller
{

    public function showLaporan(Request $request)
    {
        $month = (int) ($request->get('month', now()->month));
        $year  = (int) ($request->get('year', now()->year));

        $month = max(1, min(12, $month));
        $year  = max(2000, min(2100, $year));

        $start = Carbon::create($year, $month, 1)->startOfMonth();
        $end   = Carbon::create($year, $month, 1)->endOfMonth();

        // ✅ kalau bulan berjalan, end cukup sampai hari ini (biar “per tanggal hari ini”)
        if ($year === now()->year && $month === now()->month) {
            $end = now();
        }

        $startDate = $start->toDateString();
        $endDate   = $end->toDateString();

        $rows = User::query()
            ->where('users.status', 'aktif')
            ->select('users.id', 'users.name', 'users.jabatan', 'users.url_photo')
            ->withCount([
                'attendances as hadir' => fn($q) => $q->whereBetween('date', [$startDate, $endDate])->where('status', 'hadir'),
                'attendances as izin'  => fn($q) => $q->whereBetween('date', [$startDate, $endDate])->where('status', 'izin'),
                'attendances as sakit' => fn($q) => $q->whereBetween('date', [$startDate, $endDate])->where('status', 'sakit'),
                'attendances as alpha' => fn($q) => $q->whereBetween('date', [$startDate, $endDate])->where('status', 'alpha'),
            ])
            ->orderBy('users.name', 'asc')
            ->get();

        $monthLabel = Carbon::create($year, $month, 1)->translatedFormat('F Y');

        return view('admin.features.laporan.laporan', [
            'rows' => $rows,
            'month' => $month,
            'year' => $year,
            'monthLabel' => $monthLabel,
            'start' => $startDate,
            'end' => $endDate,
        ]);
    }
    public function showDetail(Request $request, User $user)
    {
        $month = (int) ($request->get('month', now()->month));
        $year  = (int) ($request->get('year', now()->year));

        $month = max(1, min(12, $month));
        $year  = max(2000, min(2100, $year));

        $start = Carbon::create($year, $month, 1)->startOfMonth();
        $end   = Carbon::create($year, $month, 1)->endOfMonth();

        // optional: jika bulan berjalan, sampai hari ini
        if ($year === now()->year && $month === now()->month) {
            $end = now();
        }

        $startDate = $start->toDateString();
        $endDate   = $end->toDateString();

        // ambil riwayat attendances bulan tsb
        $items = Attendance::query()
            ->where('user_id', $user->id)
            ->whereBetween('date', [$startDate, $endDate])
            ->orderBy('date', 'desc')
            ->get();

        // rekap status (hadir/izin/sakit/alpha)
        $counts = Attendance::query()
            ->where('user_id', $user->id)
            ->whereBetween('date', [$startDate, $endDate])
            ->select('status', DB::raw('COUNT(*) as total'))
            ->groupBy('status')
            ->pluck('total', 'status');

        $summary = [
            'hadir' => (int) ($counts['hadir'] ?? 0),
            'izin'  => (int) ($counts['izin'] ?? 0),
            'sakit' => (int) ($counts['sakit'] ?? 0),
            'alpha' => (int) ($counts['alpha'] ?? 0),
        ];

        // hitung durasi di PHP (lebih fleksibel)
        $normalizeDT = function ($date, $t) {
            if (!$t) return null;

            // kalau sudah Carbon instance
            if ($t instanceof \Carbon\CarbonInterface) return $t;

            $t = (string) $t;

            // kalau sudah mengandung tanggal (YYYY-MM-DD ...)
            if (preg_match('/\d{4}-\d{2}-\d{2}/', $t)) {
                return Carbon::parse($t);
            }

            // kalau cuma jam (HH:MM:SS) -> gabungkan dengan tanggal dari $date
            $dateOnly = Carbon::parse($date)->toDateString(); // aman walau $date "2026-02-20 00:00:00"
            return Carbon::parse($dateOnly . ' ' . $t);
        };

        $items->transform(function ($a) use ($normalizeDT) {
            $a->date_label = Carbon::parse($a->date)->translatedFormat('d F Y');

            $inDT  = $normalizeDT($a->date, $a->check_in);
            $outDT = $normalizeDT($a->date, $a->check_out);

            $a->check_in_label  = $inDT ? $inDT->format('H:i') : '-';
            $a->check_out_label = $outDT ? $outDT->format('H:i') : '-';

            $a->duration_label = '-';
            if ($inDT && $outDT) {
                if ($outDT->lt($inDT)) $outDT = $outDT->copy()->addDay();
                $sec = $inDT->diffInSeconds($outDT);
                $a->duration_label = gmdate('H:i', $sec);
            }

            $a->notes_label = $a->notes ?? '-';
            $a->location_label = $a->location ?? '-';
            $a->location_lat = null;
            $a->location_lng = null;
            $a->osm_url = null;
            $a->osm_embed_url = null;

            $location = trim((string) ($a->location ?? ''));
            $parts = array_map('trim', explode(',', $location));
            if (count($parts) === 2 && is_numeric($parts[0]) && is_numeric($parts[1])) {
                $lat = (float) $parts[0];
                $lng = (float) $parts[1];

                if ($lat >= -90 && $lat <= 90 && $lng >= -180 && $lng <= 180) {
                    $a->location_lat = $lat;
                    $a->location_lng = $lng;
                    $a->osm_url = "https://www.openstreetmap.org/?mlat={$lat}&mlon={$lng}#map=18/{$lat}/{$lng}";

                    $delta = 0.005;
                    $minLng = $lng - $delta;
                    $minLat = $lat - $delta;
                    $maxLng = $lng + $delta;
                    $maxLat = $lat + $delta;
                    $a->osm_embed_url = "https://www.openstreetmap.org/export/embed.html?bbox={$minLng}%2C{$minLat}%2C{$maxLng}%2C{$maxLat}&layer=mapnik&marker={$lat}%2C{$lng}";
                }
            }

            return $a;
        });

        $monthLabel = Carbon::create($year, $month, 1)->translatedFormat('F Y');

        // persentase hadir (dari total record bulan tsb)
        $total = max(1, array_sum($summary));
        $presentPercent = (int) round(($summary['hadir'] / $total) * 100);

        return view('admin.features.laporan.detail-laporan', [
            'user' => $user,
            'items' => $items,
            'summary' => $summary,
            'month' => $month,
            'year' => $year,
            'monthLabel' => $monthLabel,
            'start' => $startDate,
            'end' => $endDate,
            'presentPercent' => $presentPercent,
        ]);
    }

    // Perubahan pada LaporanController.php method export

    public function export(Request $request)
    {
        $month = (int) ($request->get('month', now()->month));
        $year  = (int) ($request->get('year', now()->year));

        $month = max(1, min(12, $month));
        $year  = max(2000, min(2100, $year));

        $start = Carbon::create($year, $month, 1)->startOfMonth();
        $end   = Carbon::create($year, $month, 1)->endOfMonth();

        // opsional: kalau bulan berjalan -> sampai hari ini
        if ($year === now()->year && $month === now()->month) {
            $end = now();
        }

        $startDate = $start->toDateString();
        $endDate   = $end->toDateString();

        // ✅ semua role ikut tampil (tidak filter role)
        $rows = User::query()
            // ->where('users.status', 'aktif') // kalau mau semua status, biarkan comment
            ->select('users.id', 'users.name', 'users.jabatan')
            ->withCount([
                'attendances as hadir' => fn($q) => $q->whereBetween('date', [$startDate, $endDate])->where('status', 'hadir'),
                'attendances as izin'  => fn($q) => $q->whereBetween('date', [$startDate, $endDate])->where('status', 'izin'),
                'attendances as sakit' => fn($q) => $q->whereBetween('date', [$startDate, $endDate])->where('status', 'sakit'),
                'attendances as alpha' => fn($q) => $q->whereBetween('date', [$startDate, $endDate])->where('status', 'alpha'),
            ])
            ->orderBy('users.name', 'asc')
            ->get();

        $monthLabel = Carbon::create($year, $month, 1)->translatedFormat('F Y');

        $totals = [
            'hadir' => (int) $rows->sum('hadir'),
            'izin'  => (int) $rows->sum('izin'),
            'sakit' => (int) $rows->sum('sakit'),
            'alpha' => (int) $rows->sum('alpha'),
        ];

        $pdf = Pdf::loadView('admin.features.laporan.export.pdf', [
            'rows' => $rows,
            'monthLabel' => $monthLabel,
            'start' => $startDate,
            'end' => $endDate,
            'totals' => $totals,
        ])->setPaper('a4', 'landscape');

        $filename = 'Rekap_Absensi_' . str_replace(' ', '_', $monthLabel) . '.pdf';

        return $pdf->download($filename);
    }

    public function exportDetail(Request $request, User $user)
    {
        $month = (int) ($request->get('month', now()->month));
        $year  = (int) ($request->get('year', now()->year));

        $month = max(1, min(12, $month));
        $year  = max(2000, min(2100, $year));

        $start = Carbon::create($year, $month, 1)->startOfMonth();
        $end   = Carbon::create($year, $month, 1)->endOfMonth();

        if ($year === now()->year && $month === now()->month) {
            $end = now();
        }

        $startDate = $start->toDateString();
        $endDate   = $end->toDateString();

        $items = Attendance::where('user_id', $user->id)
            ->whereBetween('date', [$startDate, $endDate])
            ->orderBy('date', 'asc')
            ->get();

        $counts = Attendance::where('user_id', $user->id)
            ->whereBetween('date', [$startDate, $endDate])
            ->select('status', DB::raw('COUNT(*) as total'))
            ->groupBy('status')
            ->pluck('total', 'status');

        $summary = [
            'hadir' => (int) ($counts['hadir'] ?? 0),
            'izin'  => (int) ($counts['izin'] ?? 0),
            'sakit' => (int) ($counts['sakit'] ?? 0),
            'alpha' => (int) ($counts['alpha'] ?? 0),
        ];

        $monthLabel = Carbon::create($year, $month, 1)->translatedFormat('F Y');

        $pdf = Pdf::loadView('admin.features.laporan.export.pdf-detail', [
            'user' => $user,
            'items' => $items,
            'summary' => $summary,
            'monthLabel' => $monthLabel,
            'start' => $startDate,
            'end' => $endDate,
        ])->setPaper('a4', 'portrait');

        return $pdf->download('Detail_Absensi_' . str_replace(' ', '_', $monthLabel) . '_' . $user->name . '.pdf');
    }
}
