<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Models\AttendanceSetting;
use App\Models\Department;
use App\Models\Employee;
use Carbon\Carbon;
use Illuminate\Http\Request;

class ReportController extends Controller
{
    public function monthly(Request $request)
    {
        $month = (int)$request->input('month', Carbon::now()->month);
        $year = (int)$request->input('year', Carbon::now()->year);
        $departmentId = $request->input('department_id');

        $query = Employee::with('department')->where('status', 'active');

        if ($departmentId) {
            $query->where('department_id', $departmentId);
        }

        $employees = $query->orderBy('name')->get();
        $departments = Department::all();

        $startDate = Carbon::createFromDate($year, $month, 1)->startOfMonth();
        $endDate = $startDate->copy()->endOfMonth();

        $totalDaysInMonth = $startDate->daysInMonth;

        $recapData = [];

        foreach ($employees as $emp) {
            $attendances = Attendance::where('employee_id', $emp->id)
                ->whereBetween('attendance_date', [$startDate->toDateString(), $endDate->toDateString()])
                ->get();

            $hadir = $attendances->where('status', 'present')->count();
            $terlambat = $attendances->where('status', 'late')->count();
            $izin = $attendances->where('status', 'permit')->count();
            $sakit = $attendances->where('status', 'sick')->count();
            $cuti = $attendances->where('status', 'leave')->count();
            $alpha = $attendances->whereIn('status', ['absent', 'alpha'])->count();

            $totalHadir = $hadir + $terlambat;
            $recapData[] = [
                'employee' => $emp,
                'hadir' => $hadir,
                'terlambat' => $terlambat,
                'izin' => $izin,
                'sakit' => $sakit,
                'cuti' => $cuti,
                'alpha' => $alpha,
                'total_hadir' => $totalHadir,
            ];
        }

        return view('admin.reports.monthly', compact(
            'recapData',
            'month',
            'year',
            'departments',
            'totalDaysInMonth'
        ));
    }

    public function index(Request $request)
    {
        $preset = $request->input('preset', 'this_month');
        $departmentId = $request->input('department_id');
        $status = $request->input('status');

        $now = Carbon::now();

        if ($preset === 'today') {
            $startDate = $now->toDateString();
            $endDate = $now->toDateString();
        } elseif ($preset === 'this_week') {
            $startDate = $now->startOfWeek()->toDateString();
            $endDate = $now->endOfWeek()->toDateString();
        } elseif ($preset === 'custom' && $request->filled('start_date') && $request->filled('end_date')) {
            $startDate = $request->start_date;
            $endDate = $request->end_date;
        } else { // this_month
            $startDate = $now->startOfMonth()->toDateString();
            $endDate = $now->endOfMonth()->toDateString();
        }

        $query = Attendance::with(['employee.department', 'shift', 'officeLocation'])
            ->whereBetween('attendance_date', [$startDate, $endDate]);

        if ($departmentId) {
            $query->whereHas('employee', function ($q) use ($departmentId) {
                $q->where('department_id', $departmentId);
            });
        }

        if ($status) {
            $query->where('status', $status);
        }

        $attendances = $query->latest('attendance_date')->latest('check_in')->paginate(20)->withQueryString();
        $departments = Department::all();

        return view('admin.reports.index', compact(
            'attendances',
            'departments',
            'preset',
            'startDate',
            'endDate'
        ));
    }

    public function exportMonthly(Request $request)
    {
        $month = (int)$request->input('month', Carbon::now()->month);
        $year = (int)$request->input('year', Carbon::now()->year);
        $departmentId = $request->input('department_id');

        $startDate = Carbon::createFromDate($year, $month, 1)->startOfMonth();
        $endDate = $startDate->copy()->endOfMonth();
        $monthName = $startDate->translatedFormat('F Y');
        $companyName = AttendanceSetting::get('company_name', config('app.name', 'PT Inovasi Digital Nusantara'));

        $query = Employee::with('department')->where('status', 'active');
        if ($departmentId) {
            $query->where('department_id', $departmentId);
        }
        $employees = $query->orderBy('name')->get();

        $filename = "Rekap_Presensi_Bulanan_{$year}_{$month}.xls";

        // Generate Styled HTML Excel Table for perfect visual presentation in MS Excel
        $output = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">';
        $output .= '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
        $output .= '<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Rekap Bulanan</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->';
        $output .= '<style>
            table { border-collapse: collapse; width: 100%; font-family: "Segoe UI", Arial, sans-serif; font-size: 11pt; }
            th { background-color: #1e293b; color: #ffffff; font-weight: bold; border: 1px solid #cbd5e1; padding: 10px; text-align: center; }
            td { border: 1px solid #cbd5e1; padding: 8px 10px; vertical-align: middle; }
            .header-title { font-size: 16pt; font-weight: bold; color: #0f172a; }
            .header-subtitle { font-size: 12pt; color: #475569; }
            .header-meta { font-size: 9pt; color: #64748b; font-style: italic; }
            .text-center { text-align: center; }
            .text-left { text-align: left; }
            .text-right { text-align: right; }
            .bg-summary { background-color: #f1f5f9; font-weight: bold; border-top: 2px solid #0f172a; }
            .bg-highlight { background-color: #eef2ff; }
        </style>';
        $output .= '</head><body>';

        // Title Block
        $output .= '<table>';
        $output .= '<tr><td colspan="10" class="header-title">' . htmlspecialchars($companyName) . '</td></tr>';
        $output .= '<tr><td colspan="10" class="header-subtitle">LAPORAN REKAPITULASI PRESENSI BULANAN</td></tr>';
        $output .= '<tr><td colspan="10" class="header-meta">Periode: ' . $monthName . ' | Dicetak pada: ' . now()->translatedFormat('d F Y H:i') . ' WIB</td></tr>';
        $output .= '<tr><td colspan="10"></td></tr>';

        // Table Header
        $output .= '<tr>
            <th>No</th>
            <th>NIK</th>
            <th>Nama Karyawan</th>
            <th>Departemen</th>
            <th>Hadir Tepat Waktu</th>
            <th>Terlambat</th>
            <th>Izin</th>
            <th>Sakit</th>
            <th>Cuti</th>
            <th>Tanpa Keterangan (Alpha)</th>
            <th>Total Hari Masuk</th>
        </tr>';

        $totalHadirAll = 0;
        $totalTerlambatAll = 0;
        $totalIzinAll = 0;
        $totalSakitAll = 0;
        $totalCutiAll = 0;
        $totalAlphaAll = 0;
        $grandTotalMasuk = 0;
        $no = 1;

        foreach ($employees as $emp) {
            $attendances = Attendance::where('employee_id', $emp->id)
                ->whereBetween('attendance_date', [$startDate->toDateString(), $endDate->toDateString()])
                ->get();

            $hadir = $attendances->where('status', 'present')->count();
            $terlambat = $attendances->where('status', 'late')->count();
            $izin = $attendances->where('status', 'permit')->count();
            $sakit = $attendances->where('status', 'sick')->count();
            $cuti = $attendances->where('status', 'leave')->count();
            $alpha = $attendances->whereIn('status', ['absent', 'alpha'])->count();
            $totalMasuk = $hadir + $terlambat;

            $totalHadirAll += $hadir;
            $totalTerlambatAll += $terlambat;
            $totalIzinAll += $izin;
            $totalSakitAll += $sakit;
            $totalCutiAll += $cuti;
            $totalAlphaAll += $alpha;
            $grandTotalMasuk += $totalMasuk;

            $output .= '<tr>
                <td class="text-center">' . $no++ . '</td>
                <td class="text-center" style="mso-number-format:\'@\';">' . htmlspecialchars($emp->nik) . '</td>
                <td class="text-left">' . htmlspecialchars($emp->name) . '</td>
                <td class="text-left">' . htmlspecialchars($emp->department?->name ?? '-') . '</td>
                <td class="text-center">' . $hadir . '</td>
                <td class="text-center">' . $terlambat . '</td>
                <td class="text-center">' . $izin . '</td>
                <td class="text-center">' . $sakit . '</td>
                <td class="text-center">' . $cuti . '</td>
                <td class="text-center">' . $alpha . '</td>
                <td class="text-center bg-highlight" style="font-weight: bold;">' . $totalMasuk . '</td>
            </tr>';
        }

        // Summary Row
        $output .= '<tr class="bg-summary">
            <td colspan="4" class="text-center">TOTAL KESELURUHAN</td>
            <td class="text-center">' . $totalHadirAll . '</td>
            <td class="text-center">' . $totalTerlambatAll . '</td>
            <td class="text-center">' . $totalIzinAll . '</td>
            <td class="text-center">' . $totalSakitAll . '</td>
            <td class="text-center">' . $totalCutiAll . '</td>
            <td class="text-center">' . $totalAlphaAll . '</td>
            <td class="text-center" style="font-weight: bold; color: #1e40af;">' . $grandTotalMasuk . '</td>
        </tr>';

        $output .= '</table></body></html>';

        return response($output, 200, [
            'Content-Type' => 'application/vnd.ms-excel; charset=utf-8',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
            'Pragma' => 'no-cache',
            'Expires' => '0',
        ]);
    }
}
