<?php

namespace App\Modules\AttendanceReview\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Controllers\DashboardController;
use App\Models\AppSetting;
use App\Models\UserModels;
use App\Modules\AttendanceReview\Exports\AttendanceActualRecordExport;
use App\Modules\AttendanceReview\Exports\AttendanceReviewExport;
use App\Modules\AttendanceReview\Exports\AttendanceReviewSummaryExport;
use App\Modules\AttendanceReview\Exports\SelectedSchedulePivotExport;
use App\Modules\AttendanceReview\Jobs\GenerateCalculationZipJob;
use App\Modules\AttendanceReview\Jobs\ImportMachineLogJob;
use App\Modules\AttendanceReview\Jobs\RebuildPlanningJob;
use App\Modules\AttendanceReview\Jobs\RunAttendanceDetectionJob;
use App\Modules\AttendanceReview\Jobs\SyncPublicApiLogJob;
use App\Modules\AttendanceReview\Models\AttendanceDailyReviewHistoryModel;
use App\Modules\AttendanceReview\Models\AttendanceDailyReviewModel;
use App\Modules\AttendanceReview\Models\AttendanceQuestionModel;
use App\Modules\AttendanceReview\Models\AttendanceExportJobModel;
use App\Modules\AttendanceReview\Models\AttendanceLogModel;
use App\Modules\AttendanceReview\Models\AttendanceUrgencyRecordModel;
use App\Modules\AttendanceReview\Models\AttendanceUrgencyPolicyModel;
use App\Modules\AttendanceReview\Models\AttendanceWarningLetterModel;
use App\Modules\AttendanceReview\Services\AttendanceDayCreditResolver;
use App\Modules\ForgettingClockRequest\Models\ForgettingClockRequestModel;
use App\Modules\LeaveRequest\Models\LeaveRequestModel;
use App\Modules\MasterApproval\Models\ApprovalRequestModel;
use App\Modules\MasterApproval\Services\ApprovalWorkflowService;
use App\Modules\MasterKalender\Models\KalenderModel;
use App\Modules\MasterKaryawan\Models\KaryawanFingerHistoryModel;
use App\Modules\MasterKaryawan\Models\KaryawanModel;
use App\Modules\MasterPembulatanJam\Models\PembulatanJamModel;
use App\Modules\MasterProfilBulan\Models\ProfilBulanKaryawanModel;
use App\Modules\MasterProfilBulan\Models\ProfilBulanModel;
use App\Modules\MasterProfilJamKerja\Models\ProfilJamKerjaModel;
use App\Modules\MasterShiftSchedule\Models\ShiftScheduleModel;
use App\Modules\MasterProfilPerkalianJam\Models\ProfilPerkalianJamDetailModel;
use App\Modules\ProjectJobCosting\Models\ProjectJobAssignmentModel;
use App\Modules\SuratPerintahLembur\Models\SuratPerintahLemburModel;
use App\Services\AttendanceDailySummaryService;
use App\Support\AttendanceLateRule;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;
use Throwable;

// =============================================================================
// AttendanceReviewController - Controller utama attendance review (V1) - deteksi, review, kalkulasi, export
// Dipanggil dari: Module AttendanceReview routes/web.php
// Middleware: auth, ip.block, menu.access
// Route yang terdaftar:
//   POST /attendance-review/detect/suggest-shift/apply -> applySuggestedShiftProfile()
//   POST /attendance-review/calculations/detail/approve-all -> approveCalculationDetailAll()
//   POST /attendance-review/reviews/{id}/offline-approve -> approveOfflineLogs()
//   POST /attendance-review/reviews/{id}/approve       -> approveReview()
//   POST /attendance-review/reviews/approve-by-date    -> approveReviewsByDate()
//   GET /attendance-review/calculations                -> calculationData()
//   GET /attendance-review/calculations/detail         -> calculationDetailPage()
//   GET /attendance-review/calculations/zip/{id}/status -> calculationZipStatus()
//   POST /attendance-review/detect/{id}/cancel         -> cancelDetection()
//   DELETE /attendance-review/logs/{id}                -> destroyLog()
//   GET /attendance-review/detect/{id}/status          -> detectionStatus()
//   POST /attendance-review/discipline/check-profile   -> disciplineCheckProfile()
//   POST /attendance-review/discipline/issue-warning-letter -> disciplineIssueWarningLetter()
//   POST /attendance-review/discipline/warning-letter/{id}/revoke -> disciplineRevokeWarningLetter()
//   GET /attendance-review/discipline/warning-letter/{id}/pdf -> disciplineWarningLetterPdf()
//   GET /attendance-review/calculations/zip/{id}/download -> downloadCalculationZip()
//   GET /attendance-review/reviews-export-actual-excel -> exportActualRecordsExcel()
//   GET /attendance-review/calculations/detail/export-pdf -> exportCalculationDetailPdf()
//   GET /attendance-review/calculation-sheet           -> exportCalculationSheet()
//   GET /attendance-review/reviews-export              -> exportReviews()
//   GET /attendance-review/summary-export-excel        -> exportSummaryExcel()
//   GET /attendance-review/summary-export-pdf          -> exportSummaryPdf()
//   GET /attendance-review/face-file                   -> faceFile()
//   GET /attendance-review                             -> index()
//   GET /attendance-review/logs                        -> logData()
//   GET /attendance-review/logs/jobs/{id}/status       -> logJobStatus()
//   POST /attendance-review/reviews/{id}/manual-time   -> manualUpdateReviewTime()
//   POST /attendance-review/detect/{id}/pause          -> pauseDetection()
//   POST /attendance-review/logs/preview-public-api    -> previewPublicApiLog()
//   GET /attendance-review/refs/profil-bulans          -> profilBulanOptions()
//   GET /attendance-review/queue/health                -> queueHealth()
//   POST /attendance-review/logs/import-machine        -> queueImportMachineLog()
//   POST /attendance-review/queue/process-once         -> queueProcessOnce()
//   POST /attendance-review/logs/sync-public-api       -> queueSyncPublicApiLog()
//   POST /attendance-review/rebuild-planning           -> rebuildPlanning()
//   GET /attendance-review/rebuild/{id}/status         -> rebuildStatus()
//   GET /attendance-review/refs                        -> refs()
//   POST /attendance-review/reviews/{id}/reject-hours  -> rejectHolidayHours()
//   POST /attendance-review/reviews/{id}/offline-reject -> rejectOfflineLogs()
//   POST /attendance-review/logs/repair-mapping        -> repairLogMapping()
//   POST /attendance-review/calculations/zip/request   -> requestCalculationZip()
//   POST /attendance-review/reviews/{id}/restore-hours -> restoreHolidayHours()
//   POST /attendance-review/detect/{id}/resume         -> resumeDetection()
//   GET /attendance-review/reviews                     -> reviewData()
//   GET /attendance-review/reviews/{id}/histories      -> reviewHistories()
//   GET /attendance-review/reviews/{id}/log-options    -> reviewLogOptions()
//   POST /attendance-review/detect                     -> runDetection()
//   POST /attendance-review/calculations/detail/send   -> sendCalculationDetail()
//   POST /attendance-review/reviews-export/send        -> sendReviewsExport()
//   POST /attendance-review/logs                       -> storeLog()
//   GET /attendance-review/detect/suggest-shift        -> suggestShiftProfile()
//   GET /attendance-review/summary-data                -> summaryData()
//   GET /attendance-review/summary                     -> summaryPage()
//   POST /attendance-review/logs/test-public-api       -> testPublicApiConnection()
//   POST /attendance-review/reviews/unapprove-by-date  -> unapproveReviewsByDate()
//   GET /attendance-review/logs/unmapped               -> unmappedLogData()
//   POST /attendance-review/discipline/settings        -> updateDisciplineSettings()
// =============================================================================

class AttendanceReviewController extends Controller
{
    private function guardProfilBulanOpenForAttendance(?ProfilBulanModel $profil): ?JsonResponse
    {
        if (strtolower(trim((string) ($profil?->status ?? 'open'))) !== 'closed') {
            return null;
        }

        return response()->json([
            'message' => 'Profil bulan sudah closed. Approval/koreksi Attendance Review dikunci. Buka revisi di Master Profil Bulan dulu.',
            'action' => 'profile_closed',
            'profil_bulan_id' => (int) ($profil?->id ?? 0),
        ], 423);
    }

    private const QUEUE_NAME = 'attendance-review';
    private const LEGACY_MONTHLY_TO_DAILY_THRESHOLD = 300000.00;

    private const SP_THRESHOLDS = [
        1 => ['score' => 12, 'alpha' => 3],
        2 => ['score' => 24, 'alpha' => 6],
        3 => ['score' => 36, 'alpha' => 9],
    ];

    private const REVIEW_TRACKED_FIELDS = [
        'profil_bulan_id',
        'karyawan_id',
        'work_date',
        'planned_profil_jam_kerja_id',
        'planned_shift_start',
        'planned_shift_end',
        'is_cross_day',
        'checkin_at',
        'checkout_at',
        'suggested_checkin_at',
        'suggested_checkout_at',
        'status',
        'confidence_score',
        'reason',
        'is_approved',
        'approved_by',
        'approved_at',
    ];

    // =========================================================================
    // index() - Menampilkan halaman utama/index
    // Dipanggil dari: GET /attendance-review
    // Output: View (halaman Blade template)
    // =========================================================================
    public function index()
    {
        return view('attendancereview::index', $this->publicSyncConfig());
    }

    // =========================================================================
    // publicSyncConfig() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    protected function publicSyncConfig(): array
    {
        $baseUrl = $this->getPublicSyncBaseUrl();
        $apiKey = $this->getPublicSyncApiKey();
        $transactionsPath = '/'.ltrim((string) env('ATTENDANCE_PUBLIC_SYNC_TRANSACTIONS_PATH', '/api/public/transactions'), '/');

        return [
            'public_sync_base_url' => $baseUrl,
            'public_sync_has_api_key' => $apiKey !== '',
            'public_sync_transactions_path' => $transactionsPath,
            'public_sync_transactions_url' => $baseUrl.$transactionsPath,
            'can_direct_approve_requests' => $this->isAdministrator(auth()->user()) || $this->isHrd(auth()->user()),
        ];
    }

    // =========================================================================
    // getPublicSyncBaseUrl() - Mengambil/mendapatkan data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    protected function getPublicSyncBaseUrl(?Request $request = null): string
    {
        $envDefault = rtrim((string) env('ATTENDANCE_PUBLIC_SYNC_BASE_URL', 'http://192.168.11.201:8090'), '/');

        $stored = trim((string) (AppSetting::query()
            ->where('key', 'attendance.public_sync.base_url')
            ->value('value') ?? ''));

        $baseUrl = $stored !== '' ? $stored : $envDefault;

        if ($request && $request->filled('base_url')) {
            $input = trim((string) $request->input('base_url'));
            $normalized = $this->normalizePublicSyncBaseUrl($input);

            // Persist supaya operator tidak perlu isi ulang (berguna saat domain/hosting berubah).
            AppSetting::query()->updateOrCreate(
                ['key' => 'attendance.public_sync.base_url'],
                ['value' => $normalized]
            );

            $baseUrl = $normalized;
        }

        return rtrim($baseUrl, '/');
    }

    // =========================================================================
    // getPublicSyncApiKey() - Mengambil/mendapatkan data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    protected function getPublicSyncApiKey(?Request $request = null): string
    {
        $stored = trim((string) (AppSetting::query()
            ->where('key', 'attendance.public_sync.api_key')
            ->value('value') ?? ''));
        $apiKey = $stored !== '' ? $stored : trim((string) env('WDMS_PUBLIC_API_KEY', ''));

        if ($request && $request->filled('api_key')) {
            $input = trim((string) $request->input('api_key'));
            if ($input !== '') {
                AppSetting::query()->updateOrCreate(
                    ['key' => 'attendance.public_sync.api_key'],
                    ['value' => $input]
                );
                $apiKey = $input;
            }
        }

        return $apiKey;
    }

    // =========================================================================
    // normalizePublicSyncBaseUrl() - Menormalisasi format data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    protected function normalizePublicSyncBaseUrl(string $baseUrl): string
    {
        $url = trim($baseUrl);
        if ($url === '') {
            abort(422, 'Host API wajib diisi.');
        }

        if (! preg_match('#^https?://#i', $url)) {
            $url = 'http://'.$url;
        }

        $url = rtrim($url, '/');

        if (! filter_var($url, FILTER_VALIDATE_URL)) {
            abort(422, 'Format Host API tidak valid. Contoh: http://192.168.11.201:8090 atau https://domain.com');
        }

        return $url;
    }

    /**
     * @return array<int, string>
     */
    // =========================================================================
    // publicSyncTransactionPaths() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    protected function publicSyncTransactionPaths(): array
    {
        $configured = '/'.ltrim((string) env('ATTENDANCE_PUBLIC_SYNC_TRANSACTIONS_PATH', '/api/public/transactions'), '/');
        $paths = [
            $configured,
            '/api/public/transactions',
            '/public/transactions',
        ];

        return array_values(array_unique(array_filter($paths, fn ($path) => is_string($path) && trim($path) !== '')));
    }

    /**
     * @param  array<string, mixed>  $query
     * @return array{payload:mixed, endpoint:string}
     */
    // =========================================================================
    // requestPublicAttendanceApi() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    protected function requestPublicAttendanceApi(string $baseUrl, string $apiKey, array $query, int $timeout = 30): array
    {
        $responses = [];

        foreach ($this->publicSyncTransactionPaths() as $transactionsPath) {
            $http = Http::timeout($timeout)->acceptJson();

            $endpoint = $baseUrl.$transactionsPath;
            $requestQuery = $query;
            if ($apiKey !== '' && ! array_key_exists('api_key', $requestQuery)) {
                $requestQuery['api_key'] = $apiKey;
            }
            $response = $http->get($endpoint, $requestQuery);
            if ($response->successful()) {
                return [
                    'payload' => $response->json(),
                    'endpoint' => $endpoint,
                ];
            }

            $responses[] = [
                'status' => $response->status(),
                'endpoint' => $endpoint,
                'body' => Str::limit($response->body(), 800),
            ];

            if ($response->status() !== 404) {
                break;
            }
        }

        $last = end($responses) ?: ['status' => 500, 'endpoint' => $baseUrl, 'body' => ''];
        $responseBody = (string) ($last['body'] ?? '');
        abort(response()->json([
            'message' => 'Gagal ambil data dari API publik: HTTP '.($last['status'] ?? 500).($responseBody !== '' ? ' - '.Str::limit($responseBody, 160) : ''),
            'endpoint' => $last['endpoint'] ?? $baseUrl,
            'tried_endpoints' => array_column($responses, 'endpoint'),
            'response' => $responseBody,
        ], 422));
    }

    // =========================================================================
    // summaryPage() - Halaman ringkasan attendance
    // Dipanggil dari: GET /attendance-review/summary
    // Output: View (halaman Blade template)
    // =========================================================================
    public function summaryPage()
    {
        $defaultTemplate = $this->defaultWarningLetterNoTemplate();
        $template = trim((string) (AppSetting::query()->where('key', 'attendance_review.warning_letter_no_template')->value('value') ?: $defaultTemplate));
        if ($template === '') {
            $template = $defaultTemplate;
        }
        $pad = (int) (AppSetting::query()->where('key', 'attendance_review.warning_letter_no_sequence_pad')->value('value') ?: 4);
        if ($pad < 1 || $pad > 10) {
            $pad = 4;
        }
        $validDays = $this->warningLetterValidDays();

        return view('attendancereview::summary', [
            'is_administrator' => $this->isAdministrator(auth()->user()),
            'sp_no_template' => $template,
            'sp_no_pad' => $pad,
            'sp_no_template_default' => $defaultTemplate,
            'sp_valid_days' => $validDays,
        ]);
    }

    // =========================================================================
    // summaryData() - Data ringkasan untuk DataTable
    // Dipanggil dari: GET /attendance-review/summary-data
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function summaryData(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'profil_bulan_ids' => ['nullable', 'array'],
            'profil_bulan_ids.*' => ['integer', 'exists:master_profil_bulans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date', 'after_or_equal:date_from'],
            'q' => ['nullable', 'string', 'max:100'],
            'profile_scope' => ['nullable', 'in:selected,both,main,sub'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profil = ProfilBulanModel::query()->findOrFail((int) $request->input('profil_bulan_id'));
        $profileStartDate = Carbon::parse($profil->start_date)->startOfDay();
        $profileEndDate = Carbon::parse($profil->end_date)->startOfDay();
        $startDate = $request->filled('date_from')
            ? Carbon::parse((string) $request->input('date_from'))->startOfDay()
            : $profileStartDate->copy();
        $endDate = $request->filled('date_to')
            ? Carbon::parse((string) $request->input('date_to'))->startOfDay()
            : $profileEndDate->copy();
        if ($startDate->lt($profileStartDate)) {
            $startDate = $profileStartDate->copy();
        }
        if ($endDate->gt($profileEndDate)) {
            $endDate = $profileEndDate->copy();
        }
        if ($endDate->lt($startDate)) {
            $endDate = $startDate->copy();
        }
        $profileScope = (string) $request->input('profile_scope', 'both');
        $profileScope = in_array($profileScope, ['both', 'main', 'sub'], true) ? $profileScope : 'both';
        $selectedProfileIds = collect($request->input('profil_bulan_ids', []))->map(fn ($id) => (int) $id)->filter()->unique()->values()->all();
        $profileIds = $selectedProfileIds ?: $this->summaryProfileIds($profil, $profileScope);

        $calendarMarks = $this->buildCalendarMarks($startDate->copy(), $endDate->copy());
        $holidayMapRaw = $calendarMarks['holiday_map'] ?? [];
        $workdayMap = $calendarMarks['workday_map'] ?? [];
        $holidaySpecialMap = $calendarMarks['holiday_special_map'] ?? [];
        $holidayMap = [];
        $weekendMap = [];
        foreach ($holidayMapRaw as $dateKey => $label) {
            if (strcasecmp((string) $label, 'Weekend') === 0) {
                $weekendMap[$dateKey] = 'Weekend';

                continue;
            }
            $holidayMap[$dateKey] = (string) $label;
        }
        $search = trim((string) $request->input('q', ''));

        $assignmentsQuery = ProfilBulanKaryawanModel::query()
            ->with('karyawan:id,employee_code,finger_id,full_name,employment_status,is_active,contract_end_date')
            ->whereIn('profil_bulan_id', $profileIds)
            ->where('is_active', true)
            ->whereHas('karyawan', function ($q): void {
                $q->where('is_active', true)
                    ->whereNotIn('employment_status', ['nonaktif', 'resign', 'resigned', 'keluar'])
                    ->whereIn('employment_status', ['tetap', 'kontrak', 'harian', 'magang']);
            })
            ->orderBy('karyawan_id');
        if ($search !== '') {
            $assignmentsQuery->whereHas('karyawan', function ($q) use ($search) {
                $q->where('employee_code', 'like', '%'.$search.'%')
                    ->orWhere('full_name', 'like', '%'.$search.'%');
            });
        }
        $assignments = $assignmentsQuery->get()
            ->sortByDesc('profil_bulan_id')
            ->unique('karyawan_id')
            ->values();

        $employeeIds = $assignments->pluck('karyawan_id')->filter()->map(fn ($id) => (int) $id)->unique()->values();
        if ($employeeIds->isEmpty()) {
            return response()->json([
                'data' => [],
                'meta' => [
                    'profil' => [
                        'id' => (int) $profil->id,
                        'code' => $profil->code,
                        'name' => $profil->name,
                        'start_date' => $profileStartDate->format('Y-m-d'),
                        'end_date' => $profileEndDate->format('Y-m-d'),
                        'selected_start_date' => $startDate->format('Y-m-d'),
                        'selected_end_date' => $endDate->format('Y-m-d'),
                        'profile_scope' => $profileScope,
                        'processed_profile_ids' => $profileIds,
                    ],
                    'holiday_map' => $holidayMap,
                    'weekend_map' => $weekendMap,
                    'workday_map' => $workdayMap,
                    'summary' => [
                        'employees' => 0,
                        'pay_days' => 0,
                        'no_pay_days' => 0,
                        'hadir_total' => 0,
                        'alpha_total' => 0,
                        'alpha_weighted_total' => 0,
                        'telat_total' => 0,
                        'cuti_total' => 0,
                        'sick_total' => 0,
                        'weekend_nopay_total' => 0,
                        'holiday_pay_total' => 0,
                        'belum_kontrak_total' => 0,
                        'kontrak_selesai_total' => 0,
                    ],
                    'alpha_ranking' => [],
                    'violation_ranking' => [],
                    'teladan_ranking' => [],
                ],
            ]);
        }

        $reviewRows = AttendanceDailyReviewModel::query()
            ->whereIn('profil_bulan_id', $profileIds)
            ->whereIn('karyawan_id', $employeeIds->all())
            ->whereDate('work_date', '>=', $startDate->format('Y-m-d'))
            ->whereDate('work_date', '<=', $endDate->format('Y-m-d'))
            ->orderByDesc('profil_bulan_id')
            ->get(['profil_bulan_id', 'karyawan_id', 'work_date', 'planned_profil_jam_kerja_id', 'planned_shift_start', 'planned_shift_end', 'checkin_at', 'checkout_at']);
        $hasAnyReviewRows = $reviewRows->isNotEmpty();
        $lateRuleProfiles = ProfilJamKerjaModel::query()
            ->whereIn('id', $reviewRows->pluck('planned_profil_jam_kerja_id')->filter()->unique()->values()->all())
            ->get(['id', 'late_tolerance_minutes', 'required_checkin_before_start_minutes'])
            ->keyBy('id');
        $reviewMap = [];
        foreach ($reviewRows as $row) {
            if (! $row->work_date) {
                continue;
            }
            $k = ((int) $row->karyawan_id).'|'.Carbon::parse($row->work_date)->format('Y-m-d');
            if (isset($reviewMap[$k])) {
                continue;
            }
            $reviewMap[$k] = $row;
        }

        $leaveRows = LeaveRequestModel::query()
            ->where('status', 'approved')
            ->whereIn('karyawan_id', $employeeIds->all())
            ->whereDate('start_date', '<=', $endDate->format('Y-m-d'))
            ->whereDate('end_date', '>=', $startDate->format('Y-m-d'))
            ->get(['karyawan_id', 'leave_type', 'start_date', 'end_date', 'attachment_path']);
        $leaveMap = [];
        foreach ($leaveRows as $leave) {
            $from = Carbon::parse($leave->start_date)->startOfDay();
            $to = Carbon::parse($leave->end_date)->startOfDay();
            if ($to->lt($from)) {
                $to = $from->copy();
            }
            $from = $from->lt($startDate) ? $startDate->copy() : $from;
            $to = $to->gt($endDate) ? $endDate->copy() : $to;

            foreach (CarbonPeriod::create($from, $to) as $d) {
                $k = ((int) $leave->karyawan_id).'|'.$d->format('Y-m-d');
                $leaveMap[$k] = [
                    'leave_type' => strtolower(trim((string) ($leave->leave_type ?: ''))),
                    'has_attachment' => ! empty($leave->attachment_path),
                ];
            }
        }

        $splApprovedRows = SuratPerintahLemburModel::query()
            ->whereIn('status', ['approved'])
            ->whereIn('karyawan_id', $employeeIds->all())
            ->whereDate('work_date', '>=', $startDate->format('Y-m-d'))
            ->whereDate('work_date', '<=', $endDate->format('Y-m-d'))
            ->get(['karyawan_id', 'work_date']);
        $splApprovedMap = [];
        foreach ($splApprovedRows as $spl) {
            if (! $spl->work_date) {
                continue;
            }
            $splApprovedMap[((int) $spl->karyawan_id).'|'.Carbon::parse($spl->work_date)->format('Y-m-d')] = true;
        }

        $warningLetterCounts = AttendanceWarningLetterModel::query()
            ->whereIn('karyawan_id', $employeeIds->all())
            ->selectRaw('karyawan_id, COUNT(*) as cnt')
            ->groupBy('karyawan_id')
            ->pluck('cnt', 'karyawan_id');

        $rows = [];
        $dateColumns = collect(CarbonPeriod::create($startDate->copy(), $endDate->copy()))
            ->map(fn (Carbon $d) => $d->format('Y-m-d'))
            ->values()
            ->all();
        foreach ($assignments as $idx => $assignment) {
            $employeeId = (int) $assignment->karyawan_id;
            $counter = [
                'hadir_normal' => 0,
                'hadir_telat' => 0,
                'hadir_pulang_cepat' => 0,
                'hadir_telat_pulang_cepat' => 0,
                'izin_sakit' => 0,
                'alpha' => 0,
                'cuti' => 0,
                'weekend_nopay' => 0,
                'holiday_pay' => 0,
                'belum_kontrak' => 0,
                'kontrak_selesai' => 0,
                'pay_days' => 0,
                'no_pay_days' => 0,
            ];
            $dailyCells = [];
            $checkinMinuteTotal = 0;
            $earlyMinuteTotal = 0;
            $checkinMinuteCount = 0;
            $contractStartDate = $assignment->contract_start_date ? Carbon::parse((string) $assignment->contract_start_date)->startOfDay() : null;
            $contractEndDate = $assignment->contract_end_date ? Carbon::parse((string) $assignment->contract_end_date)->startOfDay() : null;

            foreach (CarbonPeriod::create($startDate->copy(), $endDate->copy()) as $d) {
                $dateKey = $d->format('Y-m-d');
                $mapKey = $employeeId.'|'.$dateKey;
                $dayType = $this->resolveDayTypeForCalculation($dateKey, $holidayMap, $workdayMap, $holidaySpecialMap);
                $review = $reviewMap[$mapKey] ?? null;
                $hasShift = $review && $review->planned_shift_start && $review->planned_shift_end;
                $hasSplApproved = isset($splApprovedMap[$mapKey]);
                $leave = $leaveMap[$mapKey] ?? null;
                $contractMask = null;
                $putCell = function (array $cell) use (&$dailyCells, $dateKey, &$contractMask): void {
                    if ($contractMask) {
                        $cell['mask'] = $contractMask;
                    }
                    $dailyCells[$dateKey] = $cell;
                };

                if ($contractStartDate && $d->lt($contractStartDate)) {
                    $counter['belum_kontrak']++;
                    $putCell(['code' => 'BK', 'label' => 'Belum Mulai Kontrak', 'pay' => null, 'type' => 'contract', 'is_lembur' => false]);

                    continue;
                }
                if ($contractEndDate && $d->gt($contractEndDate)) {
                    $counter['kontrak_selesai']++;
                    $contractMask = ['code' => 'KS', 'label' => 'Kontrak Selesai'];
                }

                if ($leave) {
                    $leaveType = (string) ($leave['leave_type'] ?? '');
                    if (str_contains($leaveType, 'sick') || str_contains($leaveType, 'sakit')) {
                        $counter['izin_sakit']++;
                        if (! empty($leave['has_attachment'])) {
                            $counter['pay_days']++;
                            $putCell(['code' => 'S', 'label' => 'Sakit', 'pay' => 1, 'type' => 'leave', 'is_lembur' => false]);
                        } else {
                            $counter['no_pay_days']++;
                            $putCell(['code' => 'S', 'label' => 'Sakit', 'pay' => 0, 'type' => 'leave', 'is_lembur' => false]);
                        }
                    } elseif (str_contains($leaveType, 'annual') || str_contains($leaveType, 'cuti')) {
                        $counter['cuti']++;
                        $counter['pay_days']++;
                        $putCell(['code' => 'C', 'label' => 'Cuti', 'pay' => 1, 'type' => 'leave', 'is_lembur' => false]);
                    } else {
                        $counter['no_pay_days']++;
                        $putCell(['code' => 'I', 'label' => 'Izin', 'pay' => 0, 'type' => 'leave', 'is_lembur' => false]);
                    }

                    continue;
                }

                $isPresent = false;
                $isLate = false;
                $isEarly = false;
                $checkin = null;
                $checkout = null;
                if ($review && $review->checkin_at && $review->checkout_at) {
                    $checkin = Carbon::parse($review->checkin_at);
                    $checkout = Carbon::parse($review->checkout_at);
                    if ($checkout->gt($checkin)) {
                        $isPresent = true;
                        if ($review->planned_shift_start && $review->planned_shift_end) {
                            $plannedIn = Carbon::parse($review->planned_shift_start);
                            $plannedOut = Carbon::parse($review->planned_shift_end);
                            $shiftRule = ! empty($review->planned_profil_jam_kerja_id)
                                ? $lateRuleProfiles->get((int) $review->planned_profil_jam_kerja_id)
                                : null;
                            $isLate = AttendanceLateRule::isLate(
                                $checkin,
                                $plannedIn,
                                (int) ($shiftRule->late_tolerance_minutes ?? 0),
                                (int) ($shiftRule->required_checkin_before_start_minutes ?? 0)
                            );
                            $isEarly = $checkout->lt($plannedOut);
                        }
                    }
                }

                if ($dayType === 'weekend') {
                    $counter['weekend_nopay']++;
                    $counter['no_pay_days']++;
                    if ($hasSplApproved && $isPresent) {
                        $putCell(['code' => 'W+', 'label' => 'Weekend Lembur', 'pay' => 0, 'type' => 'weekend', 'is_lembur' => true]);
                    } else {
                        $putCell(['code' => 'W', 'label' => 'Weekend No Pay', 'pay' => 0, 'type' => 'weekend', 'is_lembur' => false]);
                    }

                    continue;
                }

                if ($isPresent) {
                    $checkinMinuteTotal += ((int) $checkin->format('H') * 60) + (int) $checkin->format('i');
                                        if ($review?->planned_shift_start) {
                        $plannedInForRanking = Carbon::parse($review->planned_shift_start);
                        $earlyMinuteTotal += $plannedInForRanking->diffInMinutes($checkin, false);
                    }
                    $checkinMinuteCount++;
                    if ($this->isHolidayLikeDayType($dayType)) {
                        $counter['holiday_pay']++;
                        $counter['pay_days']++;
                        $putCell(['code' => 'HH', 'label' => $dayType === 'holiday_special' ? 'Holiday Special Masuk (Pay)' : 'Holiday Masuk (Pay)', 'pay' => 1, 'type' => 'holiday', 'is_lembur' => $hasSplApproved]);

                        continue;
                    }
                    if ($isLate && $isEarly) {
                        $counter['hadir_telat_pulang_cepat']++;
                        $putCell(['code' => 'TPC', 'label' => 'Telat+Pulang Cepat', 'pay' => 1, 'type' => 'hadir', 'is_lembur' => $hasSplApproved]);
                    } elseif ($isLate) {
                        $counter['hadir_telat']++;
                        $putCell(['code' => 'T', 'label' => 'Telat', 'pay' => 1, 'type' => 'hadir', 'is_lembur' => $hasSplApproved]);
                    } elseif ($isEarly) {
                        $counter['hadir_pulang_cepat']++;
                        $putCell(['code' => 'PC', 'label' => 'Pulang Cepat', 'pay' => 1, 'type' => 'hadir', 'is_lembur' => $hasSplApproved]);
                    } else {
                        $counter['hadir_normal']++;
                        $putCell(['code' => 'H', 'label' => 'Hadir', 'pay' => 1, 'type' => 'hadir', 'is_lembur' => $hasSplApproved]);
                    }
                    $counter['pay_days']++;

                    continue;
                }

                $mustWork = $dayType === 'workday';
                if ($mustWork) {
                    if (! $hasAnyReviewRows) {
                        $putCell(['code' => 'BP', 'label' => 'Belum Diproses', 'pay' => null, 'type' => 'unprocessed', 'is_lembur' => false]);
                    } else {
                        $counter['alpha']++;
                        $counter['no_pay_days']++;
                        $putCell(['code' => 'A', 'label' => 'Alpha', 'pay' => 0, 'type' => 'alpha', 'is_lembur' => false]);
                    }
                } else {
                    if ($this->isHolidayLikeDayType($dayType)) {
                        $counter['holiday_pay']++;
                        $counter['pay_days']++;
                        $putCell(['code' => 'HL', 'label' => $dayType === 'holiday_special' ? 'Holiday Special Libur (Pay)' : 'Holiday Libur (Pay)', 'pay' => 1, 'type' => 'holiday', 'is_lembur' => false]);
                    } else {
                        $putCell(['code' => '-', 'label' => 'Libur', 'pay' => null, 'type' => 'off', 'is_lembur' => false]);
                    }
                }
            }

            $hadirTotal = $counter['hadir_normal'] + $counter['hadir_telat'] + $counter['hadir_pulang_cepat'] + $counter['hadir_telat_pulang_cepat'];
            $telatTotal = $counter['hadir_telat'] + $counter['hadir_telat_pulang_cepat'];
            $expectedDays = $counter['pay_days'] + $counter['no_pay_days'];
            $fullAttendance = $expectedDays > 0 && $counter['alpha'] === 0;
            $rows[] = [
                'no' => $idx + 1,
                'karyawan_id' => $employeeId,
                'employee_code' => $assignment->karyawan?->employee_code,
                'employee_name' => $assignment->karyawan?->full_name,
                'employee_employment_status' => $assignment->karyawan?->employment_status,
                'employee_is_active' => (bool) ($assignment->karyawan?->is_active ?? false),
                'employee_contract_end_date' => $assignment->karyawan?->contract_end_date ? Carbon::parse((string) $assignment->karyawan->contract_end_date)->format('Y-m-d') : null,
                'warning_letter_issued_count' => (int) ($warningLetterCounts[$employeeId] ?? 0),
                'hadir_normal' => $counter['hadir_normal'],
                'hadir_telat' => $counter['hadir_telat'],
                'hadir_pulang_cepat' => $counter['hadir_pulang_cepat'],
                'hadir_telat_pulang_cepat' => $counter['hadir_telat_pulang_cepat'],
                'hadir_total' => $hadirTotal,
                'izin_sakit' => $counter['izin_sakit'],
                'alpha' => $counter['alpha'],
                'cuti' => $counter['cuti'],
                'weekend_nopay' => $counter['weekend_nopay'],
                'holiday_pay' => $counter['holiday_pay'],
                'belum_kontrak' => $counter['belum_kontrak'],
                'kontrak_selesai' => $counter['kontrak_selesai'],
                'telat_total' => $telatTotal,
                'alpha_weighted' => $counter['alpha'] * 3,
                'violation_score' => ($counter['alpha'] * 3) + $telatTotal,
                'avg_checkin_minute' => $checkinMinuteCount > 0 ? round($checkinMinuteTotal / $checkinMinuteCount, 2) : null,
                'avg_early_minutes' => $checkinMinuteCount > 0 ? round($earlyMinuteTotal / $checkinMinuteCount, 2) : null,
                'checkin_sample' => $checkinMinuteCount,
                'expected_days' => $expectedDays,
                'full_attendance' => $fullAttendance,
                'pay_days' => $counter['pay_days'],
                'no_pay_days' => $counter['no_pay_days'],
                'daily' => $dailyCells,
            ];
        }

        usort($rows, static function (array $a, array $b): int {
            $weightedCmp = ((int) ($b['alpha_weighted'] ?? 0)) <=> ((int) ($a['alpha_weighted'] ?? 0));
            if ($weightedCmp !== 0) {
                return $weightedCmp;
            }
            $alphaCmp = ((int) ($b['alpha'] ?? 0)) <=> ((int) ($a['alpha'] ?? 0));
            if ($alphaCmp !== 0) {
                return $alphaCmp;
            }

            return strcmp((string) ($a['employee_code'] ?? ''), (string) ($b['employee_code'] ?? ''));
        });
        foreach ($rows as $idx => &$rowRef) {
            $rowRef['no'] = $idx + 1;
            $rowRef['alpha_rank'] = $idx + 1;
        }
        unset($rowRef);

        $sharedDaily = app(AttendanceDailySummaryService::class)->dailySeries($startDate->copy(), $endDate->copy(), $employeeIds->all());
        $sharedSeries = (array) ($sharedDaily['series'] ?? []);
        $perDayTotals = [];
        foreach ($dateColumns as $idx => $d) {
            $perDayTotals[$d] = [
                'hadir' => (int) ($sharedSeries['hadir'][$idx] ?? 0),
                'alpha' => (int) ($sharedSeries['alpha'][$idx] ?? 0),
                'leave' => (int) ($sharedSeries['cuti'][$idx] ?? 0) + (int) ($sharedSeries['sick'][$idx] ?? 0),
                'lembur' => (int) ($sharedSeries['lembur'][$idx] ?? 0),
            ];
        }

        $alphaRanking = collect($rows)
            ->filter(fn (array $r) => ((int) ($r['alpha'] ?? 0)) > 0)
            ->values()
            ->take(10)
            ->map(fn (array $r) => [
                'rank' => (int) ($r['alpha_rank'] ?? 0),
                'employee_code' => $r['employee_code'],
                'employee_name' => $r['employee_name'],
                'alpha' => (int) ($r['alpha'] ?? 0),
                'alpha_weighted' => (int) ($r['alpha_weighted'] ?? 0),
            ])
            ->all();
        $violationRanking = collect($rows)
            ->filter(fn (array $r) => ((int) ($r['violation_score'] ?? 0)) > 0)
            ->sort(function (array $a, array $b): int {
                $scoreCmp = ((int) ($b['violation_score'] ?? 0)) <=> ((int) ($a['violation_score'] ?? 0));
                if ($scoreCmp !== 0) {
                    return $scoreCmp;
                }

                return ((int) ($b['alpha'] ?? 0)) <=> ((int) ($a['alpha'] ?? 0));
            })
            ->values()
            ->take(10)
            ->map(function (array $r, int $idx): array {
                return [
                    'rank' => $idx + 1,
                    'karyawan_id' => (int) ($r['karyawan_id'] ?? 0),
                    'employee_code' => $r['employee_code'],
                    'employee_name' => $r['employee_name'],
                    'alpha' => (int) ($r['alpha'] ?? 0),
                    'telat' => (int) ($r['telat_total'] ?? 0),
                    'score' => (int) ($r['violation_score'] ?? 0),
                ];
            })
            ->all();
        $teladanRanking = collect($rows)
            ->filter(fn (array $r) => ((int) ($r['checkin_sample'] ?? 0)) > 0)
            ->sort(function (array $a, array $b): int {
                $fullCmp = ((int) (! empty($b['full_attendance']))) <=> ((int) (! empty($a['full_attendance'])));
                if ($fullCmp !== 0) {
                    return $fullCmp;
                }
                $payRatioA = ((int) ($a['expected_days'] ?? 0)) > 0 ? ((int) ($a['pay_days'] ?? 0) / (int) ($a['expected_days'] ?? 1)) : 0.0;
                $payRatioB = ((int) ($b['expected_days'] ?? 0)) > 0 ? ((int) ($b['pay_days'] ?? 0) / (int) ($b['expected_days'] ?? 1)) : 0.0;
                if (abs($payRatioB - $payRatioA) > 0.000001) {
                    return $payRatioB <=> $payRatioA;
                }
                $leaveA = (int) ($a['cuti'] ?? 0);
                $leaveB = (int) ($b['cuti'] ?? 0);
                if ($leaveA !== $leaveB) {
                    return $leaveA <=> $leaveB;
                }
                $checkinA = $a['avg_checkin_minute'] ?? 9999;
                $checkinB = $b['avg_checkin_minute'] ?? 9999;
                if ($checkinA !== $checkinB) {
                    return $checkinA <=> $checkinB;
                }

                return ((int) ($b['hadir_total'] ?? 0)) <=> ((int) ($a['hadir_total'] ?? 0));
            })
            ->values()
            ->take(10)
            ->map(function (array $r, int $idx): array {
                $avg = $r['avg_checkin_minute'];
                $avgTime = '-';
                if (is_numeric($avg)) {
                    $minute = max(0, (int) round((float) $avg));
                    $avgTime = sprintf('%02d:%02d', intdiv($minute, 60), $minute % 60);
                }

                return [
                    'rank' => $idx + 1,
                    'employee_code' => $r['employee_code'],
                    'employee_name' => $r['employee_name'],
                    'avg_checkin_time' => $avgTime,
                    'avg_early_minutes' => is_numeric($r['avg_early_minutes'] ?? null) ? (float) $r['avg_early_minutes'] : null,
                    'hadir_total' => (int) ($r['hadir_total'] ?? 0),
                    'pay_days' => (int) ($r['pay_days'] ?? 0),
                    'expected_days' => (int) ($r['expected_days'] ?? 0),
                    'full_attendance' => ! empty($r['full_attendance']),
                ];
            })
            ->all();

        $summary = [
            'employees' => count($rows),
            'pay_days' => array_sum(array_column($rows, 'pay_days')),
            'no_pay_days' => array_sum(array_column($rows, 'no_pay_days')),
            'hadir_total' => array_sum(array_column($rows, 'hadir_total')),
            'alpha_total' => array_sum(array_column($rows, 'alpha')),
            'alpha_weighted_total' => array_sum(array_column($rows, 'alpha_weighted')),
            'cuti_total' => array_sum(array_column($rows, 'cuti')),
            'sick_total' => array_sum(array_column($rows, 'izin_sakit')),
            'weekend_nopay_total' => array_sum(array_column($rows, 'weekend_nopay')),
            'holiday_pay_total' => array_sum(array_column($rows, 'holiday_pay')),
            'belum_kontrak_total' => array_sum(array_column($rows, 'belum_kontrak')),
            'kontrak_selesai_total' => array_sum(array_column($rows, 'kontrak_selesai')),
            'telat_total' => array_sum(array_column($rows, 'telat_total')),
        ];
        if ($startDate->isSameDay($endDate)) {
            $employeeKeys = $assignments
                ->flatMap(fn ($row) => [$row->karyawan?->employee_code, $row->karyawan?->finger_id])
                ->map(fn ($v) => trim((string) $v))
                ->filter()
                ->unique()
                ->values()
                ->all();
            $dashboardSummary = $this->dashboardMorningSummaryForDate($startDate, $employeeKeys);
            if ($dashboardSummary) {
                $summary = array_merge($summary, $dashboardSummary);
            }
        }

        return response()->json([
            'data' => $rows,
            'meta' => [
                'profil' => [
                    'id' => (int) $profil->id,
                    'code' => $profil->code,
                    'name' => $profil->name,
                    'start_date' => $profileStartDate->format('Y-m-d'),
                    'end_date' => $profileEndDate->format('Y-m-d'),
                    'selected_start_date' => $startDate->format('Y-m-d'),
                    'selected_end_date' => $endDate->format('Y-m-d'),
                    'profile_scope' => $profileScope,
                    'processed_profile_ids' => $profileIds,
                ],
                'dates' => $dateColumns,
                'holiday_map' => $holidayMap,
                'weekend_map' => $weekendMap,
                'workday_map' => $workdayMap,
                'per_day_totals' => $perDayTotals,
                'summary' => $summary,
                'alpha_ranking' => $alphaRanking,
                'violation_ranking' => $violationRanking,
                'teladan_ranking' => $teladanRanking,
            ],
        ]);
    }

    private function summaryProfileIds(ProfilBulanModel $profil, string $scope): array
    {
        $rootId = (int) ($profil->parent_profil_bulan_id ?: ($profil->group_root_id ?: $profil->id));
        $ids = ProfilBulanModel::query()
            ->where(function ($q) use ($rootId) {
                $q->where('id', $rootId)
                    ->orWhere('parent_profil_bulan_id', $rootId)
                    ->orWhere('group_root_id', $rootId);
            })
            ->get(['id', 'parent_profil_bulan_id'])
            ->filter(function ($row) use ($scope, $rootId) {
                $isMain = (int) $row->id === $rootId || empty($row->parent_profil_bulan_id);
                if ($scope === 'main') {
                    return $isMain;
                }
                if ($scope === 'sub') {
                    return ! $isMain;
                }
                return true;
            })
            ->pluck('id')
            ->map(fn ($id) => (int) $id)
            ->filter()
            ->values()
            ->all();

        if ($ids) {
            return $ids;
        }

        return $scope === 'sub' ? [0] : [(int) $profil->id];
    }

    private function dashboardMorningSummaryForDate(Carbon $date, array $employeeKeys = []): ?array
    {
        try {
            $request = Request::create('/dashboard/attendance-area-by-date', 'GET', [
                'date' => $date->format('Y-m-d'),
                'mode' => 'morning',
                'include_expired_contracts' => 1,
            ]);
            $payload = app(DashboardController::class)->attendanceAreaByDate($request)->getData(true);
            $rows = (array) data_get($payload, 'employee_drilldown.rows', []);
            if ($employeeKeys !== []) {
                $allowed = array_fill_keys(array_map('strval', $employeeKeys), true);
                $rows = array_values(array_filter($rows, fn ($row) => isset($allowed[trim((string) ($row['id_finger'] ?? ''))])));
            }
            $count = fn (string $category): int => count(array_filter($rows, fn ($row) => (string) ($row['category'] ?? '') === $category));
            $leave = $count('cuti') + $count('sick') + $count('leaveNoPay');
            $alpha = $count('missing');

            return [
                'employees' => count($rows),
                'hadir_total' => $count('ontime') + $count('latePre') + $count('lateGrace') + $count('nonShift'),
                'cuti_total' => $leave,
                'sick_total' => 0,
                'alpha_total' => $alpha,
                'alpha_weighted_total' => $alpha * 3,
                'telat_total' => $count('latePre') + $count('lateGrace'),
                'summary_source' => 'dashboard_morning',
            ];
        } catch (\Throwable $e) {
            report($e);
            return null;
        }
    }

    // =========================================================================
    // exportSummaryExcel() - Export ringkasan ke Excel
    // Dipanggil dari: GET /attendance-review/summary-export-excel
    // Output: Response (bervariasi)
    // =========================================================================
    public function exportSelectedSchedulePivot(Request $request)
    {
        $ids = collect($request->input('karyawan_ids', []))->map(fn ($id) => (int) $id)->filter()->unique()->values();
        if ($ids->isEmpty() && $request->filled('karyawan_id')) $ids = collect([(int) $request->input('karyawan_id')]);
        $from = Carbon::parse((string) $request->input('date_from'))->startOfDay();
        $to = Carbon::parse((string) $request->input('date_to'))->startOfDay();
        if ($ids->isEmpty() || $from->gt($to)) abort(422, 'Pilih user dan periode valid.');
        $employees = KaryawanModel::query()->whereIn('id', $ids)->get(['id', 'finger_id', 'full_name'])->keyBy('id');
        $shifts = ProfilJamKerjaModel::query()->get(['id', 'code', 'name'])->keyBy('id');
        $schedules = DB::table('master_shift_schedules')->whereIn('karyawan_id', $ids->all())->whereBetween('work_date', [$from->toDateString(), $to->toDateString()])->where('is_active', true)->orderByDesc('id')->get(['karyawan_id', 'work_date', 'profil_jam_kerja_id']);
        $map = [];
        foreach ($schedules as $schedule) $map[(int) $schedule->karyawan_id.'|'.Carbon::parse($schedule->work_date)->toDateString()] ??= $schedule;
        $dates = [];
        for ($date = $from->copy(); $date->lte($to); $date->addDay()) $dates[] = $date->toDateString();
        $headings = ['kd_finger', 'karyawan', ...array_map(fn ($date) => Carbon::parse($date)->format('d-m-Y'), $dates)];
        $rows = [];
        foreach ($employees as $employee) {
            $row = [(string) ($employee->finger_id ?? ''), (string) ($employee->full_name ?? '')];
            foreach ($dates as $date) {
                $schedule = $map[(int) $employee->id.'|'.$date] ?? null;
                $shift = $schedule ? ($shifts[(int) $schedule->profil_jam_kerja_id] ?? null) : null;
                $row[] = $shift ? trim((string) ($shift->code ?: $shift->name)) : '-';
            }
            $rows[] = $row;
        }
        return Excel::download(new SelectedSchedulePivotExport($headings, $rows), 'jadwal-selected-'.$from->format('Ymd').'-'.$to->format('Ymd').'.xlsx');
    }
    public function exportSummaryExcel(Request $request)
    {
        $resp = $this->summaryData($request);
        if ($resp->getStatusCode() !== 200) {
            $payload = $resp->getData(true);
            abort($resp->getStatusCode(), (string) ($payload['message'] ?? 'Gagal export summary'));
        }

        $payload = $resp->getData(true);
        $dataRows = is_array($payload['data'] ?? null) ? $payload['data'] : [];
        $meta = is_array($payload['meta'] ?? null) ? $payload['meta'] : [];
        $profil = is_array($meta['profil'] ?? null) ? $meta['profil'] : [];
        $dates = is_array($meta['dates'] ?? null) ? $meta['dates'] : [];

        $headings = [
            'No',
            'Kode',
            'Nama',
            'Pay',
            'No Pay',
            'Hadir',
            'Alpha',
            'Telat',
            'Score',
        ];
        foreach ($dates as $d) {
            $headings[] = (string) $d;
        }

        $rows = [];
        foreach ($dataRows as $row) {
            if (! is_array($row)) {
                continue;
            }

            $daily = is_array($row['daily'] ?? null) ? $row['daily'] : [];
            $out = [
                (int) ($row['no'] ?? 0),
                (string) ($row['employee_code'] ?? ''),
                (string) ($row['employee_name'] ?? ''),
                (int) ($row['pay_days'] ?? 0),
                (int) ($row['no_pay_days'] ?? 0),
                (int) ($row['hadir_total'] ?? 0),
                (int) ($row['alpha'] ?? 0),
                (int) ($row['telat_total'] ?? 0),
                (int) ($row['violation_score'] ?? 0),
            ];

            foreach ($dates as $d) {
                $cell = is_array($daily[$d] ?? null) ? $daily[$d] : null;
                $code = $cell ? (string) ($cell['code'] ?? '') : '';
                if ($cell && ! empty($cell['is_lembur'])) {
                    $code = $code === '' ? '*' : ($code.'*');
                }
                $out[] = $code;
            }

            $rows[] = $out;
        }

        $profilCode = trim((string) ($profil['code'] ?? ''));
        $selectedStart = trim((string) ($profil['selected_start_date'] ?? ''));
        $selectedEnd = trim((string) ($profil['selected_end_date'] ?? ''));
        $suffix = trim(implode('-', array_filter([$profilCode, $selectedStart, $selectedEnd])));
        $filename = 'attendance-review-summary'.($suffix !== '' ? ('-'.$suffix) : '').'-'.now()->format('Ymd-His').'.xlsx';

        return Excel::download(new AttendanceReviewSummaryExport($headings, $rows), $filename);
    }

    // =========================================================================
    // exportSummaryPdf() - Export ringkasan ke PDF
    // Dipanggil dari: GET /attendance-review/summary-export-pdf
    // Output: Response (bervariasi)
    // =========================================================================
    public function exportSummaryPdf(Request $request)
    {
        $resp = $this->summaryData($request);
        if ($resp->getStatusCode() !== 200) {
            $payload = $resp->getData(true);
            abort($resp->getStatusCode(), (string) ($payload['message'] ?? 'Gagal export summary'));
        }

        $payload = $resp->getData(true);
        $meta = is_array($payload['meta'] ?? null) ? $payload['meta'] : [];
        $profil = is_array($meta['profil'] ?? null) ? $meta['profil'] : [];

        $profilCode = trim((string) ($profil['code'] ?? ''));
        $selectedStart = trim((string) ($profil['selected_start_date'] ?? ''));
        $selectedEnd = trim((string) ($profil['selected_end_date'] ?? ''));
        $suffix = trim(implode('-', array_filter([$profilCode, $selectedStart, $selectedEnd])));
        $filename = 'attendance-review-summary'.($suffix !== '' ? ('-'.$suffix) : '').'-'.now()->format('Ymd-His').'.pdf';

        $pdf = Pdf::loadView('attendancereview::exports.summary_pdf', [
            'payload' => $payload,
        ])->setPaper('a4', 'landscape');

        return $pdf->download($filename);
    }

    // =========================================================================
    // disciplineCheckProfile() - Cek profil disiplin karyawan
    // Dipanggil dari: POST /attendance-review/discipline/check-profile
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function disciplineCheckProfile(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['required', 'integer', 'exists:master_karyawans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profil = ProfilBulanModel::query()->findOrFail((int) $request->input('profil_bulan_id'));
        [$startDate, $endDate] = $this->resolveSummaryPeriod($profil, $request);
        $evaluation = $this->evaluateDisciplineProfile((int) $profil->id, (int) $request->input('karyawan_id'), $startDate, $endDate);

        return response()->json([
            'data' => $evaluation,
        ]);
    }

    // =========================================================================
    // disciplineIssueWarningLetter() - Terbitkan surat peringatan
    // Dipanggil dari: POST /attendance-review/discipline/issue-warning-letter
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function disciplineIssueWarningLetter(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['required', 'integer', 'exists:master_karyawans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
            'notes' => ['nullable', 'string', 'max:1000'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profil = ProfilBulanModel::query()->findOrFail((int) $request->input('profil_bulan_id'));
        $karyawanId = (int) $request->input('karyawan_id');
        [$startDate, $endDate] = $this->resolveSummaryPeriod($profil, $request);

        $evaluation = $this->evaluateDisciplineProfile((int) $profil->id, $karyawanId, $startDate, $endDate);
        if (! (bool) ($evaluation['can_issue'] ?? false)) {
            return response()->json([
                'message' => (string) ($evaluation['reason'] ?? 'Kriteria penerbitan SP belum terpenuhi.'),
                'data' => $evaluation,
            ], 422);
        }

        $issued = null;
        try {
            DB::transaction(function () use (&$issued, $request, $profil, $karyawanId, $startDate, $endDate): void {
                $evaluation = $this->evaluateDisciplineProfile((int) $profil->id, $karyawanId, $startDate, $endDate);
                if (! (bool) ($evaluation['can_issue'] ?? false)) {
                    throw new \RuntimeException((string) ($evaluation['reason'] ?? 'Kriteria penerbitan SP belum terpenuhi.'));
                }

                $existingThisPeriod = AttendanceWarningLetterModel::query()
                    ->where('profil_bulan_id', (int) $profil->id)
                    ->where('karyawan_id', $karyawanId)
                    ->first();
                if ($existingThisPeriod && (string) ($existingThisPeriod->status ?? '') !== 'revoked') {
                    throw new \RuntimeException('SP untuk karyawan ini pada profil bulan terpilih sudah pernah diterbitkan.');
                }

                $nextLevel = (int) ($evaluation['next_sp_level'] ?? 0);
                if ($nextLevel < 1 || $nextLevel > 3) {
                    throw new \RuntimeException('Level SP tidak valid.');
                }

                $issuedAt = now();
                $employeeCode = (string) ($evaluation['employee_code'] ?? '');
                $letterNo = $this->generateWarningLetterNo($nextLevel, $employeeCode, $issuedAt);
                $validDays = $this->warningLetterValidDays();
                $validUntil = $issuedAt->copy()->addDays($validDays)->startOfDay();

                $payload = is_array($existingThisPeriod?->payload) ? $existingThisPeriod->payload : [];
                $payload['last_issue'] = [
                    'issued_at' => $issuedAt->format('Y-m-d H:i:s'),
                    'issued_by' => (int) (auth()->id() ?: 0),
                ];
                $payload['evaluation'] = $evaluation;

                if ($existingThisPeriod && (string) ($existingThisPeriod->status ?? '') === 'revoked') {
                    $existingThisPeriod->fill([
                        'sp_level' => $nextLevel,
                        'letter_no' => $letterNo,
                        'period_start' => $startDate->format('Y-m-d'),
                        'period_end' => $endDate->format('Y-m-d'),
                        'alpha_count' => (int) ($evaluation['alpha'] ?? 0),
                        'telat_count' => (int) ($evaluation['telat'] ?? 0),
                        'violation_score' => (int) ($evaluation['violation_score'] ?? 0),
                        'payload' => $payload,
                        'notes' => $request->filled('notes') ? (string) $request->input('notes') : null,
                        'status' => 'issued',
                        'issued_by' => auth()->id(),
                        'issued_at' => $issuedAt->format('Y-m-d H:i:s'),
                        'valid_days' => $validDays,
                        'valid_until' => $validUntil->format('Y-m-d'),
                        'revoked_by' => null,
                        'revoked_at' => null,
                        'revoke_reason' => null,
                    ]);
                    $existingThisPeriod->save();
                    $issued = $existingThisPeriod->fresh();
                } else {
                    $issued = AttendanceWarningLetterModel::query()->create([
                        'profil_bulan_id' => (int) $profil->id,
                        'karyawan_id' => $karyawanId,
                        'sp_level' => $nextLevel,
                        'letter_no' => $letterNo,
                        'period_start' => $startDate->format('Y-m-d'),
                        'period_end' => $endDate->format('Y-m-d'),
                        'alpha_count' => (int) ($evaluation['alpha'] ?? 0),
                        'telat_count' => (int) ($evaluation['telat'] ?? 0),
                        'violation_score' => (int) ($evaluation['violation_score'] ?? 0),
                        'payload' => $payload,
                        'notes' => $request->filled('notes') ? (string) $request->input('notes') : null,
                        'status' => 'issued',
                        'issued_by' => auth()->id(),
                        'issued_at' => $issuedAt->format('Y-m-d H:i:s'),
                        'valid_days' => $validDays,
                        'valid_until' => $validUntil->format('Y-m-d'),
                    ]);
                }
            });
        } catch (\RuntimeException $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }

        return response()->json([
            'message' => 'Surat peringatan berhasil diterbitkan.',
            'data' => [
                'id' => (int) $issued->id,
                'letter_no' => $issued->letter_no,
                'sp_level' => (int) $issued->sp_level,
                'karyawan_id' => (int) $issued->karyawan_id,
                'profil_bulan_id' => (int) $issued->profil_bulan_id,
                'period_start' => optional($issued->period_start)->format('Y-m-d'),
                'period_end' => optional($issued->period_end)->format('Y-m-d'),
                'issued_at' => optional($issued->issued_at)->format('Y-m-d H:i:s'),
                'valid_until' => optional($issued->valid_until)->format('Y-m-d'),
                'pdf_url' => route('attendance_review.discipline.warning_letter_pdf', ['id' => (int) $issued->id]),
            ],
        ]);
    }

    // =========================================================================
    // disciplineWarningLetterPdf() - Download PDF surat peringatan
    // Dipanggil dari: GET /attendance-review/discipline/warning-letter/{id}/pdf
    // Output: Response (bervariasi)
    // =========================================================================
    public function disciplineWarningLetterPdf(string $id)
    {
        $row = AttendanceWarningLetterModel::query()
            ->with(['karyawan:id,employee_code,full_name', 'profilBulan:id,code,name,start_date,end_date', 'issuer:id,name'])
            ->findOrFail((int) $id);
        if (! in_array((string) ($row->status ?? ''), ['issued', 'revoked'], true)) {
            abort(404);
        }

        $payload = is_array($row->payload) ? $row->payload : [];
        $companyName = (string) (config('app.name') ?: 'Perusahaan');
        $issuedAt = $row->issued_at instanceof Carbon ? $row->issued_at->copy() : now();
        $validDays = (int) ($row->valid_days ?? 0);
        if ($validDays < 1) {
            $validDays = $this->warningLetterValidDays();
        }
        $validUntil = $row->valid_until instanceof Carbon
            ? $row->valid_until->copy()->startOfDay()
            : $issuedAt->copy()->addDays($validDays)->startOfDay();
        $revokedAtText = $row->revoked_at instanceof Carbon ? $row->revoked_at->locale('id')->translatedFormat('d F Y') : null;

        $pdf = Pdf::loadView('attendancereview::exports.warning_letter_pdf', [
            'company_name' => $companyName,
            'row' => $row,
            'payload' => $payload,
            'issued_at_text' => $issuedAt->locale('id')->translatedFormat('d F Y'),
            'valid_days' => $validDays,
            'valid_until_text' => $validUntil->locale('id')->translatedFormat('d F Y'),
            'revoked_at_text' => $revokedAtText,
            'period_start' => optional($row->period_start)->format('Y-m-d'),
            'period_end' => optional($row->period_end)->format('Y-m-d'),
            'threshold' => $payload['threshold'] ?? (self::SP_THRESHOLDS[(int) ($row->sp_level ?? 1)] ?? ['score' => 0, 'alpha' => 0]),
        ])->setPaper('a4', 'portrait');

        $filename = 'surat-peringatan-'.Str::slug((string) ($row->letter_no ?: ('sp-'.$row->id))).'.pdf';

        return $pdf->download($filename);
    }

    // =========================================================================
    // updateDisciplineSettings() - Update setting disiplin
    // Dipanggil dari: POST /attendance-review/discipline/settings
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function updateDisciplineSettings(Request $request): JsonResponse
    {
        $user = $request->user();
        if (! $this->isAdministrator($user)) {
            return response()->json(['message' => 'No access'], 403);
        }

        $validator = Validator::make($request->all(), [
            'warning_letter_no_template' => ['required', 'string', 'max:200'],
            'warning_letter_no_sequence_pad' => ['required', 'integer', 'min:1', 'max:10'],
            'warning_letter_valid_days' => ['required', 'integer', 'min:1', 'max:3650'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $template = trim((string) $request->input('warning_letter_no_template'));
        $defaultTemplate = $this->defaultWarningLetterNoTemplate();
        if ($template === '') {
            $template = $defaultTemplate;
        }

        $pad = (int) $request->input('warning_letter_no_sequence_pad');
        $validDays = (int) $request->input('warning_letter_valid_days');
        AppSetting::query()->updateOrCreate(
            ['key' => 'attendance_review.warning_letter_no_template'],
            ['value' => $template]
        );
        AppSetting::query()->updateOrCreate(
            ['key' => 'attendance_review.warning_letter_no_sequence_pad'],
            ['value' => (string) $pad]
        );
        AppSetting::query()->updateOrCreate(
            ['key' => 'attendance_review.warning_letter_valid_days'],
            ['value' => (string) $validDays]
        );

        return response()->json([
            'message' => 'Discipline settings updated',
            'data' => [
                'warning_letter_no_template' => $template,
                'warning_letter_no_sequence_pad' => $pad,
                'warning_letter_valid_days' => $validDays,
                'warning_letter_no_template_default' => $defaultTemplate,
            ],
        ]);
    }

    // =========================================================================
    // disciplineRevokeWarningLetter() - Cabut surat peringatan
    // Dipanggil dari: POST /attendance-review/discipline/warning-letter/{id}/revoke
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function disciplineRevokeWarningLetter(string $id, Request $request): JsonResponse
    {
        if (! $this->isAdministrator(auth()->user())) {
            return response()->json(['message' => 'No access'], 403);
        }

        $validator = Validator::make($request->all(), [
            'reason' => ['required', 'string', 'max:1000'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        /** @var AttendanceWarningLetterModel $row */
        $row = AttendanceWarningLetterModel::query()->findOrFail((int) $id);
        if ((string) ($row->status ?? '') !== 'issued') {
            return response()->json(['message' => 'Hanya SP yang statusnya issued yang bisa dibatalkan.'], 422);
        }

        $reason = trim((string) $request->input('reason'));
        DB::transaction(function () use ($row, $reason): void {
            $payload = is_array($row->payload) ? $row->payload : [];
            $history = [];
            if (isset($payload['revoke_history']) && is_array($payload['revoke_history'])) {
                $history = $payload['revoke_history'];
            }
            $history[] = [
                'revoked_at' => now()->format('Y-m-d H:i:s'),
                'revoked_by' => (int) (auth()->id() ?: 0),
                'reason' => $reason,
            ];
            $payload['revoke_history'] = $history;

            $row->status = 'revoked';
            $row->revoked_by = (int) (auth()->id() ?: 0);
            $row->revoked_at = now();
            $row->revoke_reason = $reason;
            $row->payload = $payload;
            $row->save();
        });

        return response()->json([
            'message' => 'SP berhasil dibatalkan (revoked).',
            'data' => [
                'id' => (int) $row->id,
                'status' => (string) ($row->status ?? ''),
            ],
        ]);
    }

    // =========================================================================
    // warningLetterValidDays() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function warningLetterValidDays(): int
    {
        $raw = (int) (AppSetting::query()->where('key', 'attendance_review.warning_letter_valid_days')->value('value') ?: 90);
        if ($raw < 1) {
            return 90;
        }
        if ($raw > 3650) {
            return 3650;
        }

        return $raw;
    }

    // =========================================================================
    // resolveSummaryPeriod() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveSummaryPeriod(ProfilBulanModel $profil, Request $request): array
    {
        $profileStartDate = Carbon::parse($profil->start_date)->startOfDay();
        $profileEndDate = Carbon::parse($profil->end_date)->startOfDay();
        $startDate = $request->filled('date_from')
            ? Carbon::parse((string) $request->input('date_from'))->startOfDay()
            : $profileStartDate->copy();
        $endDate = $request->filled('date_to')
            ? Carbon::parse((string) $request->input('date_to'))->startOfDay()
            : $profileEndDate->copy();
        if ($startDate->lt($profileStartDate)) {
            $startDate = $profileStartDate->copy();
        }
        if ($endDate->gt($profileEndDate)) {
            $endDate = $profileEndDate->copy();
        }
        if ($endDate->lt($startDate)) {
            $endDate = $startDate->copy();
        }

        return [$startDate, $endDate];
    }

    // =========================================================================
    // evaluateDisciplineProfile() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function evaluateDisciplineProfile(int $profilId, int $karyawanId, Carbon $startDate, Carbon $endDate): array
    {
        $internalReq = Request::create('/attendance-review/summary-data', 'GET', [
            'profil_bulan_id' => $profilId,
            'date_from' => $startDate->format('Y-m-d'),
            'date_to' => $endDate->format('Y-m-d'),
        ]);
        $internalResp = $this->summaryData($internalReq);
        if ($internalResp->getStatusCode() !== 200) {
            return [
                'karyawan_id' => $karyawanId,
                'employee_code' => '',
                'employee_name' => '',
                'profil_bulan_id' => $profilId,
                'period_start' => $startDate->format('Y-m-d'),
                'period_end' => $endDate->format('Y-m-d'),
                'alpha' => 0,
                'telat' => 0,
                'violation_score' => 0,
                'next_sp_level' => 1,
                'threshold' => self::SP_THRESHOLDS[1],
                'qualified_by_score' => false,
                'qualified_by_alpha' => false,
                'can_issue' => false,
                'reason' => 'Gagal mengevaluasi summary periode.',
                'already_issued_this_period' => false,
                'last_letter' => null,
                'history' => [],
            ];
        }
        $payload = $internalResp->getData(true);

        $employeeRow = collect($payload['data'] ?? [])
            ->first(fn (array $row) => (int) ($row['karyawan_id'] ?? 0) === $karyawanId);

        $employee = KaryawanModel::query()->find($karyawanId);
        $employeeCode = (string) ($employeeRow['employee_code'] ?? $employee?->employee_code ?? '');
        $employeeName = (string) ($employeeRow['employee_name'] ?? $employee?->full_name ?? '');
        $alpha = (int) ($employeeRow['alpha'] ?? 0);
        $telat = (int) ($employeeRow['telat_total'] ?? 0);
        $score = (int) ($employeeRow['violation_score'] ?? 0);

        $today = now()->startOfDay();
        $issuedHistory = AttendanceWarningLetterModel::query()
            ->where('karyawan_id', $karyawanId)
            ->orderByDesc('issued_at')
            ->orderByDesc('id')
            ->get();

        $activeLetters = $issuedHistory
            ->where('status', 'issued')
            ->filter(function (AttendanceWarningLetterModel $row) use ($today) {
                if (! $row->valid_until) {
                    return true;
                }

                return Carbon::parse((string) $row->valid_until)->startOfDay()->gte($today);
            })
            ->values();

        $lastIssued = $activeLetters->first();
        $alreadyIssuedThisPeriod = $issuedHistory->first(function (AttendanceWarningLetterModel $row) use ($profilId) {
            return (int) $row->profil_bulan_id === $profilId && (string) $row->status !== 'revoked';
        });

        $nextLevel = 1;
        if ($lastIssued) {
            $lastLevel = (int) ($lastIssued->sp_level ?? 0);
            $nextLevel = $lastLevel >= 3 ? 3 : ($lastLevel + 1);
        }
        $threshold = self::SP_THRESHOLDS[$nextLevel] ?? ['score' => 99999, 'alpha' => 99999];
        $qualifiedByScore = $score >= (int) ($threshold['score'] ?? 0);
        $qualifiedByAlpha = $alpha >= (int) ($threshold['alpha'] ?? 0);

        $canIssue = true;
        $reason = 'Kriteria terpenuhi.';
        if (! $employeeRow) {
            $canIssue = false;
            $reason = 'Data karyawan tidak ditemukan pada hasil summary periode ini.';
        } elseif ($alreadyIssuedThisPeriod) {
            $canIssue = false;
            $reason = 'SP pada profil bulan yang sama sudah diterbitkan.';
        } elseif ($lastIssued && (int) ($lastIssued->sp_level ?? 0) >= 3) {
            $canIssue = false;
            $reason = 'Karyawan sudah mencapai SP3.';
        } elseif ($lastIssued && $lastIssued->period_end && $startDate->lte(Carbon::parse($lastIssued->period_end)->startOfDay())) {
            $canIssue = false;
            $reason = 'Periode evaluasi harus lebih baru dari periode SP sebelumnya.';
        } elseif (! $qualifiedByScore && ! $qualifiedByAlpha) {
            $canIssue = false;
            $reason = "Belum memenuhi ambang SP{$nextLevel} (score >= {$threshold['score']} atau alpha >= {$threshold['alpha']}).";
        }

        return [
            'karyawan_id' => $karyawanId,
            'employee_code' => $employeeCode,
            'employee_name' => $employeeName,
            'profil_bulan_id' => $profilId,
            'period_start' => $startDate->format('Y-m-d'),
            'period_end' => $endDate->format('Y-m-d'),
            'alpha' => $alpha,
            'telat' => $telat,
            'violation_score' => $score,
            'next_sp_level' => $nextLevel,
            'threshold' => [
                'score' => (int) ($threshold['score'] ?? 0),
                'alpha' => (int) ($threshold['alpha'] ?? 0),
            ],
            'qualified_by_score' => $qualifiedByScore,
            'qualified_by_alpha' => $qualifiedByAlpha,
            'can_issue' => $canIssue,
            'reason' => $reason,
            'already_issued_this_period' => (bool) $alreadyIssuedThisPeriod,
            'last_letter' => $lastIssued ? [
                'id' => (int) $lastIssued->id,
                'sp_level' => (int) ($lastIssued->sp_level ?? 0),
                'letter_no' => (string) ($lastIssued->letter_no ?? ''),
                'period_start' => optional($lastIssued->period_start)->format('Y-m-d'),
                'period_end' => optional($lastIssued->period_end)->format('Y-m-d'),
                'issued_at' => optional($lastIssued->issued_at)->format('Y-m-d H:i:s'),
                'valid_until' => optional($lastIssued->valid_until)->format('Y-m-d'),
                'violation_score' => (int) ($lastIssued->violation_score ?? 0),
                'pdf_url' => route('attendance_review.discipline.warning_letter_pdf', ['id' => (int) $lastIssued->id]),
            ] : null,
            'history' => $issuedHistory
                ->take(20)
                ->map(function (AttendanceWarningLetterModel $row) use ($today) {
                    $status = (string) ($row->status ?? '');
                    $isExpired = false;
                    if ($status === 'issued' && $row->valid_until) {
                        $isExpired = Carbon::parse((string) $row->valid_until)->startOfDay()->lt($today);
                    }
                    $effectiveStatus = $isExpired ? 'expired' : $status;

                    return [
                        'id' => (int) $row->id,
                        'sp_level' => (int) ($row->sp_level ?? 0),
                        'letter_no' => (string) ($row->letter_no ?? ''),
                        'period_start' => optional($row->period_start)->format('Y-m-d'),
                        'period_end' => optional($row->period_end)->format('Y-m-d'),
                        'issued_at' => optional($row->issued_at)->format('Y-m-d H:i:s'),
                        'valid_days' => (int) ($row->valid_days ?? 0),
                        'valid_until' => optional($row->valid_until)->format('Y-m-d'),
                        'status' => $effectiveStatus,
                        'pdf_url' => route('attendance_review.discipline.warning_letter_pdf', ['id' => (int) $row->id]),
                    ];
                })
                ->values()
                ->all(),
        ];
    }

    // =========================================================================
    // defaultWarningLetterNoTemplate() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function defaultWarningLetterNoTemplate(): string
    {
        return 'SP-{sp_level}/{sequence_padded}/HRD/{month_roman}/{year}/{employee_code}';
    }

    // =========================================================================
    // isAdministrator() - Cek kondisi tertentu, return bool
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function isAdministrator(?UserModels $user): bool
    {
        if (! $user) {
            return false;
        }

        $user->loadMissing('roles');
        $activeRoles = $user->roles->filter(fn ($role) => (bool) ($role->pivot->is_active ?? true));

        return $activeRoles->contains(function ($role) {
            $slug = strtolower((string) ($role->slug ?? ''));
            $name = strtolower((string) ($role->name ?? ''));

            return in_array($slug, ['administrator', 'super-admin'], true)
                || in_array($name, ['administrator', 'super admin'], true);
        });
    }

    // =========================================================================
    // isHrd() - Cek kondisi tertentu, return bool
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function isHrd(?UserModels $user): bool
    {
        if (! $user) {
            return false;
        }

        $dept = strtolower(trim((string) ($user->department ?? '')));
        if ($dept !== '') {
            // Common department labels in this app: HR, HRD, Human Resource, etc.
            if (in_array($dept, ['hr', 'hrd', 'human resource', 'human resources'], true)) {
                return true;
            }
            if (str_starts_with($dept, 'hr')) {
                return true;
            }
        }

        $user->loadMissing('roles');
        $activeRoles = $user->roles->filter(fn ($role) => (bool) ($role->pivot->is_active ?? true));

        return $activeRoles->contains(function ($role) {
            $slug = strtolower((string) ($role->slug ?? ''));
            $name = strtolower((string) ($role->name ?? ''));

            return in_array($slug, ['hr', 'hrd'], true)
                || in_array($name, ['hr', 'hrd', 'human resource', 'human resources'], true);
        });
    }

    // =========================================================================
    // canBypassIngestDateLockForUser() - Cek kondisi tertentu, return bool
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function canBypassIngestDateLockForUser(): bool
    {
        $u = auth()->user();

        return $this->isAdministrator($u) || $this->isHrd($u);
    }

    // =========================================================================
    // generateWarningLetterNo() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function generateWarningLetterNo(int $spLevel, string $employeeCode, Carbon $issuedAt): string
    {
        $year = (int) $issuedAt->format('Y');
        $sequence = AttendanceWarningLetterModel::query()
            ->where('sp_level', $spLevel)
            ->whereYear('issued_at', $year)
            ->lockForUpdate()
            ->count() + 1;

        $safeCode = strtoupper(preg_replace('/[^A-Z0-9]/', '', $employeeCode));
        if ($safeCode === '') {
            $safeCode = 'EMP';
        }
        $romanMonth = $this->romanMonth((int) $issuedAt->format('m'));

        $template = trim((string) (AppSetting::query()->where('key', 'attendance_review.warning_letter_no_template')->value('value') ?: ''));
        if ($template === '') {
            $template = $this->defaultWarningLetterNoTemplate();
        }
        $pad = (int) (AppSetting::query()->where('key', 'attendance_review.warning_letter_no_sequence_pad')->value('value') ?: 4);
        if ($pad < 1 || $pad > 10) {
            $pad = 4;
        }

        $letterNo = strtr($template, [
            '{sp_level}' => (string) $spLevel,
            '{sequence}' => (string) $sequence,
            '{sequence_padded}' => str_pad((string) $sequence, $pad, '0', STR_PAD_LEFT),
            '{month_roman}' => $romanMonth,
            '{month}' => $issuedAt->format('m'),
            '{year}' => (string) $year,
            '{employee_code}' => $safeCode,
        ]);
        $letterNo = trim((string) preg_replace('/\\s+/', ' ', $letterNo));
        if ($letterNo === '') {
            $letterNo = sprintf('SP-%d/%04d/HRD/%s/%d/%s', $spLevel, $sequence, $romanMonth, $year, $safeCode);
        }

        return $letterNo;
    }

    // =========================================================================
    // romanMonth() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function romanMonth(int $month): string
    {
        $map = [
            1 => 'I', 2 => 'II', 3 => 'III', 4 => 'IV', 5 => 'V', 6 => 'VI',
            7 => 'VII', 8 => 'VIII', 9 => 'IX', 10 => 'X', 11 => 'XI', 12 => 'XII',
        ];

        return $map[$month] ?? 'I';
    }

    // =========================================================================
    // refs() - Referensi data untuk dropdown/filter
    // Dipanggil dari: GET /attendance-review/refs
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function refs(Request $request): JsonResponse
    {
        $profilBulans = ProfilBulanModel::query()
            ->orderByDesc('period_year')
            ->orderByDesc('period_month')
            ->get(['id', 'code', 'name', 'period_year', 'period_month', 'start_date', 'end_date', 'status', 'profile_kind', 'parent_profil_bulan_id', 'group_root_id'])
            ->map(fn ($row) => [
                'id' => (int) $row->id,
                'code' => $row->code,
                'name' => $row->name,
                'period_year' => (int) $row->period_year,
                'period_month' => (int) $row->period_month,
                'start_date' => optional($row->start_date)->format('Y-m-d'),
                'end_date' => optional($row->end_date)->format('Y-m-d'),
                'status' => $row->status,
                'profile_kind' => $row->profile_kind,
                'parent_profil_bulan_id' => $row->parent_profil_bulan_id ? (int) $row->parent_profil_bulan_id : null,
                'group_root_id' => $row->group_root_id ? (int) $row->group_root_id : null,
            ])
            ->values();

        $profileKaryawanIds = collect();
        if ($request->filled('profil_bulan_id')) {
            $profil = ProfilBulanModel::query()->find((int) $request->input('profil_bulan_id'));
            $scope = (string) $request->input('profile_scope', $request->input('attendance_profile_scope', 'both'));
            $scope = match ($scope) {
                'main' => 'main',
                'sub' => 'sub',
                'selected' => 'selected',
                default => 'both',
            };
            $profileIds = $scope === 'selected'
                ? [(int) $request->input('profil_bulan_id')]
                : ($profil ? $this->summaryProfileIds($profil, $scope) : [(int) $request->input('profil_bulan_id')]);
            $profileKaryawanIds = ProfilBulanKaryawanModel::query()
                ->whereIn('profil_bulan_id', $profileIds)
                ->where('is_active', true)
                ->pluck('karyawan_id')
                ->map(fn ($id) => (int) $id)
                ->filter()
                ->unique()
                ->values();
        }

        $karyawansQuery = KaryawanModel::query()
            ->orderBy('full_name');
        if ($request->filled('profil_bulan_id')) {
            $karyawansQuery->whereIn('id', $profileKaryawanIds->all());
        }
        $karyawans = $karyawansQuery->get(['id', 'employee_code', 'finger_id', 'full_name'])
            ->map(fn ($row) => [
                'id' => (int) $row->id,
                // UI Attendance Review: tampilkan finger_id sebagai kode utama (fallback ke employee_code).
                'code' => $row->finger_id ?: $row->employee_code,
                'employee_code' => $row->employee_code,
                'finger_id' => $row->finger_id,
                'name' => $row->full_name,
            ])
            ->values();

        $roundings = PembulatanJamModel::query()
            ->where('is_active', true)
            ->orderBy('name')
            ->get(['id', 'code', 'name', 'target_type', 'round_method', 'interval_minutes', 'discipline_mode'])
            ->map(fn ($row) => [
                'id' => (int) $row->id,
                'code' => $row->code,
                'name' => $row->name,
                'target_type' => $row->target_type,
                'round_method' => $row->round_method,
                'interval_minutes' => (int) $row->interval_minutes,
                'discipline_mode' => (bool) ($row->discipline_mode ?? false),
            ])
            ->values();

        return response()->json([
            'data' => [
                'profil_bulans' => $profilBulans,
                'karyawans' => $karyawans,
                'roundings' => $roundings,
            ],
        ]);
    }

    // =========================================================================
    // profilBulanOptions() - Opsi profil bulan untuk dropdown
    // Dipanggil dari: GET /attendance-review/refs/profil-bulans
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function profilBulanOptions(Request $request): JsonResponse
    {
        $search = trim((string) $request->input('q', $request->input('term', '')));
        $page = max(1, (int) $request->input('page', 1));
        $perPage = min(50, max(10, (int) $request->input('per_page', 20)));
        $cacheKey = 'attendance_review:profil_bulan_options:'.md5(json_encode([$search, $page, $perPage]));

        return response()->json(Cache::remember($cacheKey, 60, function () use ($search, $page, $perPage) {
            return $this->profilBulanOptionsPayload($search, $page, $perPage);
        }));
    }

    private function profilBulanOptionsPayload(string $search, int $page, int $perPage): array
    {
        $query = ProfilBulanModel::query()
            ->select(['id', 'code', 'name', 'period_year', 'period_month', 'start_date', 'end_date', 'status', 'profile_kind', 'parent_profil_bulan_id', 'group_root_id'])
            ->when($search !== '', function ($q) use ($search) {
                $like = '%'.str_replace(['%', '_'], ['\\%', '\\_'], $search).'%';
                $q->where(function ($sub) use ($like) {
                    $sub->where('code', 'like', $like)
                        ->orWhere('name', 'like', $like)
                        ->orWhere('status', 'like', $like)
                        ->orWhereRaw("DATE_FORMAT(start_date, '%Y-%m-%d') LIKE ?", [$like])
                        ->orWhereRaw("DATE_FORMAT(end_date, '%Y-%m-%d') LIKE ?", [$like]);
                });
            })
            ->orderByDesc('period_year')
            ->orderByDesc('period_month')
            ->orderByRaw('COALESCE(parent_profil_bulan_id, id) DESC')
            ->orderByRaw('CASE WHEN parent_profil_bulan_id IS NULL THEN 0 ELSE 1 END ASC')
            ->orderBy('sort_order')
            ->orderBy('priority_order')
            ->orderBy('id');

        $rows = $query
            ->skip(($page - 1) * $perPage)
            ->take($perPage + 1)
            ->get();

        $hasMore = $rows->count() > $perPage;
        $items = $rows->take($perPage)->map(fn ($row) => $this->formatProfilBulanOption($row))->values();

        return [
            'data' => $items,
            'results' => $items,
            'pagination' => [
                'more' => $hasMore,
            ],
        ];
    }

    // =========================================================================
    // formatProfilBulanOption() - Memformat data untuk output
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function formatProfilBulanOption($row): array
    {
        $startDate = optional($row->start_date)->format('Y-m-d');
        $endDate = optional($row->end_date)->format('Y-m-d');
        $isSub = strtolower(trim((string) ($row->profile_kind ?? ''))) === 'sub';
        $prefix = '';
        $labelParts = array_filter([
            trim((string) $row->code),
            trim((string) $row->name),
        ]);
        $dateLabel = $startDate && $endDate ? " ({$startDate} s/d {$endDate})" : '';
        $label = $prefix . implode(' - ', $labelParts) . $dateLabel;

        return [
            'id' => (int) $row->id,
            'text' => $label,
            'code' => $row->code,
            'name' => $row->name,
            'period_year' => (int) $row->period_year,
            'period_month' => (int) $row->period_month,
            'start_date' => $startDate,
            'end_date' => $endDate,
            'status' => $row->status,
            'profile_kind' => $isSub ? 'sub' : 'main',
        ];
    }

    /**
     * @return array<int, int>
     */
    // =========================================================================
    // resolveAttendanceReviewKaryawanIds() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveAttendanceReviewKaryawanIds(Request $request): array
    {
        $raw = $request->input('karyawan_ids', []);
        if (! is_array($raw)) {
            $raw = preg_split('/[,\s;]+/', (string) $raw) ?: [];
        }

        if ($request->filled('karyawan_id')) {
            $raw[] = $request->input('karyawan_id');
        }

        return collect($raw)
            ->flatten()
            ->map(fn ($id) => (int) $id)
            ->filter(fn (int $id) => $id > 0)
            ->unique()
            ->values()
            ->all();
    }

    // =========================================================================
    // bulkCreateAutomaticSpl() - Helper function internal
    // Dipanggil dari: Route/API endpoint
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function bulkCreateAutomaticSpl(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['required', 'integer', 'exists:master_karyawans,id'],
            'date_from' => ['required', 'date'],
            'date_to' => ['required', 'date', 'after_or_equal:date_from'],
            'selected_dates' => ['nullable', 'array'],
            'selected_dates.*' => ['date'],
            'approval_flow_id' => ['required', 'integer', 'exists:master_approval_flows,id'],
            'overtime_type' => ['nullable', 'string', 'in:'.implode(',', array_keys(SuratPerintahLemburModel::overtimeTypeOptions()))],
            'target_mode' => ['nullable', 'string', 'in:missing,extend,both,selected_manual,early_in'],
            'process_mode' => ['nullable', 'string', 'in:draft,submit,approve'],
            'reason' => ['nullable', 'string', 'max:2000'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $authUser = auth()->user();
        $canForceApprove = $this->isAdministrator($authUser) || $this->isHrd($authUser);
        $processMode = strtolower(trim((string) $request->input('process_mode', 'draft')));
        if ($processMode === 'approve' && ! $canForceApprove) {
            return response()->json(['message' => 'Langsung approved hanya untuk administrator/HRD.'], 403);
        }

        $profil = ProfilBulanModel::query()->findOrFail((int) $request->input('profil_bulan_id'));
        if ($guard = $this->guardProfilBulanOpenForAttendance($profil)) {
            return $guard;
        }
        $rangeStart = Carbon::parse((string) $request->input('date_from'))->startOfDay();
        $rangeEnd = Carbon::parse((string) $request->input('date_to'))->startOfDay();
        $profilStart = Carbon::parse((string) $profil->start_date)->startOfDay();
        $profilEnd = Carbon::parse((string) $profil->end_date)->startOfDay();
        if ($rangeStart->lt($profilStart)) {
            $rangeStart = $profilStart->copy();
        }
        if ($rangeEnd->gt($profilEnd)) {
            $rangeEnd = $profilEnd->copy();
        }
        if ($rangeEnd->lt($rangeStart)) {
            $rangeEnd = $rangeStart->copy();
        }

        $selectedDates = collect((array) $request->input('selected_dates', []))
            ->map(fn ($date) => trim((string) $date))
            ->filter()
            ->map(function (string $date) use ($profilStart, $profilEnd) {
                try {
                    $parsed = Carbon::parse($date)->startOfDay();
                } catch (\Throwable $e) {
                    return null;
                }

                if ($parsed->lt($profilStart) || $parsed->gt($profilEnd)) {
                    return null;
                }

                return $parsed->format('Y-m-d');
            })
            ->filter()
            ->unique()
            ->values();

        if ($selectedDates->isNotEmpty()) {
            $rangeStart = Carbon::parse((string) $selectedDates->min())->startOfDay();
            $rangeEnd = Carbon::parse((string) $selectedDates->max())->startOfDay();
        }

        $karyawanId = (int) $request->input('karyawan_id');
        $employeeIds = collect([$karyawanId]);
        $targetMode = strtolower(trim((string) $request->input('target_mode', 'both')));
        $overtimeType = strtolower(trim((string) $request->input('overtime_type', SuratPerintahLemburModel::OVERTIME_TYPE_NORMAL)));
        $defaultReason = trim((string) $request->input('reason'));
        if ($defaultReason === '') {
            $defaultReason = 'SPL otomatis dari Attendance Review V2.';
        }

        $reviews = AttendanceDailyReviewModel::query()
            ->where('profil_bulan_id', (int) $profil->id)
            ->where('karyawan_id', $karyawanId)
            ->whereDate('work_date', '>=', $rangeStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $rangeEnd->format('Y-m-d'))
            ->get()
            ->keyBy(fn (AttendanceDailyReviewModel $row) => optional($row->work_date)->format('Y-m-d'));

        $assignment = ProfilBulanKaryawanModel::query()
            ->where('profil_bulan_id', (int) $profil->id)
            ->where('karyawan_id', $karyawanId)
            ->first();
        $autoOvertimeWithoutSpl = $this->assignmentAllowsAutomaticOvertimeWithoutSpl($assignment);

        if ($reviews->isEmpty()) {
            return response()->json(['message' => 'Belum ada data review untuk karyawan pada rentang tanggal ini.'], 422);
        }

        $rawLogMinMaxMap = [];
        try {
            $rawLogAgg = AttendanceLogModel::query()
                ->where('karyawan_id', $karyawanId)
                ->whereBetween('log_at', [$rangeStart->copy()->startOfDay(), $rangeEnd->copy()->endOfDay()])
                ->selectRaw('DATE(log_at) as d, MIN(log_at) as min_at, MAX(log_at) as max_at')
                ->groupBy('d')
                ->get();

            foreach ($rawLogAgg as $row) {
                $dateKey = (string) ($row->d ?? '');
                if ($dateKey === '') {
                    continue;
                }
                $rawLogMinMaxMap[$dateKey] = [
                    'min_at' => ! empty($row->min_at) ? (string) $row->min_at : null,
                    'max_at' => ! empty($row->max_at) ? (string) $row->max_at : null,
                ];
            }
        } catch (\Throwable $e) {
            $rawLogMinMaxMap = [];
        }

        $overtimeApprovedMap = $this->buildOvertimeApprovedMap($employeeIds, $rangeStart->copy(), $rangeEnd->copy());
        $overtimeTagMap = $this->buildOvertimeTagMap($employeeIds, $rangeStart->copy(), $rangeEnd->copy());
        $overtimeEntryListMap = $this->buildOvertimeEntryListMap($employeeIds, $rangeStart->copy(), $rangeEnd->copy());

        $candidates = [];
        $appendContinuesEarlyInCandidate = function (string $dateKey, ?Carbon $plannedStart, ?Carbon $rawInAt, array $entriesOnDate, string $reasonPrefix) use (&$candidates, $overtimeType): void {
            if ($overtimeType !== SuratPerintahLemburModel::OVERTIME_TYPE_CONTINUES_NEXT_DAY) {
                return;
            }
            if (! $plannedStart instanceof Carbon || ! $rawInAt instanceof Carbon || ! $rawInAt->lt($plannedStart)) {
                return;
            }
            if ($this->hasOvertimeTypeInEntryList($entriesOnDate, SuratPerintahLemburModel::OVERTIME_TYPE_NORMAL)) {
                return;
            }

            $candidates[] = [
                'mode' => 'early_in_support',
                'date' => $dateKey,
                'start_at' => $rawInAt->copy(),
                'end_at' => $plannedStart->copy(),
                'minutes' => $rawInAt->diffInMinutes($plannedStart),
                'reason' => trim($reasonPrefix.' [Masuk cepat sebelum ContinuesNextDay]'),
                'overtime_type' => SuratPerintahLemburModel::OVERTIME_TYPE_NORMAL,
            ];
        };

        foreach (CarbonPeriod::create($rangeStart->copy(), $rangeEnd->copy()) as $date) {
            $dateKey = $date->format('Y-m-d');
            if ($selectedDates->isNotEmpty() && ! $selectedDates->contains($dateKey)) {
                continue;
            }
            /** @var AttendanceDailyReviewModel|null $review */
            $review = $reviews->get($dateKey);
            if (! $review) {
                continue;
            }

            $plannedStart = $review->planned_shift_start ? Carbon::parse((string) $review->planned_shift_start) : null;
            $plannedEnd = $review->planned_shift_end ? Carbon::parse((string) $review->planned_shift_end) : null;
            $rawLog = $rawLogMinMaxMap[$dateKey] ?? ['min_at' => null, 'max_at' => null];
            $rawIn = $rawLog['min_at'] ?: ($review->suggested_checkin_at ?: $review->checkin_at);
            $rawOut = $rawLog['max_at'] ?: ($review->suggested_checkout_at ?: $review->checkout_at);
            $rawInAt = $rawIn ? Carbon::parse((string) $rawIn) : null;
            $rawOutAt = $rawOut ? Carbon::parse((string) $rawOut) : null;
            $splKey = $karyawanId.'|'.$dateKey;
            $entriesOnDate = $overtimeEntryListMap[$splKey] ?? [];
            $hasApprovedSpl = isset($overtimeApprovedMap[$splKey]);

            if (($targetMode === 'selected_manual' && $selectedDates->contains($dateKey)) || $targetMode === 'early_in') {
                $manualCandidate = null;

                if ($plannedEnd instanceof Carbon && $rawOutAt instanceof Carbon && $rawOutAt->gt($plannedEnd)) {
                    $manualCandidate = [
                        'mode' => $targetMode === 'early_in' ? 'early_in' : 'selected_manual',
                        'date' => $dateKey,
                        'start_at' => $plannedEnd->copy(),
                        'end_at' => $rawOutAt->copy(),
                        'minutes' => $plannedEnd->diffInMinutes($rawOutAt),
                        'reason' => trim($defaultReason.($targetMode === 'early_in' ? ' [Masuk cepat]' : ' [Tanggal dipilih manual]')),
                    ];
                }

                if (! $manualCandidate && $plannedStart instanceof Carbon && $rawInAt instanceof Carbon && $rawInAt->lt($plannedStart)) {
                    $manualCandidate = [
                        'mode' => 'early_in',
                        'date' => $dateKey,
                        'start_at' => $rawInAt->copy(),
                        'end_at' => $plannedStart->copy(),
                        'minutes' => $rawInAt->diffInMinutes($plannedStart),
                        'reason' => trim($defaultReason.' [Masuk cepat]'),
                    ];
                }

                if (
                    ! $manualCandidate
                    && $hasApprovedSpl
                    && $plannedStart instanceof Carbon
                    && $plannedEnd instanceof Carbon
                    && $rawOutAt instanceof Carbon
                ) {
                    $approvedWindow = $this->resolveApprovedOvertimeWindowForShift(
                        $overtimeApprovedMap[$splKey] ?? [],
                        $plannedStart,
                        $plannedEnd
                    );
                    if (($approvedWindow['post_end'] ?? null) instanceof Carbon && $rawOutAt->gt($approvedWindow['post_end'])) {
                        /** @var Carbon $approvedPostEnd */
                        $approvedPostEnd = $approvedWindow['post_end'];
                        $manualCandidate = [
                            'mode' => 'extend',
                            'date' => $dateKey,
                            'start_at' => $approvedPostEnd->copy(),
                            'end_at' => $rawOutAt->copy(),
                            'minutes' => $approvedPostEnd->diffInMinutes($rawOutAt),
                            'reason' => trim($defaultReason.' [Extend SPL]'),
                        ];
                    }
                }

                if ($manualCandidate) {
                    $hasSameTypeSplOnManual = $this->hasOvertimeTypeInEntryList($entriesOnDate, $overtimeType);
                    if (! $hasSameTypeSplOnManual) {
                        $candidates[] = $manualCandidate;
                        if (
                            ($manualCandidate['mode'] ?? '') !== 'early_in'
                            && ($manualCandidate['overtime_type'] ?? $overtimeType) === SuratPerintahLemburModel::OVERTIME_TYPE_CONTINUES_NEXT_DAY
                        ) {
                            $appendContinuesEarlyInCandidate($dateKey, $plannedStart, $rawInAt, $entriesOnDate, $defaultReason);
                        }

                        continue;
                    }
                }
            }

            if (! $plannedEnd || ! $rawOutAt || ! $rawOutAt->gt($plannedEnd)) {
                continue;
            }

            $hasSameTypeSpl = $this->hasOvertimeTypeInEntryList($entriesOnDate, $overtimeType);

            if (in_array($targetMode, ['missing', 'both'], true) && ! $hasSameTypeSpl && ! $autoOvertimeWithoutSpl) {
                $minutes = $plannedEnd->diffInMinutes($rawOutAt);
                $threshold = max(1, (int) env('ATTENDANCE_MISSING_SPL_THRESHOLD_MINUTES', 30));
                if ($minutes >= $threshold) {
                    $candidates[] = [
                        'mode' => 'missing',
                        'date' => $dateKey,
                        'start_at' => $plannedEnd->copy(),
                        'end_at' => $rawOutAt->copy(),
                        'minutes' => $minutes,
                        'reason' => $defaultReason,
                    ];
                    $appendContinuesEarlyInCandidate($dateKey, $plannedStart, $rawInAt, $entriesOnDate, $defaultReason);
                }
            }

            if (in_array($targetMode, ['extend', 'both'], true) && $hasApprovedSpl && ! $autoOvertimeWithoutSpl) {
                $approvedWindow = $this->resolveApprovedOvertimeWindowForShift(
                    $overtimeApprovedMap[$splKey] ?? [],
                    $plannedStart,
                    $plannedEnd
                );
                if (($approvedWindow['post_end'] ?? null) instanceof Carbon && $rawOutAt->gt($approvedWindow['post_end'])) {
                    /** @var Carbon $approvedPostEnd */
                    $approvedPostEnd = $approvedWindow['post_end'];
                    $minutes = $approvedPostEnd->diffInMinutes($rawOutAt);
                    $threshold = max(1, (int) env('ATTENDANCE_EXTEND_SPL_THRESHOLD_MINUTES', 1));
                    if ($minutes >= $threshold) {
                        $candidates[] = [
                            'mode' => 'extend',
                            'date' => $dateKey,
                            'start_at' => $approvedPostEnd->copy(),
                            'end_at' => $rawOutAt->copy(),
                            'minutes' => $minutes,
                            'reason' => trim($defaultReason.' [Extend SPL]'),
                        ];
                    }
                }
            }

        }

        if (empty($candidates)) {
            $message = $autoOvertimeWithoutSpl
                ? 'Karyawan ini memakai mode OT otomatis tanpa SPL, jadi tidak ada kandidat Butuh SPL / Extend SPL pada rentang tersebut.'
                : ($selectedDates->isNotEmpty()
                    ? 'Tanggal yang dipilih tidak memiliki kandidat Butuh SPL / Extend SPL / Masuk Cepat yang bisa diproses.'
                    : 'Tidak ada tanggal yang memenuhi syarat untuk dibuatkan SPL otomatis.');

            return response()->json(['message' => $message], 422);
        }

        $created = 0;
        $submitted = 0;
        $approved = 0;
        $skipped = [];
        $notesAutoApprove = 'Approved otomatis dari Attendance Review V2.';
        $approvalService = new ApprovalWorkflowService;
        $approvalFlowId = (int) $request->input('approval_flow_id');
        $requestDate = now()->format('Y-m-d');

        DB::transaction(function () use (
            $candidates,
            $karyawanId,
            $approvalFlowId,
            $requestDate,
            $overtimeType,
            $processMode,
            $approvalService,
            $notesAutoApprove,
            &$created,
            &$submitted,
            &$approved,
            &$skipped
        ): void {
            foreach ($candidates as $candidate) {
                /** @var Carbon $startAt */
                $startAt = $candidate['start_at'];
                /** @var Carbon $endAt */
                $endAt = $candidate['end_at'];
                $candidateOvertimeType = strtolower(trim((string) ($candidate['overtime_type'] ?? $overtimeType)));
                if ($endAt->lte($startAt)) {
                    $skipped[] = $candidate['date'].': jam akhir tidak lebih besar dari jam mulai.';

                    continue;
                }

                $startTime = $startAt->format('H:i');
                $endTime = $endAt->format('H:i');

                $dup = SuratPerintahLemburModel::query()
                    ->where('karyawan_id', $karyawanId)
                    ->whereDate('work_date', $candidate['date'])
                    ->where('is_active', true)
                    ->whereNotIn('status', ['cancelled'])
                    ->where('start_time', $startTime.':00')
                    ->where('end_time', $endTime.':00')
                    ->where('overtime_type', $candidateOvertimeType)
                    ->exists();

                if ($dup) {
                    $skipped[] = $candidate['date'].': SPL otomatis dengan jam yang sama sudah ada.';

                    continue;
                }

                $jobId = $this->inferBulkShortcutJobId($karyawanId, (string) $candidate['date']);
                $tmpDoc = 'SPL-'.now()->format('Ymd').'-'.str_replace('-', '', (string) Str::uuid());
                $row = SuratPerintahLemburModel::query()->create([
                    'document_no' => $tmpDoc,
                    'karyawan_id' => $karyawanId,
                    'job_id' => $jobId,
                    'approval_flow_id' => $approvalFlowId,
                    'request_date' => $requestDate,
                    'work_date' => $candidate['date'],
                    'start_time' => $startTime,
                    'end_time' => $endTime,
                    'overtime_type' => $candidateOvertimeType,
                    'rule_payload' => [
                        'source' => 'attendance_review_v2_bulk_shortcut',
                        'target_mode' => $candidate['mode'],
                        'minutes' => (int) ($candidate['minutes'] ?? 0),
                    ],
                    'reason' => $candidate['reason'] ?? null,
                    'status' => 'draft',
                    'created_by' => auth()->id(),
                    'is_active' => true,
                ]);

                $row->document_no = 'SPL-'.now()->format('Ymd').'-'.str_pad((string) $row->id, 5, '0', STR_PAD_LEFT);
                $row->save();
                $created++;

                if (in_array($processMode, ['submit', 'approve'], true)) {
                    $approvalReq = $approvalService->createDraftRequest(
                        $approvalFlowId,
                        'overtime',
                        SuratPerintahLemburModel::class,
                        (int) $row->id,
                        auth()->id(),
                        $row->document_no
                    );
                    $row->approval_request_id = (int) $approvalReq->id;
                    $row->save();

                    $submittedReq = $approvalService->submit((int) $approvalReq->id);
                    $row->status = (string) $submittedReq->status;
                    $row->save();
                    $submitted++;

                    if ($processMode === 'approve') {
                        $this->forceApproveRequest((int) $submittedReq->id, (int) auth()->id(), $notesAutoApprove);
                        $row->status = 'approved';
                        $row->save();
                        $approved++;
                    }
                }
            }
        });

        return response()->json([
            'message' => 'Pintasan massal SPL selesai diproses.',
            'data' => [
                'created' => $created,
                'submitted' => $submitted,
                'approved' => $approved,
                'skipped' => $skipped,
                'effective_date_from' => $rangeStart->format('Y-m-d'),
                'effective_date_to' => $rangeEnd->format('Y-m-d'),
                'selected_dates' => $selectedDates->values()->all(),
            ],
        ]);
    }

    public function bulkContinuesWorkdayCandidates(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'work_date' => ['required', 'date'],
            'karyawan_ids' => ['nullable', 'array'],
            'karyawan_ids.*' => ['integer', 'exists:master_karyawans,id'],
            'profile_scope' => ['nullable', 'string', 'in:all,both,main,sub,selected'],
            'unapproved_only' => ['nullable', 'boolean'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profil = ProfilBulanModel::query()->findOrFail((int) $request->input('profil_bulan_id'));
        $workDate = Carbon::parse((string) $request->input('work_date'))->startOfDay();
        $nextDate = $workDate->copy()->addDay();
        $unapprovedOnly = $request->boolean('unapproved_only', true);
        $ids = collect($request->input('karyawan_ids', []))
            ->map(fn ($id) => (int) $id)
            ->filter(fn ($id) => $id > 0)
            ->unique()
            ->values();
        if ($ids->isEmpty()) {
            $scope = (string) $request->input('profile_scope', 'selected');
            $scope = match ($scope) {
                'all', 'both' => 'both',
                'main' => 'main',
                'sub' => 'sub',
                default => 'selected',
            };
            $profileIds = $scope === 'selected'
                ? [(int) $profil->id]
                : $this->summaryProfileIds($profil, $scope);
            $ids = ProfilBulanKaryawanModel::query()
                ->whereIn('profil_bulan_id', $profileIds)
                ->where('is_active', true)
                ->pluck('karyawan_id')
                ->map(fn ($id) => (int) $id)
                ->filter()
                ->unique()
                ->values();
        }

        if ($ids->isEmpty()) {
            return response()->json(['data' => []]);
        }

        $karyawans = KaryawanModel::query()
            ->whereIn('id', $ids->all())
            ->get(['id', 'employee_code', 'full_name'])
            ->keyBy('id');
        $reviews = AttendanceDailyReviewModel::query()
            ->where('profil_bulan_id', (int) $profil->id)
            ->whereIn('karyawan_id', $ids->all())
            ->whereDate('work_date', '>=', $workDate->format('Y-m-d'))
            ->whereDate('work_date', '<=', $nextDate->format('Y-m-d'))
            ->get()
            ->groupBy(fn ($row) => ((int) $row->karyawan_id).'|'.optional($row->work_date)->format('Y-m-d'));
        $rawLogs = AttendanceLogModel::query()
            ->whereIn('karyawan_id', $ids->all())
            ->whereBetween('log_at', [$workDate->copy()->startOfDay(), $nextDate->copy()->endOfDay()])
            ->orderBy('log_at')
            ->get(['karyawan_id', 'log_at'])
            ->groupBy(fn ($row) => ((int) $row->karyawan_id).'|'.Carbon::parse((string) $row->log_at)->format('Y-m-d'));

        $rows = $ids->map(function (int $id) use ($karyawans, $reviews, $rawLogs, $workDate, $nextDate, $unapprovedOnly) {
            $todayReview = optional($reviews->get($id.'|'.$workDate->format('Y-m-d')))->first();
            $nextReview = optional($reviews->get($id.'|'.$nextDate->format('Y-m-d')))->first();
            if ($unapprovedOnly && $todayReview && (bool) $todayReview->is_approved) {
                return null;
            }
            $todayLogs = collect($rawLogs->get($id.'|'.$workDate->format('Y-m-d'), collect()));
            $nextLogs = collect($rawLogs->get($id.'|'.$nextDate->format('Y-m-d'), collect()));
            $firstTodayLog = $todayLogs->first();
            $firstNextLog = $nextLogs->first();
            $nextHasPairing = $nextReview && $nextReview->checkin_at && $nextReview->checkout_at;
            if ($nextHasPairing || ! $firstNextLog) {
                return null;
            }
            $startAt = $todayReview?->checkin_at
                ?: $todayReview?->suggested_checkin_at
                ?: ($firstTodayLog?->log_at)
                ?: $todayReview?->planned_shift_start;
            $endAt = $firstNextLog->log_at;
            $employee = $karyawans->get($id);

            return [
                'karyawan_id' => $id,
                'code' => (string) ($employee?->employee_code ?? $id),
                'name' => (string) ($employee?->full_name ?? '-'),
                'start_time' => $startAt ? Carbon::parse((string) $startAt)->format('H:i') : '',
                'start_datetime' => $startAt ? Carbon::parse((string) $startAt)->format('Y-m-d\TH:i') : '',
                'end_time' => $endAt ? Carbon::parse((string) $endAt)->format('H:i') : '',
                'end_datetime' => $endAt ? Carbon::parse((string) $endAt)->format('Y-m-d\TH:i') : '',
                'note' => 'Saran OUT dari log '.$nextDate->format('Y-m-d'),
            ];
        })->filter()->values();

        return response()->json(['data' => $rows]);
    }

    public function bulkCreateContinuesWorkdaySpl(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'work_date' => ['required', 'date'],
            'items' => ['required', 'array', 'min:1'],
            'items.*.karyawan_id' => ['required', 'integer', 'exists:master_karyawans,id'],
            'items.*.start_time' => ['required', 'string', 'max:32'],
            'items.*.end_time' => ['required', 'string', 'max:32'],
            'approval_flow_id' => ['required', 'integer', 'exists:master_approval_flows,id'],
            'process_mode' => ['nullable', 'string', 'in:draft,submit,approve'],
            'reason' => ['nullable', 'string', 'max:2000'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $authUser = auth()->user();
        $canForceApprove = $this->isAdministrator($authUser) || $this->isHrd($authUser);
        $processMode = strtolower(trim((string) $request->input('process_mode', 'approve')));
        if ($processMode === 'approve' && ! $canForceApprove) {
            return response()->json(['message' => 'Langsung approved hanya untuk administrator/HRD.'], 403);
        }

        $profil = ProfilBulanModel::query()->findOrFail((int) $request->input('profil_bulan_id'));
        if ($guard = $this->guardProfilBulanOpenForAttendance($profil)) {
            return $guard;
        }

        $workDate = Carbon::parse((string) $request->input('work_date'))->format('Y-m-d');
        $profilStart = Carbon::parse((string) $profil->start_date)->format('Y-m-d');
        $profilEnd = Carbon::parse((string) $profil->end_date)->format('Y-m-d');
        if ($workDate < $profilStart || $workDate > $profilEnd) {
            return response()->json(['message' => 'Tanggal kerja di luar periode profil bulan.'], 422);
        }

        $normalizeSplTime = static function (?string $value): string {
            $raw = trim((string) ($value ?? ''));
            if ($raw === '') {
                return '';
            }

            foreach (['Y-m-d\TH:i', 'Y-m-d H:i', 'd/m/Y H:i', 'H:i'] as $format) {
                try {
                    $parsed = Carbon::createFromFormat('!'.$format, $raw);
                    if ($parsed && $parsed->format($format) === $raw) {
                        return $parsed->format('H:i');
                    }
                } catch (Throwable) {
                    // Try next format.
                }
            }

            $match = [];
            if (preg_match('/(\d{1,2}):(\d{2})/', $raw, $match)) {
                return str_pad((string) $match[1], 2, '0', STR_PAD_LEFT).':'.$match[2];
            }

            return '';
        };

        $items = collect($request->input('items', []))
            ->map(function ($item) use ($normalizeSplTime) {
                return [
                    'karyawan_id' => (int) ($item['karyawan_id'] ?? 0),
                    'start_time' => $normalizeSplTime($item['start_time'] ?? ''),
                    'end_time' => $normalizeSplTime($item['end_time'] ?? ''),
                ];
            })
            ->filter(fn ($item) => $item['karyawan_id'] > 0 && $item['start_time'] !== '' && $item['end_time'] !== '')
            ->unique(fn ($item) => $item['karyawan_id'])
            ->values();

        if ($items->isEmpty()) {
            return response()->json(['message' => 'Belum ada karyawan valid untuk diproses.'], 422);
        }

        $employeeIds = $items->pluck('karyawan_id')->all();
        $assignedIds = ProfilBulanKaryawanModel::query()
            ->where('profil_bulan_id', (int) $profil->id)
            ->whereIn('karyawan_id', $employeeIds)
            ->pluck('karyawan_id')
            ->map(fn ($id) => (int) $id)
            ->all();
        $assignedSet = array_flip($assignedIds);

        $created = 0;
        $updated = 0;
        $submitted = 0;
        $approved = 0;
        $skipped = [];
        $approvalFlowId = (int) $request->input('approval_flow_id');
        $reason = trim((string) $request->input('reason'));
        if ($reason === '') {
            $reason = 'SPL Continues Work Day bulk dari Attendance Review V2.';
        }

        $approvalService = new ApprovalWorkflowService;
        $notesAutoApprove = 'Approved otomatis Continues Work Day dari Attendance Review V2.';

        foreach ($items as $item) {
            $karyawanId = (int) $item['karyawan_id'];
            try {
                DB::transaction(function () use (
                    $item,
                    $karyawanId,
                    $assignedSet,
                    $workDate,
                    $approvalFlowId,
                    $processMode,
                    $reason,
                    $approvalService,
                    $notesAutoApprove,
                    &$created,
                    &$updated,
                    &$submitted,
                    &$approved,
                    &$skipped
                ): void {
                    if (! isset($assignedSet[$karyawanId])) {
                        $skipped[] = $karyawanId.': belum masuk profil bulan.';

                        return;
                    }

                    $existing = SuratPerintahLemburModel::query()
                        ->where('karyawan_id', $karyawanId)
                        ->whereDate('work_date', $workDate)
                        ->where('is_active', true)
                        ->whereNotIn('status', ['cancelled'])
                        ->where('overtime_type', SuratPerintahLemburModel::OVERTIME_TYPE_CONTINUES_NEXT_DAY)
                        ->first();

                    if ($existing && ! in_array((string) $existing->status, ['draft'], true)) {
                        $skipped[] = $karyawanId.': SPL ContinuesNextDay sudah '.($existing->status ?: 'aktif').'.';

                        return;
                    }

                    $payload = [
                        'source' => 'attendance_review_v2_bulk_continues_workday',
                        'continues_target_coverage_hours' => 24,
                        'continues_next_day_work_hours' => 8,
                        'continues_shortage_hours' => 0,
                        'continues_conversion_mode' => 'bonus_hours',
                        'payment_mode' => 'payroll',
                    ];

                    $row = $existing ?: new SuratPerintahLemburModel;
                    if (! $row->exists) {
                        $row->document_no = 'SPL-'.now()->format('Ymd').'-'.str_replace('-', '', (string) Str::uuid());
                        $row->created_by = auth()->id();
                        $row->is_active = true;
                    }

                    $row->fill([
                        'karyawan_id' => $karyawanId,
                        'job_id' => $this->inferBulkShortcutJobId($karyawanId, $workDate),
                        'approval_flow_id' => $approvalFlowId,
                        'request_date' => now()->format('Y-m-d'),
                        'work_date' => $workDate,
                        'start_time' => $item['start_time'],
                        'end_time' => $item['end_time'],
                        'overtime_type' => SuratPerintahLemburModel::OVERTIME_TYPE_CONTINUES_NEXT_DAY,
                        'rule_payload' => $payload,
                        'reason' => $reason,
                        'status' => 'draft',
                    ]);
                    $row->save();

                    if (! $existing) {
                        $row->document_no = 'SPL-'.now()->format('Ymd').'-'.str_pad((string) $row->id, 5, '0', STR_PAD_LEFT);
                        $row->save();
                        $created++;
                    } else {
                        $updated++;
                    }

                    if ($processMode === 'approve') {
                        $row->status = 'approved';
                        $row->approval_request_id = null;
                        $row->save();
                        $approved++;
                    } elseif ($processMode === 'submit') {
                        $approvalReq = $approvalService->createDraftRequest(
                            $approvalFlowId,
                            'overtime',
                            SuratPerintahLemburModel::class,
                            (int) $row->id,
                            auth()->id(),
                            $row->document_no
                        );
                        $row->approval_request_id = (int) $approvalReq->id;
                        $row->save();

                        $submittedReq = $approvalService->submit((int) $approvalReq->id);
                        $row->status = (string) $submittedReq->status;
                        $row->save();
                        $submitted++;
                    }
                });
            } catch (Throwable $e) {
                report($e);
                $skipped[] = $karyawanId.': '.$e->getMessage();
            }
        }

        return response()->json([
            'message' => 'Bulk Continues Work Day selesai diproses.',
            'data' => compact('created', 'updated', 'submitted', 'approved', 'skipped') + [
                'work_date' => $workDate,
            ],
        ]);
    }

    // =========================================================================
    // bulkCreateAutoOtHolidayWeekendSpl() - Helper function internal
    // Dipanggil dari: Route/API endpoint
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function bulkCreateAutoOtHolidayWeekendSpl(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['required', 'integer', 'exists:master_karyawans,id'],
            'selected_dates' => ['required', 'array', 'min:1'],
            'selected_dates.*' => ['required', 'date'],
            'approval_flow_id' => ['required', 'integer', 'exists:master_approval_flows,id'],
            'overtime_type' => ['nullable', 'string', 'in:'.implode(',', array_keys(SuratPerintahLemburModel::overtimeTypeOptions()))],
            'process_mode' => ['nullable', 'string', 'in:draft,approve'],
            'reason' => ['nullable', 'string', 'max:2000'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $authUser = auth()->user();
        $canForceApprove = $this->isAdministrator($authUser) || $this->isHrd($authUser);
        $processMode = strtolower(trim((string) $request->input('process_mode', 'draft')));
        if ($processMode === 'approve' && ! $canForceApprove) {
            return response()->json(['message' => 'Langsung approved hanya untuk administrator/HRD.'], 403);
        }

        $profil = ProfilBulanModel::query()->findOrFail((int) $request->input('profil_bulan_id'));
        if ($guard = $this->guardProfilBulanOpenForAttendance($profil)) {
            return $guard;
        }
        $targetMode = strtolower(trim((string) $request->input('target_mode', 'selected_manual')));
        $selectedDates = collect($request->input('selected_dates', []))
            ->map(fn ($date) => Carbon::parse((string) $date)->format('Y-m-d'))
            ->filter()
            ->unique()
            ->values();

        if ($selectedDates->isEmpty()) {
            return response()->json(['message' => 'Belum ada tanggal holiday/weekend yang dipilih.'], 422);
        }

        $rangeStart = Carbon::parse((string) $selectedDates->min())->startOfDay();
        $rangeEnd = Carbon::parse((string) $selectedDates->max())->startOfDay();
        $profilStart = Carbon::parse((string) $profil->start_date)->startOfDay();
        $profilEnd = Carbon::parse((string) $profil->end_date)->startOfDay();
        if ($rangeStart->lt($profilStart)) {
            $rangeStart = $profilStart->copy();
        }
        if ($rangeEnd->gt($profilEnd)) {
            $rangeEnd = $profilEnd->copy();
        }
        if ($rangeEnd->lt($rangeStart)) {
            $rangeEnd = $rangeStart->copy();
        }

        if ($targetMode === 'selected_manual' && $selectedDates->isEmpty()) {
            $selectedDates = collect(CarbonPeriod::create($rangeStart->copy(), $rangeEnd->copy()))
                ->map(fn (Carbon $date) => $date->format('Y-m-d'))
                ->values();
        }

        $karyawanId = (int) $request->input('karyawan_id');
        $employeeIds = collect([$karyawanId]);
        $overtimeType = strtolower(trim((string) $request->input('overtime_type', SuratPerintahLemburModel::OVERTIME_TYPE_NORMAL)));
        $defaultReason = trim((string) $request->input('reason'));
        if ($defaultReason === '') {
            $defaultReason = 'SPL holiday/weekend khusus AUTO OT dari Attendance Review V2.';
        }

        $assignment = ProfilBulanKaryawanModel::query()
            ->where('profil_bulan_id', (int) $profil->id)
            ->where('karyawan_id', $karyawanId)
            ->first();

        if (! $this->assignmentAllowsAutomaticOvertimeWithoutSpl($assignment)) {
            return response()->json(['message' => 'Karyawan ini belum memakai mode OT otomatis tanpa SPL.'], 422);
        }

        $reviews = AttendanceDailyReviewModel::query()
            ->where('profil_bulan_id', (int) $profil->id)
            ->where('karyawan_id', $karyawanId)
            ->whereDate('work_date', '>=', $rangeStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $rangeEnd->format('Y-m-d'))
            ->get()
            ->keyBy(fn (AttendanceDailyReviewModel $row) => optional($row->work_date)->format('Y-m-d'));

        $calendarMarks = $this->buildCalendarMarks($rangeStart->copy(), $rangeEnd->copy());
        $holidayMap = $calendarMarks['holiday_map'] ?? [];
        $workdayMap = $calendarMarks['workday_map'] ?? [];
        $holidaySpecialMap = $calendarMarks['holiday_special_map'] ?? [];

        $rawLogMinMaxMap = [];
        try {
            $rawLogAgg = AttendanceLogModel::query()
                ->where('karyawan_id', $karyawanId)
                ->whereBetween('log_at', [$rangeStart->copy()->startOfDay(), $rangeEnd->copy()->endOfDay()])
                ->selectRaw('DATE(log_at) as d, MIN(log_at) as min_at, MAX(log_at) as max_at')
                ->groupBy('d')
                ->get();

            foreach ($rawLogAgg as $row) {
                $dateKey = (string) ($row->d ?? '');
                if ($dateKey === '') {
                    continue;
                }
                $rawLogMinMaxMap[$dateKey] = [
                    'min_at' => ! empty($row->min_at) ? (string) $row->min_at : null,
                    'max_at' => ! empty($row->max_at) ? (string) $row->max_at : null,
                ];
            }
        } catch (\Throwable $e) {
            $rawLogMinMaxMap = [];
        }

        $overtimeTagMap = $this->buildOvertimeTagMap($employeeIds, $rangeStart->copy(), $rangeEnd->copy());
        $overtimeEntryListMap = $this->buildOvertimeEntryListMap($employeeIds, $rangeStart->copy(), $rangeEnd->copy());

        $candidates = [];
        $discoverySkipped = [];
        foreach ($selectedDates as $selectedDate) {
            $date = Carbon::parse((string) $selectedDate)->startOfDay();
            if ($date->lt($rangeStart) || $date->gt($rangeEnd)) {
                $discoverySkipped[] = $date->format('Y-m-d').': di luar periode profil bulan.';

                continue;
            }
            $dateKey = $date->format('Y-m-d');
            $dayType = $this->resolveDayTypeForCalculation($dateKey, $holidayMap, $workdayMap, $holidaySpecialMap);
            if (! in_array($dayType, ['holiday', 'holiday_special', 'weekend'], true)) {
                $discoverySkipped[] = $dateKey.': bukan holiday/weekend.';

                continue;
            }

            /** @var AttendanceDailyReviewModel|null $review */
            $review = $reviews->get($dateKey);
            $rawLog = $rawLogMinMaxMap[$dateKey] ?? ['min_at' => null, 'max_at' => null];

            $rawIn = $rawLog['min_at'] ?: ($review?->suggested_checkin_at ?: $review?->checkin_at);
            $rawOut = $rawLog['max_at'] ?: ($review?->suggested_checkout_at ?: $review?->checkout_at);

            if (! $rawIn || ! $rawOut) {
                $discoverySkipped[] = $dateKey.': jam actual tidak lengkap.';

                continue;
            }

            $startAt = Carbon::parse((string) $rawIn);
            $endAt = Carbon::parse((string) $rawOut);
            if (! $endAt->gt($startAt)) {
                $discoverySkipped[] = $dateKey.': jam akhir tidak lebih besar dari jam mulai.';

                continue;
            }

            $existingDraftSplId = null;
            $splKey = $karyawanId.'|'.$dateKey;
            $entriesOnDate = $overtimeEntryListMap[$splKey] ?? [];
            if (! empty($entriesOnDate)) {
                $sameTypeEntries = array_values(array_filter($entriesOnDate, fn (array $entry) => strtolower(trim((string) ($entry['overtime_type'] ?? ''))) === $overtimeType));
                if (! empty($sameTypeEntries)) {
                    $blockingEntry = collect($sameTypeEntries)->first(fn (array $entry) => strtolower(trim((string) ($entry['status'] ?? ''))) !== 'draft');
                    if ($blockingEntry) {
                        $tagLabel = trim((string) ($blockingEntry['label'] ?? 'SPL aktif'));
                        $tagNotes = trim((string) ($blockingEntry['notes'] ?? ''));
                        $discoverySkipped[] = $dateKey.': sudah ada '.$tagLabel.($tagNotes !== '' ? ' ('.$tagNotes.')' : '').' untuk tipe SPL yang sama.';

                        continue;
                    }

                    $draftEntry = collect($sameTypeEntries)->first(fn (array $entry) => strtolower(trim((string) ($entry['status'] ?? ''))) === 'draft' && (int) ($entry['reference_id'] ?? 0) > 0);
                    if ($draftEntry) {
                        $existingDraftSplId = (int) ($draftEntry['reference_id'] ?? 0);
                    }
                }
            }

            $candidates[] = [
                'mode' => $dayType,
                'date' => $dateKey,
                'start_at' => $startAt->copy(),
                'end_at' => $endAt->copy(),
                'minutes' => $startAt->diffInMinutes($endAt),
                'reason' => trim($defaultReason.' ['.strtoupper($dayType).']'),
                'existing_draft_spl_id' => $existingDraftSplId,
            ];
        }

        if (empty($candidates)) {
            if (! empty($discoverySkipped)) {
                return response()->json([
                    'message' => 'Pintasan SPL holiday/weekend AUTO OT selesai diproses, tidak ada SPL baru yang dibuat.',
                    'data' => [
                        'created' => 0,
                        'updated' => 0,
                        'submitted' => 0,
                        'approved' => 0,
                        'skipped' => $discoverySkipped,
                        'effective_date_from' => $rangeStart->format('Y-m-d'),
                        'effective_date_to' => $rangeEnd->format('Y-m-d'),
                    ],
                ]);
            }

            return response()->json(['message' => 'Tidak ada holiday/weekend dengan jam actual yang bisa dibuatkan SPL pada rentang tersebut.'], 422);
        }

        $created = 0;
        $updated = 0;
        $submitted = 0;
        $approved = 0;
        $skipped = $discoverySkipped;
        $notesAutoApprove = 'Approved otomatis dari pintasan SPL holiday/weekend AUTO OT.';
        $approvalService = new ApprovalWorkflowService;
        $approvalFlowId = (int) $request->input('approval_flow_id');
        $requestDate = now()->format('Y-m-d');

        DB::transaction(function () use (
            $candidates,
            $karyawanId,
            $approvalFlowId,
            $requestDate,
            $overtimeType,
            $processMode,
            $approvalService,
            $notesAutoApprove,
            &$created,
            &$updated,
            &$submitted,
            &$approved,
            &$skipped
        ): void {
            foreach ($candidates as $candidate) {
                /** @var Carbon $startAt */
                $startAt = $candidate['start_at'];
                /** @var Carbon $endAt */
                $endAt = $candidate['end_at'];
                if ($endAt->lte($startAt)) {
                    $skipped[] = $candidate['date'].': jam akhir tidak lebih besar dari jam mulai.';

                    continue;
                }

                $startTime = $startAt->format('H:i');
                $endTime = $endAt->format('H:i');
                $existingDraftSplId = (int) ($candidate['existing_draft_spl_id'] ?? 0);

                $dup = SuratPerintahLemburModel::query()
                    ->where('karyawan_id', $karyawanId)
                    ->whereDate('work_date', $candidate['date'])
                    ->where('is_active', true)
                    ->whereNotIn('status', ['cancelled'])
                    ->where('start_time', $startTime.':00')
                    ->where('end_time', $endTime.':00')
                    ->where('overtime_type', $overtimeType)
                    ->when($existingDraftSplId > 0, fn ($q) => $q->where('id', '<>', $existingDraftSplId))
                    ->exists();

                if ($dup) {
                    $skipped[] = $candidate['date'].': SPL holiday/weekend dengan jam yang sama sudah ada.';

                    continue;
                }

                $jobId = $this->inferBulkShortcutJobId($karyawanId, (string) $candidate['date']);
                $payload = [
                    'karyawan_id' => $karyawanId,
                    'job_id' => $jobId,
                    'approval_flow_id' => $approvalFlowId,
                    'request_date' => $requestDate,
                    'work_date' => $candidate['date'],
                    'start_time' => $startTime,
                    'end_time' => $endTime,
                    'overtime_type' => $overtimeType,
                    'rule_payload' => [
                        'source' => 'attendance_review_v2_auto_ot_holiday_weekend_shortcut',
                        'target_mode' => $candidate['mode'],
                        'minutes' => (int) ($candidate['minutes'] ?? 0),
                        'updated_existing_draft' => $existingDraftSplId > 0,
                    ],
                    'reason' => $candidate['reason'] ?? null,
                    'status' => 'draft',
                    'is_active' => true,
                ];

                if ($existingDraftSplId > 0) {
                    $row = SuratPerintahLemburModel::query()
                        ->whereKey($existingDraftSplId)
                        ->where('karyawan_id', $karyawanId)
                        ->whereDate('work_date', $candidate['date'])
                        ->where('is_active', true)
                        ->lockForUpdate()
                        ->first();

                    if (! $row) {
                        $skipped[] = $candidate['date'].': SPL draft tidak ditemukan saat proses update.';

                        continue;
                    }
                    if ((string) $row->status !== 'draft') {
                        $skipped[] = $candidate['date'].': SPL sudah berubah status menjadi '.((string) $row->status ?: '-').'.';

                        continue;
                    }
                    if ($row->approval_request_id) {
                        DB::table('approval_requests')->where('id', (int) $row->approval_request_id)->delete();
                        $row->approval_request_id = null;
                    }
                    $row->fill($payload);
                    $row->save();
                    $updated++;
                } else {
                    $tmpDoc = 'SPL-'.now()->format('Ymd').'-'.str_replace('-', '', (string) Str::uuid());
                    $row = SuratPerintahLemburModel::query()->create($payload + [
                        'document_no' => $tmpDoc,
                        'created_by' => auth()->id(),
                    ]);

                    $row->document_no = 'SPL-'.now()->format('Ymd').'-'.str_pad((string) $row->id, 5, '0', STR_PAD_LEFT);
                    $row->save();
                    $created++;
                }

                if ($processMode === 'approve') {
                    $submittedReq = null;
                    try {
                        $approvalReq = $approvalService->createDraftRequest(
                            $approvalFlowId,
                            'overtime',
                            SuratPerintahLemburModel::class,
                            (int) $row->id,
                            auth()->id(),
                            $row->document_no
                        );
                        $row->approval_request_id = (int) $approvalReq->id;
                        $row->save();

                        $submittedReq = $approvalService->submit((int) $approvalReq->id);
                        $row->status = (string) $submittedReq->status;
                        $row->save();
                        $submitted++;
                    } catch (Throwable $e) {
                        if (! $this->isAdministrator(auth()->user()) && ! $this->isHrd(auth()->user())) {
                            throw $e;
                        }
                    }

                    if ($submittedReq) {
                        $this->forceApproveRequest((int) $submittedReq->id, (int) auth()->id(), $notesAutoApprove);
                    } else {
                        $row->approval_request_id = null;
                    }

                    $row->status = 'approved';
                    $row->save();
                    $approved++;
                }
            }
        });

        return response()->json([
            'message' => 'Pintasan SPL holiday/weekend AUTO OT selesai diproses.',
            'data' => [
                'created' => $created,
                'updated' => $updated,
                'submitted' => $submitted,
                'approved' => $approved,
                'skipped' => $skipped,
                'effective_date_from' => $rangeStart->format('Y-m-d'),
                'effective_date_to' => $rangeEnd->format('Y-m-d'),
            ],
        ]);
    }

    // =========================================================================
    // inferBulkShortcutJobId() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function inferBulkShortcutJobId(int $karyawanId, string $workDate): ?int
    {
        try {
            return ProjectJobAssignmentModel::query()
                ->where('is_active', true)
                ->where('karyawan_id', $karyawanId)
                ->whereDate('work_date', $workDate)
                ->value('job_id') ?: null;
        } catch (\Throwable $e) {
            return null;
        }
    }

    // =========================================================================
    // forceApproveRequest() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function forceApproveRequest(int $approvalRequestId, int $userId, ?string $notes = null): ApprovalRequestModel
    {
        return DB::transaction(function () use ($approvalRequestId, $userId, $notes): ApprovalRequestModel {
            /** @var ApprovalRequestModel $request */
            $request = ApprovalRequestModel::query()
                ->with(['steps' => fn ($q) => $q->orderBy('step_order')])
                ->findOrFail($approvalRequestId);

            if ($request->status === 'approved') {
                return $request;
            }

            $now = now();
            foreach ($request->steps as $step) {
                if ((string) $step->status === 'approved') {
                    continue;
                }
                if ((string) $step->status === 'rejected') {
                    $step->status = 'approved';
                } elseif ((string) $step->status !== 'approved') {
                    $step->status = 'approved';
                }
                $step->approver_user_id = $step->approver_user_id ?: $userId;
                $step->action_notes = $notes ?: 'Auto approved dari pintasan SPL otomatis.';
                $step->acted_at = $now;
                $step->save();
            }

            $request->status = 'approved';
            $request->current_step_order = null;
            $request->submitted_at = $request->submitted_at ?: $now;
            $request->final_approved_at = $now;
            $request->rejected_at = null;
            $request->rejection_reason = null;
            $request->save();

            return $request->fresh(['steps']);
        });
    }

    // =========================================================================
    // logData() - Data log untuk DataTable
    // Dipanggil dari: GET /attendance-review/logs
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function logData(Request $request): JsonResponse
    {
        $q = AttendanceLogModel::query()
            ->with('karyawan:id,employee_code,finger_id,full_name')
            ->orderByDesc('log_at')
            ->orderByDesc('id');

        if ($request->filled('date_from')) {
            $q->where('log_at', '>=', Carbon::parse($request->input('date_from'))->startOfDay());
        }
        if ($request->filled('date_to')) {
            $q->where('log_at', '<=', Carbon::parse($request->input('date_to'))->endOfDay());
        }
        if ($request->filled('karyawan_id')) {
            $q->where('karyawan_id', (int) $request->input('karyawan_id'));
        }

        $rows = $q->limit(1000)->get()->map(fn (AttendanceLogModel $row) => [
            'id' => (int) $row->id,
            'karyawan_id' => $row->karyawan_id ? (int) $row->karyawan_id : null,
            'employee_code' => $row->karyawan?->employee_code ?: $row->employee_code,
            'finger_id' => $row->karyawan?->finger_id ?: $row->finger_id,
            'employee_name' => $row->karyawan?->full_name,
            'log_at' => optional($row->log_at)->format('Y-m-d H:i:s'),
            'log_type' => $row->log_type,
            'source' => $row->source,
            'device_code' => $row->device_code,
            'notes' => $row->notes,
        ])->values();

        return response()->json(['data' => $rows]);
    }

    // =========================================================================
    // unmappedLogData() - Data log yang belum ter-mapping
    // Dipanggil dari: GET /attendance-review/logs/unmapped
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function unmappedLogData(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'source' => ['nullable', 'string', 'max:40'],
            'device_code' => ['nullable', 'string', 'max:60'],
            'limit' => ['nullable', 'integer', 'min:1', 'max:5000'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $source = trim((string) $request->input('source', ''));
        $deviceCode = trim((string) $request->input('device_code', ''));
        $limit = (int) $request->input('limit', 500);

        $q = AttendanceLogModel::query()
            ->whereNull('karyawan_id')
            ->orderByDesc('log_at')
            ->orderByDesc('id');

        if ($source !== '') {
            $q->where('source', $source);
        }
        if ($deviceCode !== '') {
            $q->where('device_code', $deviceCode);
        }

        $rows = $q->limit($limit)
            ->get(['id', 'employee_code', 'finger_id', 'log_at', 'log_type', 'source', 'device_code', 'notes'])
            ->map(fn (AttendanceLogModel $row) => [
                'id' => (int) $row->id,
                'employee_code' => $row->employee_code,
                'finger_id' => $row->finger_id,
                'log_at' => optional($row->log_at)->format('Y-m-d H:i:s'),
                'log_type' => $row->log_type,
                'source' => $row->source,
                'device_code' => $row->device_code,
                'notes' => $row->notes,
            ])
            ->values();

        return response()->json([
            'data' => $rows,
            'meta' => [
                'source' => $source !== '' ? $source : null,
                'device_code' => $deviceCode !== '' ? $deviceCode : null,
                'count' => $rows->count(),
                'limit' => $limit,
            ],
        ]);
    }

    // =========================================================================
    // storeLog() - Simpan log attendance baru
    // Dipanggil dari: POST /attendance-review/logs
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function storeLog(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'karyawan_id' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'employee_code' => ['nullable', 'string', 'max:40'],
            'finger_id' => ['nullable', 'string', 'max:60'],
            'log_at' => ['required', 'date'],
            'log_type' => ['nullable', 'in:in,out,unknown'],
            'source' => ['nullable', 'string', 'max:40'],
            'device_code' => ['nullable', 'string', 'max:60'],
            'notes' => ['nullable', 'string'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $karyawanId = $request->input('karyawan_id') ? (int) $request->input('karyawan_id') : null;
        $employeeCode = strtoupper(trim($request->string('employee_code')->toString()));
        $fingerId = trim($request->string('finger_id')->toString());

        if (! $karyawanId && ($employeeCode !== '' || $fingerId !== '')) {
            $karyawan = KaryawanModel::query()
                ->when($fingerId !== '', fn ($q) => $q->where('finger_id', $fingerId))
                ->when($employeeCode !== '', fn ($q) => $q->orWhere('employee_code', $employeeCode))
                ->first();
            if ($karyawan) {
                $karyawanId = (int) $karyawan->id;
                if ($employeeCode === '') {
                    $employeeCode = (string) ($karyawan->employee_code ?? '');
                }
                if ($fingerId === '') {
                    $fingerId = (string) ($karyawan->finger_id ?? '');
                }
            }
        }

        AttendanceLogModel::query()->create([
            'karyawan_id' => $karyawanId,
            'employee_code' => $employeeCode !== '' ? $employeeCode : null,
            'finger_id' => $fingerId !== '' ? $fingerId : null,
            'log_at' => Carbon::parse($request->input('log_at'))->format('Y-m-d H:i:s'),
            'log_type' => trim($request->string('log_type')->toString()) ?: 'unknown',
            'source' => trim($request->string('source')->toString()) ?: 'manual',
            'device_code' => trim($request->string('device_code')->toString()) ?: null,
            'notes' => $request->string('notes')->toString() ?: null,
            'is_active' => true,
        ]);

        return response()->json(['message' => 'Log attendance created']);
    }

    // =========================================================================
    // importMachineLog() - Import log dari mesin fingerprint
    // Dipanggil dari: Route/API endpoint
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function importMachineLog(Request $request): JsonResponse
    {
        @ini_set('max_execution_time', '0');
        @set_time_limit(0);

        $validator = Validator::make($request->all(), [
            'file' => ['required', 'file', 'mimes:txt,dat,csv,log'],
            'delimiter' => ['nullable', 'string', 'max:10'],
            'source' => ['nullable', 'string', 'max:40'],
            'device_code' => ['nullable', 'string', 'max:60'],
            'override_lock' => ['nullable', 'boolean'],
            'override_key' => ['nullable', 'string', 'max:255'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $path = $request->file('file')->getRealPath();
        $lines = file($path, FILE_IGNORE_NEW_LINES);
        if ($lines === false || count($lines) === 0) {
            return response()->json(['message' => 'File kosong atau gagal dibaca.'], 422);
        }

        $source = trim((string) $request->input('source', 'x100c-flashdisk')) ?: 'x100c-flashdisk';
        $deviceCode = trim((string) $request->input('device_code', ''));
        $deviceCode = $deviceCode !== '' ? $deviceCode : null;
        $delimiterInput = strtolower(trim((string) $request->input('delimiter', 'auto')));

        $lines = array_values(array_filter(
            array_map(fn ($line) => trim((string) $line), $lines),
            fn ($line) => $line !== ''
        ));
        if (count($lines) === 0) {
            return response()->json(['message' => 'Tidak ada baris data pada file.'], 422);
        }

        $normalized = [];
        $errors = [];
        $inserted = 0;
        $duplicates = 0;
        $failed = 0;
        $unmappedInserted = 0;
        $lineNo = 0;
        $lockEnabled = $this->isAppSettingTruthy('attendance.ingest.lock_enabled', true);
        $lockCutoff = $this->getAppSettingTime('attendance.ingest.lock_cutoff_time', '10:00');
        $lockOverride = $this->canOverrideIngestLock($request);

        $firstLine = ltrim((string) ($lines[0] ?? ''), "\xEF\xBB\xBF");
        $delimiter = $this->resolveImportDelimiter($delimiterInput, $firstLine);
        $headerFields = str_getcsv($firstLine, $delimiter);
        $hasHeader = $this->hasMachineLikelyHeader($headerFields);

        if ($hasHeader) {
            $header = collect($headerFields)
                ->map(fn ($h) => strtolower(trim((string) $h)))
                ->values()
                ->all();

            foreach (array_slice($lines, 1) as $idx => $line) {
                $lineNo = $idx + 2;
                $raw = str_getcsv((string) $line, $delimiter);
                $assoc = [];
                foreach ($header as $hIdx => $key) {
                    if ($key === '') {
                        continue;
                    }
                    $assoc[$key] = $raw[$hIdx] ?? null;
                }
                $normalized[] = $this->normalizeMachineAssocRow($assoc, $lineNo, $source, $deviceCode);
            }
        } else {
            foreach ($lines as $idx => $line) {
                $lineNo = $idx + 1;
                $rawFields = str_getcsv((string) $line, $delimiter);
                $normalized[] = $this->normalizeMachinePositionalRow($rawFields, $lineNo, $source, $deviceCode);
            }
        }

        $candidates = [];
        $fingerIds = [];
        $employeeCodes = [];
        $clientLogIds = [];
        $minLogAt = null;
        $maxLogAt = null;

        foreach ($normalized as $idx => $row) {
            $ln = (int) ($row['_line_no'] ?? ($idx + 1));
            try {
                $fingerId = trim((string) ($row['finger_id'] ?? ''));
                $employeeCode = strtoupper(trim((string) ($row['employee_code'] ?? '')));
                $logAt = Carbon::parse((string) ($row['log_at'] ?? ''))->format('Y-m-d H:i:s');
                $logType = strtolower(trim((string) ($row['log_type'] ?? 'unknown')));
                $clientLogId = trim((string) ($row['client_log_id'] ?? ''));
                $lockMessage = $this->validateIngestDateLockForReview(
                    Carbon::parse($logAt),
                    $lockEnabled,
                    $lockCutoff,
                    $lockOverride
                );
                if ($lockMessage !== null) {
                    $failed++;
                    $errors[] = ['row' => $ln, 'message' => $lockMessage];

                    continue;
                }

                if ($logAt === '' || ($fingerId === '' && $employeeCode === '')) {
                    $failed++;
                    $errors[] = ['row' => $ln, 'message' => 'Baris tidak valid (finger/employee dan log_at wajib).'];

                    continue;
                }

                if ($fingerId !== '') {
                    $fingerIds[] = $fingerId;
                }
                if ($employeeCode !== '') {
                    $employeeCodes[] = $employeeCode;
                }
                if ($clientLogId !== '') {
                    $clientLogIds[] = $clientLogId;
                }
                $minLogAt = $minLogAt === null || $logAt < $minLogAt ? $logAt : $minLogAt;
                $maxLogAt = $maxLogAt === null || $logAt > $maxLogAt ? $logAt : $maxLogAt;

                $candidates[] = [
                    '_line_no' => $ln,
                    'finger_id' => $fingerId,
                    'employee_code' => $employeeCode,
                    'client_log_id' => $clientLogId,
                    'log_at' => $logAt,
                    'log_type' => in_array($logType, ['in', 'out', 'unknown'], true) ? $logType : 'unknown',
                    'notes' => trim((string) ($row['notes'] ?? 'import flashdisk machine')) ?: null,
                ];
            } catch (\Throwable $e) {
                $failed++;
                $errors[] = ['row' => $ln, 'message' => 'Format baris tidak valid: '.$e->getMessage()];
            }
        }

        if (! empty($candidates)) {
            $fingerIds = array_values(array_unique(array_filter($fingerIds)));
            $employeeCodes = array_values(array_unique(array_filter($employeeCodes)));
            $clientLogIds = array_values(array_unique(array_filter($clientLogIds)));

            $karyawanRows = KaryawanModel::query()
                ->where(function ($q) use ($fingerIds, $employeeCodes): void {
                    if (! empty($fingerIds)) {
                        $q->whereIn('finger_id', $fingerIds);
                    }
                    if (! empty($employeeCodes)) {
                        $q->orWhereIn('employee_code', $employeeCodes);
                    }
                })
                ->get(['id', 'finger_id', 'employee_code']);

            $karyawanByFinger = [];
            $karyawanByCode = [];
            foreach ($karyawanRows as $kRow) {
                $f = trim((string) ($kRow->finger_id ?? ''));
                $c = strtoupper(trim((string) ($kRow->employee_code ?? '')));
                if ($f !== '') {
                    $karyawanByFinger[$f] = $kRow;
                }
                if ($c !== '') {
                    $karyawanByCode[$c] = $kRow;
                }
            }

            $existingClientIds = [];
            if (! empty($clientLogIds)) {
                $existingClientIds = AttendanceLogModel::query()
                    ->whereIn('client_log_id', $clientLogIds)
                    ->pluck('client_log_id')
                    ->filter()
                    ->values()
                    ->all();
                $existingClientIds = array_fill_keys($existingClientIds, true);
            }

            $existingStrictKeys = [];
            if ($minLogAt !== null && $maxLogAt !== null) {
                $existingRows = AttendanceLogModel::query()
                    ->whereBetween('log_at', [$minLogAt, $maxLogAt])
                    ->where(function ($q) use ($fingerIds, $employeeCodes): void {
                        if (! empty($fingerIds)) {
                            $q->whereIn('finger_id', $fingerIds);
                        }
                        if (! empty($employeeCodes)) {
                            $q->orWhereIn('employee_code', $employeeCodes);
                        }
                        $q->orWhereNotNull('karyawan_id');
                    })
                    ->get(['karyawan_id', 'employee_code', 'finger_id', 'log_at']);

                foreach ($existingRows as $eRow) {
                    $identity = '';
                    if (! empty($eRow->karyawan_id)) {
                        $identity = 'K:'.(int) $eRow->karyawan_id;
                    } elseif (! empty($eRow->employee_code)) {
                        $identity = 'E:'.strtoupper(trim((string) $eRow->employee_code));
                    } elseif (! empty($eRow->finger_id)) {
                        $identity = 'F:'.trim((string) $eRow->finger_id);
                    }
                    if ($identity === '') {
                        continue;
                    }
                    $existingStrictKeys[$identity.'|'.Carbon::parse((string) $eRow->log_at)->format('Y-m-d H:i:s')] = true;
                }
            }

            $now = now()->format('Y-m-d H:i:s');
            $toInsert = [];
            $inRequestKeys = [];

            foreach ($candidates as $row) {
                $ln = (int) $row['_line_no'];
                $fingerId = (string) ($row['finger_id'] ?? '');
                $employeeCode = (string) ($row['employee_code'] ?? '');
                $clientLogId = (string) ($row['client_log_id'] ?? '');
                $logAt = (string) ($row['log_at'] ?? '');
                $logType = (string) ($row['log_type'] ?? 'unknown');

                $karyawan = null;
                if ($fingerId !== '' && isset($karyawanByFinger[$fingerId])) {
                    $karyawan = $karyawanByFinger[$fingerId];
                } elseif ($employeeCode !== '' && isset($karyawanByCode[$employeeCode])) {
                    $karyawan = $karyawanByCode[$employeeCode];
                }

                $karyawanId = $karyawan ? (int) $karyawan->id : null;
                if ($employeeCode === '' && $karyawan?->employee_code) {
                    $employeeCode = strtoupper((string) $karyawan->employee_code);
                }
                if ($fingerId === '' && $karyawan?->finger_id) {
                    $fingerId = (string) $karyawan->finger_id;
                }

                $identity = $karyawanId
                    ? 'K:'.$karyawanId
                    : ($employeeCode !== '' ? 'E:'.$employeeCode : ($fingerId !== '' ? 'F:'.$fingerId : ''));
                if ($identity === '') {
                    $failed++;
                    $errors[] = ['row' => $ln, 'message' => 'Identity kosong setelah normalisasi.'];

                    continue;
                }
                $strictKey = $identity.'|'.$logAt;

                if ($clientLogId !== '' && isset($existingClientIds[$clientLogId])) {
                    $duplicates++;

                    continue;
                }
                if (isset($existingStrictKeys[$strictKey]) || isset($inRequestKeys[$strictKey])) {
                    $duplicates++;

                    continue;
                }
                $inRequestKeys[$strictKey] = true;
                if ($clientLogId !== '') {
                    $existingClientIds[$clientLogId] = true;
                }

                $toInsert[] = [
                    'karyawan_id' => $karyawanId,
                    'employee_code' => $employeeCode !== '' ? $employeeCode : null,
                    'finger_id' => $fingerId !== '' ? $fingerId : null,
                    'client_log_id' => $clientLogId !== '' ? $clientLogId : null,
                    'log_at' => $logAt,
                    'log_type' => $logType,
                    'source' => $source,
                    'device_code' => $deviceCode,
                    'notes' => $row['notes'] ?? null,
                    'is_active' => true,
                    'created_at' => $now,
                    'updated_at' => $now,
                ];
                if ($karyawanId === null) {
                    $unmappedInserted++;
                }
            }

            foreach (array_chunk($toInsert, 500) as $chunk) {
                if (empty($chunk)) {
                    continue;
                }
                try {
                    DB::table('attendance_logs')->insert($chunk);
                    $inserted += count($chunk);
                } catch (\Throwable $e) {
                    $failed += count($chunk);
                    $errors[] = ['row' => 0, 'message' => 'Batch insert gagal: '.$e->getMessage()];
                }
            }
        }

        return response()->json([
            'message' => 'Import log mesin selesai.',
            'inserted' => $inserted,
            'duplicates' => $duplicates,
            'failed' => $failed,
            'unmapped_inserted' => $unmappedInserted,
            'lock' => [
                'enabled' => $lockEnabled,
                'cutoff_time' => $lockCutoff,
                'override_used' => $lockOverride,
            ],
            'errors' => $errors,
        ]);
    }

    // =========================================================================
    // queueImportMachineLog() - Antrian import log mesin fingerprint
    // Dipanggil dari: POST /attendance-review/logs/import-machine
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function queueImportMachineLog(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'file' => ['required', 'file', 'mimes:txt,dat,csv,log'],
            'delimiter' => ['nullable', 'string', 'max:10'],
            'source' => ['nullable', 'string', 'max:40'],
            'device_code' => ['nullable', 'string', 'max:60'],
            'override_lock' => ['nullable', 'boolean'],
            'override_key' => ['nullable', 'string', 'max:255'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profilId = (int) $request->input('profil_bulan_id');
        $file = $request->file('file');
        $path = $file->store('attendance-review/import-machine-logs');
        $lineCount = 0;
        $realPath = $file->getRealPath();
        if ($realPath && is_file($realPath)) {
            $lines = file($realPath, FILE_IGNORE_NEW_LINES);
            $lineCount = is_array($lines) ? count(array_filter($lines, fn ($line) => trim((string) $line) !== '')) : 0;
        }

        $job = AttendanceExportJobModel::query()->create([
            'request_no' => 'ARU-'.now()->format('YmdHis').'-'.Str::upper(Str::random(4)),
            'user_id' => auth()->id(),
            'profil_bulan_id' => $profilId,
            'filters' => [
                'job_type' => 'import_machine_log',
                'stage' => 'queued',
                'message' => 'File sudah diterima, menunggu worker queue.',
                'file_path' => $path,
                'file_original_name' => $file->getClientOriginalName(),
                'delimiter' => strtolower(trim((string) $request->input('delimiter', 'auto'))) ?: 'auto',
                'source' => trim((string) $request->input('source', 'x100c-flashdisk')) ?: 'x100c-flashdisk',
                'device_code' => trim((string) $request->input('device_code', '')),
                'resolved_lock_override' => $this->canBypassIngestDateLockForUser() || $this->canOverrideIngestLock($request),
                'inserted' => 0,
                'duplicates' => 0,
                'failed' => 0,
                'unmapped_inserted' => 0,
            ],
            'status' => 'pending',
            'total_users' => max(1, $lineCount),
            'processed_users' => 0,
        ]);

        ImportMachineLogJob::dispatch((int) $job->id)->onQueue(self::QUEUE_NAME);

        return response()->json([
            'message' => 'Upload log masuk antrian. Proses akan berjalan di background.',
            'job_id' => (int) $job->id,
            'request_no' => (string) $job->request_no,
            'data' => [
                'job_id' => (int) $job->id,
                'request_no' => (string) $job->request_no,
            ],
        ], 202);
    }

    // =========================================================================
    // syncPublicApiLog() - Sinkronisasi log dari public API
    // Dipanggil dari: Route/API endpoint
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function syncPublicApiLog(Request $request): JsonResponse
    {
        @ini_set('max_execution_time', '0');
        @set_time_limit(0);

        $validator = Validator::make($request->all(), [
            '_export_job_id' => ['nullable', 'integer', 'exists:attendance_export_jobs,id'],
            'start_date' => ['required', 'date'],
            'end_date' => ['required', 'date', 'after_or_equal:start_date'],
            'api_key' => ['nullable', 'string', 'max:255'],
            'sn' => ['nullable', 'string', 'max:100'],
            'emp_code' => ['nullable', 'string', 'max:100'],
            'limit' => ['nullable', 'integer', 'min:1', 'max:1000'],
            'source' => ['nullable', 'string', 'max:40'],
            'override_lock' => ['nullable', 'boolean'],
            'override_key' => ['nullable', 'string', 'max:255'],
            'profil_bulan_id' => ['nullable', 'integer', 'exists:master_profil_bulans,id'],
            'rounding_rule_id' => ['nullable', 'integer', 'exists:master_pembulatan_jams,id'],
            'run_detect_after_sync' => ['nullable', 'boolean'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $startDate = Carbon::parse((string) $request->input('start_date'))->startOfDay();
        $endDate = Carbon::parse((string) $request->input('end_date'))->endOfDay();
        if ($startDate->diffInDays($endDate) > 31) {
            return response()->json(['message' => 'Range tanggal maksimal 31 hari per sync.'], 422);
        }

        $baseUrl = $this->getPublicSyncBaseUrl($request);
        $apiKey = $this->getPublicSyncApiKey($request);
        $limit = (int) ($request->input('limit') ?: 500);
        $source = trim((string) $request->input('source', 'wdms-public-api')) ?: 'wdms-public-api';
        $sn = trim((string) $request->input('sn', ''));
        $empCode = trim((string) $request->input('emp_code', ''));

        $fetched = 0;
        $normalizedCount = 0;
        $stats = ['inserted' => 0, 'duplicates' => 0, 'failed' => 0, 'errors' => []];
        $page = 0;
        $afterId = null;
        $lastResponseSample = null;

        $exportJobId = (int) $request->input('_export_job_id', 0);
        $exportJob = $exportJobId > 0 ? AttendanceExportJobModel::query()->find($exportJobId) : null;
        $lockOverrideResolved = $this->canBypassIngestDateLockForUser() || $this->canOverrideIngestLock($request);
        $apiExpectedTotal = null;

        /** @var AttendanceIngestApiController $ingestor */
        $ingestor = app(AttendanceIngestApiController::class);

        try {
            do {
                $page++;
                $query = [
                    'start_date' => $startDate->format('Y-m-d'),
                    'end_date' => $endDate->format('Y-m-d'),
                    'limit' => $limit,
                ];
                if ($sn !== '') {
                    $query['sn'] = $sn;
                }
                if ($empCode !== '') {
                    $query['emp_code'] = $empCode;
                }
                if ($afterId !== null && $afterId !== '') {
                    $query['after_id'] = $afterId;
                }

                $result = $this->requestPublicAttendanceApi($baseUrl, $apiKey, $query, 120);
                $payload = $result['payload'];
                $lastResponseSample = $payload;
                $rows = $this->extractPublicApiRows($payload);
                $fetched += count($rows);

                if ($apiExpectedTotal === null && is_array($payload)) {
                    // Best effort only; some APIs provide total count.
                    foreach (['total', 'total_count', 'totalCount', 'count'] as $k) {
                        if (isset($payload[$k]) && is_numeric($payload[$k])) {
                            $apiExpectedTotal = (int) $payload[$k];
                            break;
                        }
                    }
                    if ($apiExpectedTotal === null && isset($payload['meta']) && is_array($payload['meta']) && is_numeric($payload['meta']['total'] ?? null)) {
                        $apiExpectedTotal = (int) $payload['meta']['total'];
                    }
                }

                $normalizedRows = [];
                foreach ($rows as $row) {
                    $normalized = $this->normalizePublicTransactionRow($row, $source);
                    if ($normalized !== null) {
                        $normalizedRows[] = $normalized;
                    }
                }
                $normalizedCount += count($normalizedRows);

                if (count($normalizedRows) > 0) {
                    $batch = $ingestor->ingestNormalizedRowsWithResolvedLock(
                        $normalizedRows,
                        1,
                        $lockOverrideResolved
                    );
                    $stats['inserted'] += (int) ($batch['inserted'] ?? 0);
                    $stats['duplicates'] += (int) ($batch['duplicates'] ?? 0);
                    $stats['failed'] += (int) ($batch['failed'] ?? 0);
                    $stats['errors'] = array_slice(array_merge($stats['errors'], (array) ($batch['errors'] ?? [])), 0, 50);
                }

                if ($exportJob) {
                    // Throttle DB writes; update every page (max 100) or on the last page.
                    $exportJob->refresh();
                    if ((string) $exportJob->status === 'cancelled') {
                        return response()->json([
                            'message' => 'Sync API publik dibatalkan.',
                            'fetched' => $fetched,
                            'normalized' => $normalizedCount,
                            'inserted' => (int) ($stats['inserted'] ?? 0),
                            'duplicates' => (int) ($stats['duplicates'] ?? 0),
                            'failed' => (int) ($stats['failed'] ?? 0),
                            'cancelled' => true,
                        ]);
                    }
                    $filters = (array) ($exportJob->filters ?? []);
                    $exportJob->filters = array_merge($filters, [
                        'job_type' => 'sync_public_api',
                        'stage' => 'fetching',
                        'message' => "Memproses API publik... page {$page}".($apiExpectedTotal ? " | Estimasi total {$apiExpectedTotal}" : ''),
                        'page' => $page,
                        'expected_total' => $apiExpectedTotal,
                        'fetched' => $fetched,
                        'normalized' => $normalizedCount,
                        'inserted' => (int) $stats['inserted'],
                        'duplicates' => (int) $stats['duplicates'],
                        'failed' => (int) $stats['failed'],
                        'errors' => array_slice((array) $stats['errors'], 0, 10),
                    ]);
                    $exportJob->save();
                }

                $hasMore = $this->extractPublicApiHasMore($payload, $rows, $limit);
                $nextAfterId = $this->extractPublicApiNextAfterId($payload, $rows);
                if (! $hasMore || $nextAfterId === null || $nextAfterId === '' || $page >= 100) {
                    break;
                }
                $afterId = $nextAfterId;
            } while (true);
        } catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
            // Keep JSON payload from requestPublicAttendanceApi() (contains endpoint/response/tried_endpoints).
            throw $e;
        } catch (Throwable $e) {
            return response()->json([
                'message' => 'Gagal koneksi ke API publik: '.$e->getMessage(),
            ], 422);
        }

        if ($normalizedCount === 0) {
            return response()->json([
                'message' => 'Sync selesai, tetapi tidak ada transaksi valid pada range tersebut.',
                'fetched' => $fetched,
                'sample' => is_array($lastResponseSample) ? array_slice($lastResponseSample, 0, 5, true) : null,
            ]);
        }

        $detectPayload = null;
        $detectError = null;
        if ($request->boolean('run_detect_after_sync') && (int) $request->input('profil_bulan_id') > 0) {
            try {
                $detectRequest = Request::create('/attendance-review/detect', 'POST', [
                    'profil_bulan_id' => (int) $request->input('profil_bulan_id'),
                    'rounding_rule_id' => $request->filled('rounding_rule_id') ? (int) $request->input('rounding_rule_id') : null,
                ]);
                $detectResponse = $this->runDetection($detectRequest);
                $detectBody = (array) $detectResponse->getData(true);
                if ($detectResponse->getStatusCode() >= 400) {
                    $detectError = (string) ($detectBody['message'] ?? 'Run detection gagal dijalankan otomatis.');
                } else {
                    $detectPayload = (array) ($detectBody['data'] ?? []);
                }
            } catch (Throwable $e) {
                $detectError = $e->getMessage();
            }
        }

        return response()->json([
            'message' => 'Sync API publik selesai.',
            'fetched' => $fetched,
            'normalized' => $normalizedCount,
            'inserted' => (int) ($stats['inserted'] ?? 0),
            'duplicates' => (int) ($stats['duplicates'] ?? 0),
            'failed' => (int) ($stats['failed'] ?? 0),
            'errors' => $stats['errors'] ?? [],
            'detect_job_id' => (int) ($detectPayload['job_id'] ?? $detectPayload['id'] ?? 0),
            'detect_message' => $detectPayload ? 'Run detection otomatis masuk antrian.' : null,
            'detect_error' => $detectError,
        ]);
    }

    // =========================================================================
    // queueSyncPublicApiLog() - Antrian sinkronisasi log public API
    // Dipanggil dari: POST /attendance-review/logs/sync-public-api
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function queueSyncPublicApiLog(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'attendance_profile_scope' => ['nullable', 'string', 'in:selected,main,sub,all'],
            'start_date' => ['required', 'date'],
            'end_date' => ['required', 'date', 'after_or_equal:start_date'],
            'api_key' => ['nullable', 'string', 'max:255'],
            'base_url' => ['nullable', 'string', 'max:255'],
            'sn' => ['nullable', 'string', 'max:100'],
            'emp_code' => ['nullable', 'string', 'max:100'],
            'limit' => ['nullable', 'integer', 'min:1', 'max:1000'],
            'source' => ['nullable', 'string', 'max:40'],
            'override_lock' => ['nullable', 'boolean'],
            'override_key' => ['nullable', 'string', 'max:255'],
            'rounding_rule_id' => ['nullable', 'integer', 'exists:master_pembulatan_jams,id'],
            'run_detect_after_sync' => ['nullable', 'boolean'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $startDate = Carbon::parse((string) $request->input('start_date'))->startOfDay();
        $endDate = Carbon::parse((string) $request->input('end_date'))->endOfDay();
        if ($startDate->diffInDays($endDate) > 31) {
            return response()->json(['message' => 'Range tanggal maksimal 31 hari per sync.'], 422);
        }

        $job = AttendanceExportJobModel::query()->create([
            'request_no' => 'ARS-'.now()->format('YmdHis').'-'.Str::upper(Str::random(4)),
            'user_id' => auth()->id(),
            'profil_bulan_id' => (int) $request->input('profil_bulan_id'),
            'filters' => [
                'job_type' => 'sync_public_api',
                'stage' => 'queued',
                'message' => 'Sync API menunggu worker queue.',
                'base_url' => trim((string) $request->input('base_url', '')),
                'api_key_set' => $this->getPublicSyncApiKey($request) !== '',
                'start_date' => $startDate->format('Y-m-d'),
                'end_date' => $endDate->format('Y-m-d'),
                'sn' => trim((string) $request->input('sn', '')),
                'emp_code' => trim((string) $request->input('emp_code', '')),
                'limit' => (int) ($request->input('limit') ?: 500),
                'source' => trim((string) $request->input('source', 'wdms-public-api')) ?: 'wdms-public-api',
                'attendance_profile_scope' => (string) ($request->input('attendance_profile_scope') ?: 'selected'),
                'rounding_rule_id' => $request->filled('rounding_rule_id') ? (int) $request->input('rounding_rule_id') : null,
                'resolved_lock_override' => $this->canBypassIngestDateLockForUser() || $this->canOverrideIngestLock($request),
                'run_detect_after_sync' => $request->boolean('run_detect_after_sync'),
                'fetched' => 0,
                'normalized' => 0,
                'inserted' => 0,
                'duplicates' => 0,
                'failed' => 0,
            ],
            'status' => 'pending',
            'total_users' => 100,
            'processed_users' => 0,
        ]);

        SyncPublicApiLogJob::dispatch((int) $job->id)->onQueue(self::QUEUE_NAME);

        return response()->json([
            'message' => 'Sync API masuk antrian. Proses akan berjalan di background.',
            'job_id' => (int) $job->id,
            'request_no' => (string) $job->request_no,
            'data' => [
                'job_id' => (int) $job->id,
                'request_no' => (string) $job->request_no,
            ],
        ], 202);
    }

    // =========================================================================
    // previewPublicApiLog() - Preview data dari public API
    // Dipanggil dari: POST /attendance-review/logs/preview-public-api
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function previewPublicApiLog(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'start_date' => ['required', 'date'],
            'end_date' => ['required', 'date', 'after_or_equal:start_date'],
            'api_key' => ['nullable', 'string', 'max:255'],
            'sn' => ['nullable', 'string', 'max:100'],
            'emp_code' => ['nullable', 'string', 'max:100'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $startDate = Carbon::parse((string) $request->input('start_date'))->startOfDay();
        $endDate = Carbon::parse((string) $request->input('end_date'))->endOfDay();
        if ($startDate->diffInDays($endDate) > 31) {
            return response()->json(['message' => 'Range tanggal maksimal 31 hari per preview.'], 422);
        }

        $baseUrl = $this->getPublicSyncBaseUrl($request);
        $apiKey = $this->getPublicSyncApiKey($request);
        $sn = trim((string) $request->input('sn', ''));
        $empCode = trim((string) $request->input('emp_code', ''));

        $total = 0;
        $sample = [];
        $page = 0;
        $afterId = null;

        try {
            do {
                $page++;
                $query = [
                    'start_date' => $startDate->format('Y-m-d'),
                    'end_date' => $endDate->format('Y-m-d'),
                    'limit' => 5000,
                ];
                if ($sn !== '') {
                    $query['sn'] = $sn;
                }
                if ($empCode !== '') {
                    $query['emp_code'] = $empCode;
                }
                if ($afterId !== null && $afterId !== '') {
                    $query['after_id'] = $afterId;
                }

                $result = $this->requestPublicAttendanceApi($baseUrl, $apiKey, $query, 30);
                $payload = $result['payload'];
                $rows = $this->extractPublicApiRows($payload);
                $total += count($rows);

                foreach ($rows as $row) {
                    if (count($sample) < 20) {
                        $sample[] = $row;
                    }
                }

                $afterId = $this->extractPublicApiNextAfterId($payload, $rows);
                $hasMore = $this->extractPublicApiHasMore($payload, $rows, 5000);
            } while ($hasMore && $afterId && $page < 100);
        } catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
            // Keep JSON payload from requestPublicAttendanceApi() (contains endpoint/response/tried_endpoints).
            throw $e;
        } catch (Throwable $e) {
            return response()->json([
                'message' => 'Preview API publik gagal: '.$e->getMessage(),
            ], 422);
        }

        return response()->json([
            'ok' => true,
            'total' => $total,
            'sample' => $sample,
        ]);
    }

    // =========================================================================
    // testPublicApiConnection() - Test koneksi ke public API
    // Dipanggil dari: POST /attendance-review/logs/test-public-api
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function testPublicApiConnection(Request $request): JsonResponse
    {
        $baseUrl = $this->getPublicSyncBaseUrl($request);
        $apiKey = $this->getPublicSyncApiKey($request);
        $today = Carbon::today()->format('Y-m-d');

        try {
            $result = $this->requestPublicAttendanceApi($baseUrl, $apiKey, [
                'start_date' => $today,
                'end_date' => $today,
                'limit' => 1,
            ], 20);

            $rows = $this->extractPublicApiRows($result['payload']);

            return response()->json([
                'ok' => true,
                'message' => 'API publik bisa diakses.',
                'endpoint' => $result['endpoint'],
                'count' => count($rows),
                'sample' => $rows[0] ?? null,
                'tried_endpoints' => array_map(fn ($path) => $baseUrl.$path, $this->publicSyncTransactionPaths()),
            ]);
        } catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
            throw $e;
        } catch (Throwable $e) {
            return response()->json([
                'ok' => false,
                'message' => 'Tes koneksi API publik gagal: '.$e->getMessage(),
                'tried_endpoints' => array_map(fn ($path) => $baseUrl.$path, $this->publicSyncTransactionPaths()),
            ], 422);
        }
    }

    // =========================================================================
    // destroyLog() - Hapus log attendance
    // Dipanggil dari: DELETE /attendance-review/logs/{id}
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function destroyLog(string $id): JsonResponse
    {
        AttendanceLogModel::query()->findOrFail($id)->delete();

        return response()->json(['message' => 'Log attendance deleted']);
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    // =========================================================================
    // extractPublicApiRows() - Mengekstrak data dari sumber
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    protected function extractPublicApiRows(mixed $payload): array
    {
        if (is_array($payload)) {
            foreach (['data', 'rows', 'items', 'transactions', 'result'] as $key) {
                $candidate = $payload[$key] ?? null;
                if (is_array($candidate) && array_is_list($candidate)) {
                    return array_values(array_filter($candidate, fn ($row) => is_array($row)));
                }
            }

            if (array_is_list($payload)) {
                return array_values(array_filter($payload, fn ($row) => is_array($row)));
            }
        }

        return [];
    }

    // =========================================================================
    // extractPublicApiHasMore() - Mengekstrak data dari sumber
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    protected function extractPublicApiHasMore(mixed $payload, array $rows, int $limit): bool
    {
        if (is_array($payload)) {
            foreach (['has_more', 'hasMore', 'next_page', 'nextPage'] as $key) {
                if (array_key_exists($key, $payload)) {
                    return (bool) $payload[$key];
                }
            }
        }

        return count($rows) >= $limit && $limit > 0;
    }

    // =========================================================================
    // extractPublicApiNextAfterId() - Mengekstrak data dari sumber
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    protected function extractPublicApiNextAfterId(mixed $payload, array $rows): string|int|null
    {
        if (is_array($payload)) {
            foreach (['after_id', 'next_after_id', 'nextAfterId', 'last_id', 'lastId'] as $key) {
                if (isset($payload[$key]) && $payload[$key] !== '') {
                    return $payload[$key];
                }
            }
        }

        $last = end($rows);
        if (is_array($last)) {
            foreach (['id', 'log_id', 'transaction_id', 'after_id'] as $key) {
                if (isset($last[$key]) && $last[$key] !== '') {
                    return $last[$key];
                }
            }
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $row
     * @return array<string, mixed>|null
     */
    // =========================================================================
    // normalizePublicTransactionRow() - Menormalisasi format data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    protected function normalizePublicTransactionRow(array $row, string $source): ?array
    {
        $value = function (array $keys) use ($row): ?string {
            foreach ($keys as $key) {
                if (array_key_exists($key, $row) && trim((string) $row[$key]) !== '') {
                    return trim((string) $row[$key]);
                }
            }

            return null;
        };

        $logAtRaw = $value(['log_at', 'datetime', 'checktime', 'transaction_time', 'punch_time', 'att_time', 'timestamp']);
        if ($logAtRaw === null) {
            $datePart = $value(['date', 'work_date', 'transaction_date']);
            $timePart = $value(['time', 'clock_time', 'transaction_clock']);
            if ($datePart !== null) {
                $logAtRaw = trim($datePart.' '.($timePart ?: '00:00:00'));
            }
        }

        if ($logAtRaw === null) {
            return null;
        }

        try {
            $logAt = Carbon::parse(str_replace('/', '-', $logAtRaw))->format('Y-m-d H:i:s');
        } catch (Throwable) {
            return null;
        }

        $empCode = strtoupper((string) ($value(['emp_code', 'employee_code', 'nik', 'userid']) ?? ''));
        $fingerId = (string) ($value(['finger_id', 'pin', 'enrollnumber', 'fingerid', 'user_id']) ?? '');
        $deviceCode = $value(['sn', 'device_sn', 'device_code', 'terminal_sn']);
        $typeRaw = strtolower((string) ($value(['log_type', 'status', 'inout', 'punch_state', 'verify_mode']) ?? ''));
        $logType = 'unknown';
        if (in_array($typeRaw, ['0', 'checkin', 'in', 'masuk'], true)) {
            $logType = 'in';
        } elseif (in_array($typeRaw, ['1', 'checkout', 'out', 'pulang'], true)) {
            $logType = 'out';
        }

        $clientId = $value(['id', 'transaction_id', 'log_id', 'record_id']);
        if ($clientId === null || $clientId === '') {
            $clientId = md5(implode('|', [$fingerId, $empCode, $deviceCode, $logAt, $logType]));
        }

        return [
            'employee_code' => $empCode !== '' ? $empCode : null,
            'finger_id' => $fingerId !== '' ? $fingerId : null,
            'client_log_id' => 'wdms-public-'.$clientId,
            'log_at' => $logAt,
            'log_type' => $logType,
            'source' => $source,
            'device_code' => $deviceCode,
            'notes' => trim((string) ($value(['remark', 'notes']) ?? 'sync api publik attendance')),
        ];
    }

    // =========================================================================
    // repairLogMapping() - Perbaiki mapping log attendance
    // Dipanggil dari: POST /attendance-review/logs/repair-mapping
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function repairLogMapping(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'source' => ['nullable', 'string', 'max:40'],
            'device_code' => ['nullable', 'string', 'max:60'],
            'limit' => ['nullable', 'integer', 'min:1', 'max:100000'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $source = trim((string) $request->input('source', ''));
        $deviceCode = trim((string) $request->input('device_code', ''));
        $limit = (int) $request->input('limit', 20000);

        $q = AttendanceLogModel::query()
            ->whereNull('karyawan_id')
            ->where(function ($x): void {
                $x->whereNotNull('finger_id')->where('finger_id', '<>', '')
                    ->orWhere(function ($y): void {
                        $y->whereNotNull('employee_code')->where('employee_code', '<>', '');
                    });
            })
            ->orderBy('id');

        if ($source !== '') {
            $q->where('source', $source);
        }
        if ($deviceCode !== '') {
            $q->where('device_code', $deviceCode);
        }

        $rows = $q->limit($limit)->get(['id', 'karyawan_id', 'employee_code', 'finger_id']);
        if ($rows->isEmpty()) {
            return response()->json([
                'message' => 'Tidak ada log NULL yang bisa direpair.',
                'data' => [
                    'checked' => 0,
                    'repaired' => 0,
                    'still_unmapped' => 0,
                ],
            ]);
        }

        $employeeCodes = $rows->pluck('employee_code')
            ->filter(fn ($v) => trim((string) $v) !== '')
            ->map(fn ($v) => strtoupper(trim((string) $v)))
            ->unique()
            ->values();
        $fingerIds = $rows->pluck('finger_id')
            ->filter(fn ($v) => trim((string) $v) !== '')
            ->map(fn ($v) => trim((string) $v))
            ->unique()
            ->values();

        $karyawanByCode = collect();
        if ($employeeCodes->isNotEmpty()) {
            $karyawanByCode = KaryawanModel::query()
                ->whereIn('employee_code', $employeeCodes->all())
                ->get(['id', 'employee_code', 'finger_id'])
                ->keyBy(fn ($r) => strtoupper((string) $r->employee_code));
        }
        $karyawanByFinger = collect();
        if ($fingerIds->isNotEmpty()) {
            $karyawanByFinger = KaryawanModel::query()
                ->whereIn('finger_id', $fingerIds->all())
                ->get(['id', 'employee_code', 'finger_id'])
                ->keyBy(fn ($r) => (string) $r->finger_id);
        }
        $karyawanByFingerHistory = collect();
        if ($fingerIds->isNotEmpty()) {
            $karyawanByFingerHistory = KaryawanFingerHistoryModel::query()
                ->with('karyawan:id,employee_code,finger_id')
                ->whereIn('finger_id', $fingerIds->all())
                ->where('is_active', true)
                ->orderByDesc('id')
                ->get()
                ->groupBy(fn ($r) => (string) $r->finger_id)
                ->map(function ($group) {
                    $first = $group->first();

                    return $first?->karyawan;
                });
        }

        $repaired = 0;
        foreach ($rows as $row) {
            $finger = trim((string) ($row->finger_id ?? ''));
            $code = strtoupper(trim((string) ($row->employee_code ?? '')));

            $karyawan = null;
            if ($finger !== '' && $karyawanByFinger->has($finger)) {
                $karyawan = $karyawanByFinger->get($finger);
            } elseif ($finger !== '' && $karyawanByFingerHistory->has($finger)) {
                $karyawan = $karyawanByFingerHistory->get($finger);
            } elseif ($code !== '' && $karyawanByCode->has($code)) {
                $karyawan = $karyawanByCode->get($code);
            }

            if (! $karyawan) {
                continue;
            }

            $updated = AttendanceLogModel::query()
                ->where('id', (int) $row->id)
                ->update([
                    'karyawan_id' => (int) $karyawan->id,
                    'employee_code' => $code !== '' ? $code : (string) ($karyawan->employee_code ?? ''),
                    'finger_id' => $finger !== '' ? $finger : (string) ($karyawan->finger_id ?? ''),
                    'updated_at' => now(),
                ]);

            if ($updated > 0) {
                $repaired++;
            }
        }

        $stillUnmapped = AttendanceLogModel::query()
            ->whereNull('karyawan_id')
            ->when($source !== '', fn ($x) => $x->where('source', $source))
            ->when($deviceCode !== '', fn ($x) => $x->where('device_code', $deviceCode))
            ->count();

        return response()->json([
            'message' => 'Repair mapping selesai.',
            'data' => [
                'checked' => $rows->count(),
                'repaired' => $repaired,
                'still_unmapped' => (int) $stillUnmapped,
                'source' => $source !== '' ? $source : null,
                'device_code' => $deviceCode !== '' ? $deviceCode : null,
            ],
        ]);
    }

    // =========================================================================
    // resolveImportDelimiter() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveImportDelimiter(string $input, string $sample): string
    {
        if (in_array($input, [',', ';', "\t", '|'], true)) {
            return $input;
        }
        if ($input === 'tab') {
            return "\t";
        }
        if ($input === 'semicolon') {
            return ';';
        }
        if ($input === 'pipe') {
            return '|';
        }
        if ($input === 'comma') {
            return ',';
        }

        $candidates = [',', ';', "\t", '|'];
        $best = ',';
        $score = -1;
        foreach ($candidates as $d) {
            $parts = str_getcsv($sample, $d);
            $count = count(array_filter($parts, fn ($x) => trim((string) $x) !== ''));
            if ($count > $score) {
                $score = $count;
                $best = $d;
            }
        }

        return $best;
    }

    // =========================================================================
    // hasMachineLikelyHeader() - Cek kondisi tertentu, return bool
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function hasMachineLikelyHeader(array $fields): bool
    {
        $keys = array_map(fn ($f) => strtolower(trim((string) $f)), $fields);
        $joined = ' '.implode(' ', $keys).' ';
        foreach ([' user', ' pin', ' id', ' nik', ' date', ' time', ' check', ' punch', ' log', ' status'] as $token) {
            if (str_contains($joined, $token)) {
                return true;
            }
        }

        return false;
    }

    // =========================================================================
    // isAppSettingTruthy() - Cek kondisi tertentu, return bool
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function isAppSettingTruthy(string $key, bool $default = false): bool
    {
        $raw = AppSetting::query()->where('key', $key)->value('value');
        if ($raw === null) {
            return $default;
        }
        $v = strtolower(trim((string) $raw));

        return in_array($v, ['1', 'true', 'yes', 'on'], true);
    }

    // =========================================================================
    // getAppSettingTime() - Mengambil/mendapatkan data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function getAppSettingTime(string $key, string $default): string
    {
        $raw = trim((string) (AppSetting::query()->where('key', $key)->value('value') ?? ''));
        if ($raw !== '' && preg_match('/^\d{2}:\d{2}$/', $raw)) {
            return $raw;
        }

        return $default;
    }

    // =========================================================================
    // canOverrideIngestLock() - Cek kondisi tertentu, return bool
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function canOverrideIngestLock(Request $request): bool
    {
        if (app()->runningInConsole() && $request->boolean('_resolved_lock_override')) {
            return true;
        }

        if (! $request->boolean('override_lock')) {
            return false;
        }

        if ($this->isAdministrator(auth()->user())) {
            return true;
        }

        $provided = trim((string) $request->input('override_key', ''));
        if ($provided === '') {
            return false;
        }

        $configured = trim((string) (
            AppSetting::query()->where('key', 'attendance.ingest.lock_override_key')->value('value')
            ?: env('ATTENDANCE_INGEST_LOCK_OVERRIDE_KEY', '')
        ));
        if ($configured === '') {
            return false;
        }

        return hash_equals($configured, $provided);
    }

    // =========================================================================
    // validateIngestDateLockForReview() - Validasi input/data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function validateIngestDateLockForReview(
        Carbon $logAt,
        bool $enabled,
        string $cutoffTime,
        bool $overrideUsed
    ): ?string {
        // Administrator/HRD can ingest older logs without providing override key/flag.
        if ($this->canBypassIngestDateLockForUser()) {
            return null;
        }

        if (! $enabled || $overrideUsed) {
            return null;
        }

        $today = now()->startOfDay();
        $logDate = $logAt->copy()->startOfDay();
        if ($logDate->gte($today)) {
            return null;
        }

        $diffDays = $logDate->diffInDays($today);
        $cutoffAt = Carbon::parse($today->format('Y-m-d').' '.$cutoffTime.':00');
        $now = now();

        if ($diffDays >= 2) {
            return 'Tanggal '.$logDate->format('Y-m-d').' sudah dikunci (lebih dari kemarin).';
        }
        if ($diffDays === 1 && $now->gte($cutoffAt)) {
            return 'Tanggal kemarin sudah dikunci setelah jam '.$cutoffTime.'.';
        }

        return null;
    }

    // =========================================================================
    // normalizeMachineAssocRow() - Menormalisasi format data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function normalizeMachineAssocRow(array $assoc, int $lineNo, string $source, ?string $deviceCode): array
    {
        $value = function (array $keys) use ($assoc): ?string {
            foreach ($keys as $key) {
                if (array_key_exists($key, $assoc) && trim((string) $assoc[$key]) !== '') {
                    return trim((string) $assoc[$key]);
                }
            }

            return null;
        };

        $finger = $value(['finger_id', 'fingerid', 'id_finger', 'pin', 'uid', 'user_id', 'enrollnumber']);
        $employeeCode = $value(['employee_code', 'nik', 'userid', 'badge', 'emp_code']);
        $logTypeRaw = $value(['log_type', 'inout', 'status', 'punch_state', 'io_mode', 'verify_mode']);
        $logAt = $this->normalizeMachineDateTime($value(['log_at', 'datetime', 'checktime', 'att_time', 'timestamp']));
        if ($logAt === null) {
            $datePart = $value(['work_date', 'date', 'tanggal']);
            $timePart = $value(['time', 'jam', 'clock_time']);
            if ($datePart !== null) {
                $logAt = $this->normalizeMachineDateTime(trim($datePart.' '.($timePart ?? '00:00:00')));
            }
        }

        return [
            'finger_id' => $finger,
            'employee_code' => $employeeCode,
            'log_type' => $this->normalizeMachineLogType($logTypeRaw),
            'log_at' => $logAt,
            'source' => $source,
            'device_code' => $deviceCode,
            'client_log_id' => $value(['client_log_id']) ?: $this->buildMachineClientLogId('machine-header', $deviceCode, $finger, $employeeCode, $logAt, $lineNo),
            'notes' => $value(['notes', 'remark']) ?: 'import flashdisk machine',
            '_line_no' => $lineNo,
        ];
    }

    // =========================================================================
    // normalizeMachinePositionalRow() - Menormalisasi format data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function normalizeMachinePositionalRow(array $fields, int $lineNo, string $source, ?string $deviceCode): array
    {
        $clean = array_values(array_filter(array_map(fn ($f) => trim((string) $f), $fields), fn ($f) => $f !== ''));
        $datetimeIdx = null;
        $logAt = null;
        foreach ($clean as $idx => $val) {
            $dt = $this->normalizeMachineDateTime($val);
            if ($dt !== null) {
                $datetimeIdx = $idx;
                $logAt = $dt;
                break;
            }
        }

        $finger = $clean[0] ?? null;
        $employeeCode = null;
        $logTypeRaw = null;

        if ($datetimeIdx !== null) {
            if ($datetimeIdx > 1 && isset($clean[1])) {
                $employeeCode = $clean[1];
            }
            $logTypeRaw = $clean[$datetimeIdx + 2] ?? $clean[$datetimeIdx + 1] ?? null;
        } else {
            $employeeCode = $clean[1] ?? null;
            $logTypeRaw = $clean[2] ?? null;
            $logAt = $this->normalizeMachineDateTime($clean[3] ?? null);
        }

        return [
            'finger_id' => $finger,
            'employee_code' => $employeeCode,
            'log_type' => $this->normalizeMachineLogType($logTypeRaw),
            'log_at' => $logAt,
            'source' => $source,
            'device_code' => $deviceCode,
            'client_log_id' => $this->buildMachineClientLogId('machine-positional', $deviceCode, $finger, $employeeCode, $logAt, $lineNo),
            'notes' => 'import flashdisk machine',
            '_line_no' => $lineNo,
        ];
    }

    // =========================================================================
    // normalizeMachineDateTime() - Menormalisasi format data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function normalizeMachineDateTime(?string $input): ?string
    {
        $raw = trim((string) ($input ?? ''));
        if ($raw === '') {
            return null;
        }
        $raw = str_replace('/', '-', $raw);
        try {
            return Carbon::parse($raw)->format('Y-m-d H:i:s');
        } catch (\Throwable) {
            return null;
        }
    }

    // =========================================================================
    // normalizeMachineLogType() - Menormalisasi format data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function normalizeMachineLogType(?string $value): string
    {
        $raw = strtolower(trim((string) ($value ?? '')));
        if ($raw === '' || $raw === '255') {
            return 'unknown';
        }
        if (in_array($raw, ['0', 'in', 'checkin', 'check-in', 'masuk'], true)) {
            return 'in';
        }
        if (in_array($raw, ['1', 'out', 'checkout', 'check-out', 'pulang'], true)) {
            return 'out';
        }

        return 'unknown';
    }

    // =========================================================================
    // buildMachineClientLogId() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildMachineClientLogId(
        string $prefix,
        ?string $deviceCode,
        ?string $fingerId,
        ?string $employeeCode,
        ?string $logAt,
        int $lineNo
    ): string {
        $parts = [
            strtoupper($prefix),
            strtoupper(trim((string) ($deviceCode ?? ''))) ?: 'DEVICE',
            strtoupper(trim((string) ($fingerId ?? ''))) ?: strtoupper(trim((string) ($employeeCode ?? ''))) ?: 'USER',
            $logAt ? str_replace(['-', ':', ' '], '', $logAt) : 'NOLOGAT',
            'L'.$lineNo,
        ];

        return implode('-', $parts);
    }

    // =========================================================================
    // runDetection() - Menjalankan deteksi attendance
    // Dipanggil dari: POST /attendance-review/detect
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function runDetection(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'attendance_profile_scope' => ['nullable', 'string', 'in:selected,main,sub,all,both'],
            'rounding_rule_id' => ['nullable', 'integer', 'exists:master_pembulatan_jams,id'],
            'karyawan_id' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['required_without:karyawan_id', 'array', 'min:1', 'max:50'],
            'karyawan_ids.*' => ['integer', 'distinct', 'exists:master_karyawans,id'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profilId = (int) $request->input('profil_bulan_id');
        $profil = ProfilBulanModel::query()->findOrFail($profilId);
        $attendanceScope = (string) $request->input('attendance_profile_scope', 'selected');
        $attendanceScope = $attendanceScope === 'all' ? 'both' : $attendanceScope;
        $targetProfilIds = $attendanceScope === 'selected'
            ? [$profilId]
            : $this->summaryProfileIds($profil, $attendanceScope);
        $roundingId = $request->filled('rounding_rule_id') ? (int) $request->input('rounding_rule_id') : null;
        $karyawanId = $request->filled('karyawan_id') ? (int) $request->input('karyawan_id') : null;

        $jobs = [];
        foreach ($targetProfilIds as $targetProfilId) {
            $targetProfilId = (int) $targetProfilId;
            $totalUsers = ProfilBulanKaryawanModel::query()
                ->where('profil_bulan_id', $targetProfilId)
                ->where('is_active', true)
                ->when($karyawanId, fn ($q) => $q->where('karyawan_id', $karyawanId))
                ->count();
            if ($totalUsers <= 0) {
                continue;
            }

            $existingJob = $this->findOverlappingAttendanceMutationJob($targetProfilId, $karyawanId, null, null, ['detect']);
            if ($existingJob) {
                $jobs[] = $this->attendanceMutationJobPayload($existingJob);
                continue;
            }

            $blockingJob = $this->findOverlappingAttendanceMutationJob($targetProfilId, $karyawanId, null, null, ['rebuild_planning']);
            if ($blockingJob) {
                continue;
            }

            $job = AttendanceExportJobModel::query()->create([
                'request_no' => 'ARD-'.now()->format('YmdHis').'-'.Str::upper(Str::random(4)),
                'user_id' => auth()->id(),
                'profil_bulan_id' => $targetProfilId,
                'filters' => [
                    'job_type' => 'detect',
                    'attendance_profile_scope' => $attendanceScope,
                    'rounding_rule_id' => $roundingId,
                    'karyawan_id' => $karyawanId,
                ],
                'status' => 'pending',
                'total_users' => (int) $totalUsers,
                'processed_users' => 0,
            ]);

            RunAttendanceDetectionJob::dispatch((int) $job->id)->onQueue(self::QUEUE_NAME);
            $jobs[] = [
                'job_id' => (int) $job->id,
                'request_no' => (string) $job->request_no,
                'profil_bulan_id' => $targetProfilId,
            ];
        }

        if (! $jobs) {
            return response()->json(['message' => 'Tidak ada assignment aktif atau scope sedang diblokir job lain.'], 422);
        }

        return response()->json([
            'message' => 'Run detection dimulai di background.',
            'data' => [
                'job_id' => (int) ($jobs[0]['job_id'] ?? 0),
                'request_no' => (string) ($jobs[0]['request_no'] ?? ''),
                'queued_jobs' => $jobs,
            ],
        ]);
    }

    // =========================================================================
    // rebuildPlanning() - Membangun ulang planning attendance
    // Dipanggil dari: POST /attendance-review/rebuild-planning
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function rebuildPlanning(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'attendance_profile_scope' => ['nullable', 'string', 'in:selected,main,sub,all,both'],
            'karyawan_id' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['required_without:karyawan_id', 'array', 'min:1', 'max:50'],
            'karyawan_ids.*' => ['integer', 'distinct', 'exists:master_karyawans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profil = ProfilBulanModel::query()->findOrFail((int) $request->input('profil_bulan_id'));
        $attendanceScope = (string) $request->input('attendance_profile_scope', 'selected');
        $attendanceScope = $attendanceScope === 'all' ? 'both' : $attendanceScope;
        $targetProfilIds = $attendanceScope === 'selected'
            ? [(int) $profil->id]
            : $this->summaryProfileIds($profil, $attendanceScope);
        $periodStart = Carbon::parse($profil->start_date)->startOfDay();
        $periodEnd = Carbon::parse($profil->end_date)->startOfDay();
        $filterDateFrom = $request->filled('date_from') ? Carbon::parse($request->input('date_from'))->startOfDay() : null;
        $filterDateTo = $request->filled('date_to') ? Carbon::parse($request->input('date_to'))->startOfDay() : null;
        $effectiveStart = $filterDateFrom && $filterDateFrom->gt($periodStart) ? $filterDateFrom : $periodStart->copy();
        $effectiveEnd = $filterDateTo && $filterDateTo->lt($periodEnd) ? $filterDateTo : $periodEnd->copy();

        if ($effectiveStart->gt($effectiveEnd)) {
            return response()->json(['message' => 'Range tanggal tidak valid.'], 422);
        }

        $karyawanId = $request->filled('karyawan_id') ? (int) $request->input('karyawan_id') : null;

        $jobs = [];
        foreach ($targetProfilIds as $targetProfilId) {
            $targetProfilId = (int) $targetProfilId;
            $employeeIds = ProfilBulanKaryawanModel::query()
                ->where('profil_bulan_id', $targetProfilId)
                ->where('is_active', true)
                ->when($karyawanId, fn ($q) => $q->where('karyawan_id', $karyawanId))
                ->pluck('karyawan_id')
                ->map(fn ($id) => (int) $id)
                ->filter()
                ->values();
            if ($employeeIds->isEmpty()) {
                continue;
            }

            $totalReviews = AttendanceDailyReviewModel::query()
                ->where('profil_bulan_id', $targetProfilId)
                ->whereIn('karyawan_id', $employeeIds->all())
                ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
                ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
                ->count();
            if ($totalReviews <= 0) {
                continue;
            }

            $existingJob = $this->findOverlappingAttendanceMutationJob($targetProfilId, $karyawanId, $effectiveStart, $effectiveEnd, ['rebuild_planning']);
            if ($existingJob) {
                $jobs[] = $this->attendanceMutationJobPayload($existingJob);
                continue;
            }

            $blockingJob = $this->findOverlappingAttendanceMutationJob($targetProfilId, $karyawanId, $effectiveStart, $effectiveEnd, ['detect']);
            if ($blockingJob) {
                continue;
            }

            $job = AttendanceExportJobModel::query()->create([
                'request_no' => 'ARB-'.now()->format('YmdHis').'-'.Str::upper(Str::random(4)),
                'user_id' => auth()->id(),
                'profil_bulan_id' => $targetProfilId,
                'filters' => [
                    'job_type' => 'rebuild_planning',
                    'attendance_profile_scope' => $attendanceScope,
                    'karyawan_id' => $karyawanId,
                    'date_from' => $effectiveStart->format('Y-m-d'),
                    'date_to' => $effectiveEnd->format('Y-m-d'),
                    'updated' => 0,
                    'skipped' => 0,
                    'reset_approval' => 0,
                    'affected_rows' => 0,
                ],
                'status' => 'pending',
                'total_users' => (int) $totalReviews,
                'processed_users' => 0,
            ]);

            RebuildPlanningJob::dispatch((int) $job->id)->onQueue(self::QUEUE_NAME);
            $jobs[] = [
                'job_id' => (int) $job->id,
                'request_no' => (string) $job->request_no,
                'profil_bulan_id' => $targetProfilId,
            ];
        }

        if (! $jobs) {
            return response()->json(['message' => 'Tidak ada assignment/review aktif atau scope sedang diblokir job lain.'], 422);
        }

        return response()->json([
            'message' => 'Rebuild planning dimulai di background.',
            'data' => [
                'job_id' => (int) ($jobs[0]['job_id'] ?? 0),
                'request_no' => (string) ($jobs[0]['request_no'] ?? ''),
                'queued_jobs' => $jobs,
                'date_from' => $effectiveStart->format('Y-m-d'),
                'date_to' => $effectiveEnd->format('Y-m-d'),
            ],
        ]);
    }

    public function shiftShortcutRefs(): JsonResponse
    {
        $shifts = ProfilJamKerjaModel::query()
            ->where('is_active', true)
            ->orderBy('code')
            ->orderBy('name')
            ->get(['id', 'code', 'name', 'start_time', 'end_time'])
            ->map(fn (ProfilJamKerjaModel $row) => [
                'id' => (int) $row->id,
                'code' => (string) ($row->code ?? ''),
                'name' => (string) ($row->name ?? ''),
                'start_time' => substr((string) ($row->start_time ?? ''), 0, 5),
                'end_time' => substr((string) ($row->end_time ?? ''), 0, 5),
            ])
            ->values();

        return response()->json(['data' => ['shifts' => $shifts]]);
    }

    public function storeShiftShortcut(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['required', 'integer', 'exists:master_karyawans,id'],
            'work_date' => ['required', 'date'],
            'profil_jam_kerja_id' => ['nullable', 'integer', 'exists:master_profil_jam_kerjas,id'],
            'notes' => ['nullable', 'string', 'max:500'],
            'clear_override' => ['nullable', 'boolean'],
            'rebuild' => ['nullable', 'boolean'],
            'detect' => ['nullable', 'boolean'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profil = ProfilBulanModel::query()->findOrFail((int) $request->input('profil_bulan_id'));
        if ($guard = $this->guardProfilBulanOpenForAttendance($profil)) {
            return $guard;
        }
        $date = Carbon::parse((string) $request->input('work_date'))->startOfDay();
        $periodStart = Carbon::parse((string) $profil->start_date)->startOfDay();
        $periodEnd = Carbon::parse((string) $profil->end_date)->startOfDay();
        if ($date->lt($periodStart) || $date->gt($periodEnd)) {
            return response()->json(['message' => 'Tanggal di luar periode profil bulan.'], 422);
        }

        $karyawanId = (int) $request->input('karyawan_id');
        $hasAssignment = ProfilBulanKaryawanModel::query()
            ->where('profil_bulan_id', (int) $profil->id)
            ->where('karyawan_id', $karyawanId)
            ->where('is_active', true)
            ->exists();
        if (! $hasAssignment) {
            return response()->json(['message' => 'Karyawan belum aktif di profil bulan ini.'], 422);
        }

        DB::transaction(function () use ($request, $profil, $date, $karyawanId): void {
            if ($request->boolean('clear_override')) {
                ShiftScheduleModel::query()
                    ->where('karyawan_id', $karyawanId)
                    ->whereDate('work_date', $date->format('Y-m-d'))
                    ->update([
                        'is_active' => false,
                        'notes' => DB::raw("CONCAT(COALESCE(notes, ''), ' | Dinonaktifkan dari Attendance Review V2.')"),
                        'updated_at' => now(),
                    ]);
                return;
            }

            ShiftScheduleModel::query()->updateOrCreate(
                [
                    'karyawan_id' => $karyawanId,
                    'work_date' => $date->format('Y-m-d'),
                ],
                [
                    'profil_bulan_id' => (int) $profil->id,
                    'profil_jam_kerja_id' => (int) $request->input('profil_jam_kerja_id'),
                    'source' => 'attendance_review_shortcut',
                    'is_locked' => false,
                    'notes' => trim((string) $request->input('notes')) ?: 'Shortcut dari Attendance Review V2.',
                    'is_active' => true,
                ]
            );
        });

        $jobs = [];
        if ($request->boolean('rebuild')) {
            $jobs['rebuild'] = $this->processRebuildPlanningJob(
                (int) $profil->id,
                $karyawanId,
                $date->format('Y-m-d'),
                $date->format('Y-m-d')
            );
        }
        if ($request->boolean('detect')) {
            $resp = $this->runDetection(new Request([
                'profil_bulan_id' => (int) $profil->id,
                'karyawan_id' => $karyawanId,
            ]))->getData(true);
            $jobs['detect'] = $resp['data'] ?? null;
        }

        return response()->json([
            'message' => $request->boolean('clear_override')
                ? 'Override shift harian dihapus.'
                : 'Override shift harian tersimpan.',
            'jobs' => $jobs,
        ]);
    }

    // =========================================================================
    // processRebuildPlanningJob() - Proses job rebuild planning
    // Dipanggil dari: Route/API endpoint
    // Output: Response (bervariasi)
    // =========================================================================
    public function processRebuildPlanningJob(int $profilId, ?int $karyawanId, ?string $dateFrom, ?string $dateTo, int $jobId = 0): array
    {
        $profil = ProfilBulanModel::query()->findOrFail($profilId);
        $periodStart = Carbon::parse($profil->start_date)->startOfDay();
        $periodEnd = Carbon::parse($profil->end_date)->startOfDay();
        $filterDateFrom = $dateFrom ? Carbon::parse($dateFrom)->startOfDay() : null;
        $filterDateTo = $dateTo ? Carbon::parse($dateTo)->startOfDay() : null;
        $effectiveStart = $filterDateFrom && $filterDateFrom->gt($periodStart) ? $filterDateFrom : $periodStart->copy();
        $effectiveEnd = $filterDateTo && $filterDateTo->lt($periodEnd) ? $filterDateTo : $periodEnd->copy();

        if ($effectiveStart->gt($effectiveEnd)) {
            throw new \RuntimeException('Range tanggal tidak valid.');
        }

        if ($jobId > 0 && ! $this->claimAttendanceMutationJob($jobId, $profilId, $karyawanId, $effectiveStart, $effectiveEnd)) {
            return ['updated' => 0, 'skipped' => 0, 'reset_approval' => 0, 'cancelled' => true];
        }

        $assignments = ProfilBulanKaryawanModel::query()
            ->with(['profilJamKerja:id,start_time,end_time', 'profilJamKerjaAlt:id,start_time,end_time'])
            ->where('profil_bulan_id', (int) $profil->id)
            ->where('is_active', true)
            ->when($karyawanId, fn ($q) => $q->where('karyawan_id', $karyawanId))
            ->get()
            ->keyBy(fn (ProfilBulanKaryawanModel $row) => (int) $row->karyawan_id);

        if ($assignments->isEmpty()) {
            throw new \RuntimeException('Tidak ada assignment aktif untuk filter ini.');
        }

        $employeeIds = $assignments->keys()->map(fn ($id) => (int) $id)->values();

        $customScheduleRows = DB::table('master_shift_schedules')
            ->whereIn('karyawan_id', $employeeIds->all())
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->where('is_active', true)
            ->where(function ($q) use ($profil): void {
                $q->whereNull('profil_bulan_id')
                    ->orWhere('profil_bulan_id', (int) $profil->id);
            })
            ->orderByRaw(
                'CASE
                    WHEN profil_bulan_id = ? AND is_locked = 1 THEN 1
                    WHEN profil_bulan_id = ? AND is_locked = 0 THEN 2
                    WHEN profil_bulan_id IS NULL AND is_locked = 1 THEN 3
                    ELSE 4
                END ASC',
                [(int) $profil->id, (int) $profil->id]
            )
            ->orderByDesc('id')
            ->get(['karyawan_id', 'work_date', 'profil_jam_kerja_id']);

        $customScheduleMap = [];
        $customScheduleEmployeeIds = [];
        $customShiftIds = [];
        foreach ($customScheduleRows as $row) {
            $dateKey = Carbon::parse((string) $row->work_date)->format('Y-m-d');
            $mapKey = ((int) $row->karyawan_id).'|'.$dateKey;
            if (isset($customScheduleMap[$mapKey])) {
                continue;
            }
            $shiftId = (int) ($row->profil_jam_kerja_id ?? 0);
            if ($shiftId <= 0) {
                continue;
            }
            $customScheduleMap[$mapKey] = $shiftId;
            $customScheduleEmployeeIds[(int) $row->karyawan_id] = true;
            $customShiftIds[$shiftId] = $shiftId;
        }

        $customShiftMap = collect();
        if (! empty($customShiftIds)) {
            $customShiftMap = ProfilJamKerjaModel::query()
                ->whereIn('id', array_values($customShiftIds))
                ->get(['id', 'start_time', 'end_time'])
                ->keyBy('id');
        }

        $reviews = AttendanceDailyReviewModel::query()
            ->where('profil_bulan_id', (int) $profil->id)
            ->whereIn('karyawan_id', $employeeIds->all())
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->orderBy('work_date')
            ->get();

        $updated = 0;
        $skipped = 0;
        $resetApproval = 0;
        $processed = 0;
        $job = $jobId > 0 ? AttendanceExportJobModel::query()->find($jobId) : null;

        foreach ($reviews as $review) {
            $assignment = $assignments->get((int) $review->karyawan_id);
            if (! $assignment) {
                $skipped++;
                $processed++;
                $this->syncRebuildJobProgress($job, $processed, $updated, $skipped, $resetApproval, $effectiveStart, $effectiveEnd);

                continue;
            }

            $workDate = $review->work_date instanceof Carbon
                ? $review->work_date->copy()->startOfDay()
                : Carbon::parse((string) $review->work_date)->startOfDay();
            $mapKey = ((int) $review->karyawan_id).'|'.$workDate->format('Y-m-d');
            $customShiftId = isset($customScheduleMap[$mapKey]) ? (int) $customScheduleMap[$mapKey] : 0;

            if ($customShiftId > 0 && $customShiftMap->has($customShiftId)) {
                $selectedShift = [
                    'shift' => $customShiftMap->get($customShiftId),
                    'shift_id' => $customShiftId,
                ];
            } else {
                $selectedShift = $this->resolveAssignedShiftForDate($assignment, $workDate);
            }

            if (! $selectedShift || empty($selectedShift['shift'])) {
                $skipped++;
                $processed++;
                $this->syncRebuildJobProgress($job, $processed, $updated, $skipped, $resetApproval, $effectiveStart, $effectiveEnd);

                continue;
            }

            $shift = $selectedShift['shift'];
            $selectedShiftId = (int) ($selectedShift['shift_id'] ?? 0);
            $shiftStart = Carbon::parse($workDate->format('Y-m-d').' '.substr((string) $shift->start_time, 0, 8));
            $shiftEnd = Carbon::parse($workDate->format('Y-m-d').' '.substr((string) $shift->end_time, 0, 8));
            $isCrossDay = $shiftEnd->lte($shiftStart);
            if ($isCrossDay) {
                $shiftEnd->addDay();
            }

            $payload = [
                'planned_profil_jam_kerja_id' => $selectedShiftId > 0 ? $selectedShiftId : ($assignment->profil_jam_kerja_id ?: null),
                'planned_shift_start' => $shiftStart->format('Y-m-d H:i:s'),
                'planned_shift_end' => $shiftEnd->format('Y-m-d H:i:s'),
                'is_cross_day' => $isCrossDay,
            ];

            if ($this->isReviewPlanningUnchanged($review, $payload)) {
                $skipped++;
                $processed++;
                $this->syncRebuildJobProgress($job, $processed, $updated, $skipped, $resetApproval, $effectiveStart, $effectiveEnd);

                continue;
            }

            $before = $this->snapshotReview($review);
            $review->fill($payload);

            $notes = 'Planning direbuild dari assignment profil terbaru.';
            $action = 'rebuild_planning';
            if ((bool) $review->is_approved) {
                $review->is_approved = false;
                $review->approved_by = null;
                $review->approved_at = null;
                $resetApproval++;
                $action = 'rebuild_planning_requires_reapprove';
                $notes = 'Planning berubah dari assignment profil terbaru. Approval direset agar direview ulang.';
            }

            $review->save();
            $this->saveHistory($review, $action, $before, $this->snapshotReview($review), $notes);
            $updated++;
            $processed++;
            $this->syncRebuildJobProgress($job, $processed, $updated, $skipped, $resetApproval, $effectiveStart, $effectiveEnd);
        }

        return [
            'updated' => $updated,
            'skipped' => $skipped,
            'reset_approval' => $resetApproval,
            'date_from' => $effectiveStart->format('Y-m-d'),
            'date_to' => $effectiveEnd->format('Y-m-d'),
        ];
    }

    // =========================================================================
    // syncRebuildJobProgress() - Mensinkronisasi data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function syncRebuildJobProgress(?AttendanceExportJobModel $job, int $processed, int $updated, int $skipped, int $resetApproval, Carbon $effectiveStart, Carbon $effectiveEnd): void
    {
        if (! $job) {
            return;
        }

        $shouldSync = $processed <= 1
            || $processed === (int) ($job->total_users ?? 0)
            || $processed % 10 === 0;

        if (! $shouldSync) {
            return;
        }

        $job->processed_users = $processed;
        $filters = (array) ($job->filters ?? []);
        $job->filters = array_merge($filters, [
            'job_type' => 'rebuild_planning',
            'updated' => $updated,
            'skipped' => $skipped,
            'reset_approval' => $resetApproval,
            'affected_rows' => $updated,
            'date_from' => $effectiveStart->format('Y-m-d'),
            'date_to' => $effectiveEnd->format('Y-m-d'),
        ]);
        $job->save();
    }

    // =========================================================================
    // logJobStatus() - Status job import/sync log
    // Dipanggil dari: GET /attendance-review/logs/jobs/{id}/status
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function logJobStatus(string $id): JsonResponse
    {
        $row = AttendanceExportJobModel::query()->findOrFail((int) $id);
        $filters = (array) ($row->filters ?? []);
        $jobType = (string) ($filters['job_type'] ?? '');
        if (! in_array($jobType, ['import_machine_log', 'sync_public_api'], true)) {
            return response()->json(['message' => 'Job bukan tipe import/sync log.'], 422);
        }

        $totalUsers = (int) ($row->total_users ?? 0);
        $processedUsers = (int) ($row->processed_users ?? 0);
        $pct = $totalUsers > 0 ? (int) floor(($processedUsers / max(1, $totalUsers)) * 100) : 0;

        // Sync API: total unit unknown until job ends; compute a stable "progress %" from live stats.
        if ($jobType === 'sync_public_api') {
            $status = (string) ($row->status ?? 'pending');
            $stage = (string) ($filters['stage'] ?? '');
            $fetched = (int) ($filters['fetched'] ?? 0);
            $expected = (int) ($filters['expected_total'] ?? 0);
            $normalized = (int) ($filters['normalized'] ?? 0);
            $doneRows = (int) ($filters['inserted'] ?? 0) + (int) ($filters['duplicates'] ?? 0) + (int) ($filters['failed'] ?? 0);

            if ($status === 'done') {
                $pct = 100;
            } elseif ($status === 'failed' || $status === 'cancelled') {
                $pct = max(0, min(99, $pct));
            } elseif ($stage === 'queued') {
                $pct = 0;
            } else {
                if ($fetched <= 0 && $normalized <= 0 && $doneRows <= 0) {
                    // Avoid showing "fake" progress before we actually fetch anything.
                    $pct = 0;
                } elseif ($expected > 0) {
                    $pct = (int) floor((max(0, $fetched) / max(1, $expected)) * 95);
                } else {
                    // Fallback: logarithmic growth based on fetched rows so operator sees "moving" progress.
                    $pct = (int) floor(min(95, 8 + (log10(max(1, $fetched)) * 18)));
                }
                // When ingestion stats are moving, bump a bit so it feels responsive.
                if ($normalized > 0 && $doneRows > 0) {
                    $pct = min(99, max($pct, 50));
                }
            }

            // For UI display, always show percent out of 100 (not row totals).
            $totalUsers = 100;
            $processedUsers = $pct;
        } elseif ((string) $row->status === 'done') {
            $pct = 100;
        }

        return response()->json([
            'data' => array_merge([
                'id' => (int) $row->id,
                'request_no' => (string) $row->request_no,
                'job_type' => $jobType,
                'label' => $jobType === 'sync_public_api' ? 'Sync API' : 'Upload Log',
                'status' => (string) $row->status,
                'stage' => (string) ($filters['stage'] ?? ''),
                'message' => (string) ($filters['message'] ?? ''),
                'total_users' => $totalUsers,
                'processed_users' => $processedUsers,
                'progress_percent' => max(0, min(100, $pct)),
                'error_message' => $row->error_message,
                'fetched' => (int) ($filters['fetched'] ?? 0),
                'page' => (int) ($filters['page'] ?? 0),
                'expected_total' => (int) ($filters['expected_total'] ?? 0),
                'normalized' => (int) ($filters['normalized'] ?? 0),
                'inserted' => (int) ($filters['inserted'] ?? 0),
                'duplicates' => (int) ($filters['duplicates'] ?? 0),
                'failed' => (int) ($filters['failed'] ?? 0),
                'unmapped_inserted' => (int) ($filters['unmapped_inserted'] ?? 0),
                'errors' => array_slice((array) ($filters['errors'] ?? []), 0, 10),
                'detect_job_id' => (int) ($filters['detect_job_id'] ?? 0),
                'detect_message' => (string) ($filters['detect_message'] ?? ''),
                'started_at' => optional($row->started_at)->format('Y-m-d H:i:s'),
                'finished_at' => optional($row->finished_at)->format('Y-m-d H:i:s'),
                'updated_at' => optional($row->updated_at)->format('Y-m-d H:i:s'),
            ], $this->buildAttendanceJobRuntimeMeta($row)),
        ]);
    }

    // =========================================================================
    // rebuildStatus() - Cek status rebuild planning
    // Dipanggil dari: GET /attendance-review/rebuild/{id}/status
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function rebuildStatus(string $id): JsonResponse
    {
        $row = AttendanceExportJobModel::query()->findOrFail((int) $id);
        $filters = (array) ($row->filters ?? []);
        if (($filters['job_type'] ?? '') !== 'rebuild_planning') {
            return response()->json(['message' => 'Job bukan tipe rebuild planning.'], 422);
        }

        $totalUsers = (int) ($row->total_users ?? 0);
        $processedUsers = (int) ($row->processed_users ?? 0);
        $pct = $totalUsers > 0 ? (int) floor(($processedUsers / max(1, $totalUsers)) * 100) : 0;

        return response()->json([
            'data' => array_merge([
                'id' => (int) $row->id,
                'request_no' => (string) $row->request_no,
                'status' => (string) $row->status,
                'total_users' => $totalUsers,
                'processed_users' => $processedUsers,
                'progress_percent' => $pct,
                'error_message' => $row->error_message,
                'updated' => (int) ($filters['updated'] ?? 0),
                'skipped' => (int) ($filters['skipped'] ?? 0),
                'reset_approval' => (int) ($filters['reset_approval'] ?? 0),
                'affected_rows' => (int) ($filters['affected_rows'] ?? 0),
                'date_from' => (string) ($filters['date_from'] ?? ''),
                'date_to' => (string) ($filters['date_to'] ?? ''),
                'started_at' => optional($row->started_at)->format('Y-m-d H:i:s'),
                'finished_at' => optional($row->finished_at)->format('Y-m-d H:i:s'),
                'updated_at' => optional($row->updated_at)->format('Y-m-d H:i:s'),
            ], $this->buildAttendanceJobRuntimeMeta($row)),
        ]);
    }

    // =========================================================================
    // detectionStatus() - Cek status deteksi attendance
    // Dipanggil dari: GET /attendance-review/detect/{id}/status
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function detectionStatus(string $id): JsonResponse
    {
        $row = AttendanceExportJobModel::query()->findOrFail((int) $id);
        $filters = (array) ($row->filters ?? []);
        if (($filters['job_type'] ?? '') !== 'detect') {
            return response()->json(['message' => 'Job bukan tipe detection.'], 422);
        }

        $totalUsers = (int) ($row->total_users ?? 0);
        $processedUsers = (int) ($row->processed_users ?? 0);
        $pct = $totalUsers > 0 ? (int) floor(($processedUsers / max(1, $totalUsers)) * 100) : 0;

        return response()->json([
            'data' => array_merge([
                'id' => (int) $row->id,
                'request_no' => (string) $row->request_no,
                'status' => (string) $row->status,
                'total_users' => $totalUsers,
                'processed_users' => $processedUsers,
                'progress_percent' => $pct,
                'error_message' => $row->error_message,
                'affected_rows' => (int) ($filters['affected_rows'] ?? 0),
                'started_at' => optional($row->started_at)->format('Y-m-d H:i:s'),
                'finished_at' => optional($row->finished_at)->format('Y-m-d H:i:s'),
                'updated_at' => optional($row->updated_at)->format('Y-m-d H:i:s'),
            ], $this->buildAttendanceJobRuntimeMeta($row)),
        ]);
    }

    // =========================================================================
    // cancelDetection() - Batalkan proses deteksi
    // Dipanggil dari: POST /attendance-review/detect/{id}/cancel
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function cancelDetection(string $id): JsonResponse
    {
        $row = AttendanceExportJobModel::query()->findOrFail((int) $id);
        $filters = (array) ($row->filters ?? []);
        if (($filters['job_type'] ?? '') !== 'detect') {
            return response()->json(['message' => 'Job bukan tipe detection.'], 422);
        }
        if (in_array((string) $row->status, ['done', 'failed', 'cancelled'], true)) {
            return response()->json(['message' => 'Job sudah selesai/tidak bisa dibatalkan.'], 422);
        }

        $row->status = 'cancelled';
        $row->error_message = 'Dibatalkan oleh user.';
        $row->finished_at = now();
        $row->save();

        return response()->json(['message' => 'Permintaan stop sudah dikirim. Job akan berhenti di checkpoint terdekat.']);
    }

    // =========================================================================
    // pauseDetection() - Pause proses deteksi
    // Dipanggil dari: POST /attendance-review/detect/{id}/pause
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function pauseDetection(string $id): JsonResponse
    {
        $row = AttendanceExportJobModel::query()->findOrFail((int) $id);
        $filters = (array) ($row->filters ?? []);
        if (($filters['job_type'] ?? '') !== 'detect') {
            return response()->json(['message' => 'Job bukan tipe detection.'], 422);
        }
        if (! in_array((string) $row->status, ['pending', 'processing'], true)) {
            return response()->json(['message' => 'Job tidak bisa dipause pada status saat ini.'], 422);
        }

        $row->status = 'paused';
        $row->error_message = 'Dipause oleh user.';
        $row->save();

        return response()->json([
            'message' => 'Job dipause. Klik Resume untuk lanjut dari progres terakhir.',
            'data' => [
                'id' => (int) $row->id,
                'status' => (string) $row->status,
                'processed_users' => (int) ($row->processed_users ?? 0),
                'total_users' => (int) ($row->total_users ?? 0),
            ],
        ]);
    }

    // =========================================================================
    // resumeDetection() - Resume proses deteksi
    // Dipanggil dari: POST /attendance-review/detect/{id}/resume
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function resumeDetection(string $id): JsonResponse
    {
        $row = AttendanceExportJobModel::query()->findOrFail((int) $id);
        $filters = (array) ($row->filters ?? []);
        if (($filters['job_type'] ?? '') !== 'detect') {
            return response()->json(['message' => 'Job bukan tipe detection.'], 422);
        }
        if ((string) $row->status !== 'paused') {
            return response()->json(['message' => 'Job bukan status paused.'], 422);
        }

        $profil = ProfilBulanModel::query()->find((int) $row->profil_bulan_id);
        if ($profil) {
            $periodStart = Carbon::parse($profil->start_date)->startOfDay();
            $periodEnd = Carbon::parse($profil->end_date)->startOfDay();
            $blockingJob = $this->findOverlappingAttendanceMutationJob(
                (int) $row->profil_bulan_id,
                ! empty($filters['karyawan_id']) ? (int) $filters['karyawan_id'] : null,
                $periodStart,
                $periodEnd,
                ['detect', 'rebuild_planning'],
                (int) $row->id
            );
            if ($blockingJob) {
                return response()->json([
                    'message' => 'Job tidak bisa dilanjutkan karena ada job Attendance Review lain yang masih aktif pada scope yang sama.',
                    'data' => $this->attendanceMutationJobPayload($blockingJob),
                ], 422);
            }
        }

        $row->status = 'pending';
        $row->error_message = null;
        $row->finished_at = null;
        $row->save();

        RunAttendanceDetectionJob::dispatch((int) $row->id)->onQueue(self::QUEUE_NAME);

        return response()->json([
            'message' => 'Job dilanjutkan dari checkpoint terakhir.',
            'data' => [
                'id' => (int) $row->id,
                'status' => (string) $row->status,
                'processed_users' => (int) ($row->processed_users ?? 0),
                'total_users' => (int) ($row->total_users ?? 0),
            ],
        ]);
    }

    // =========================================================================
    // attendanceMutationJobPayload() - Helper terkait attendance
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function attendanceMutationJobPayload(AttendanceExportJobModel $job): array
    {
        $filters = (array) ($job->filters ?? []);
        $profil = ProfilBulanModel::query()->find((int) $job->profil_bulan_id);
        $scope = $profil ? $this->attendanceMutationJobScope($job, $profil) : null;
        $totalUsers = (int) ($job->total_users ?? 0);
        $processedUsers = (int) ($job->processed_users ?? 0);
        $pct = $totalUsers > 0 ? (int) floor(($processedUsers / max(1, $totalUsers)) * 100) : 0;
        $runtimeMeta = $this->buildAttendanceJobRuntimeMeta($job);

        return [
            'id' => (int) $job->id,
            'job_id' => (int) $job->id,
            'request_no' => (string) $job->request_no,
            'status' => (string) $job->status,
            'profil_bulan_id' => (int) $job->profil_bulan_id,
            'karyawan_id' => $scope ? $scope['karyawan_id'] : (! empty($filters['karyawan_id']) ? (int) $filters['karyawan_id'] : null),
            'date_from' => $scope ? $scope['date_from']->toDateString() : (string) ($filters['date_from'] ?? ''),
            'date_to' => $scope ? $scope['date_to']->toDateString() : (string) ($filters['date_to'] ?? ''),
            'total_users' => $totalUsers,
            'processed_users' => $processedUsers,
            'progress_percent' => $pct,
            'error_message' => $job->error_message,
            'job_type' => (string) ($filters['job_type'] ?? ''),
            'started_at' => optional($job->started_at)->format('Y-m-d H:i:s'),
            'finished_at' => optional($job->finished_at)->format('Y-m-d H:i:s'),
            'updated_at' => optional($job->updated_at)->format('Y-m-d H:i:s'),
            'status_hint' => (string) ($runtimeMeta['status_hint'] ?? ''),
            'age_seconds' => (int) ($runtimeMeta['age_seconds'] ?? 0),
            'updated_age_seconds' => (int) ($runtimeMeta['updated_age_seconds'] ?? 0),
            'is_stale' => (bool) ($runtimeMeta['is_stale'] ?? false),
            'open_jobs_ahead' => (int) ($runtimeMeta['open_jobs_ahead'] ?? 0),
            'other_processing_jobs' => (int) ($runtimeMeta['other_processing_jobs'] ?? 0),
            'queue_open_by_type' => (array) ($runtimeMeta['queue_open_by_type'] ?? []),
        ];
    }

    /**
     * @param  array<int, string>  $jobTypes
     */
    // =========================================================================
    // findOverlappingAttendanceMutationJob() - Mencari data tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function findOverlappingAttendanceMutationJob(
        int $profilId,
        ?int $karyawanId,
        ?Carbon $dateFrom,
        ?Carbon $dateTo,
        array $jobTypes,
        ?int $ignoreJobId = null
    ): ?AttendanceExportJobModel {
        $profil = ProfilBulanModel::query()->find($profilId);
        if (! $profil) {
            return null;
        }

        $newFrom = $dateFrom ? $dateFrom->copy()->startOfDay() : Carbon::parse($profil->start_date)->startOfDay();
        $newTo = $dateTo ? $dateTo->copy()->startOfDay() : Carbon::parse($profil->end_date)->startOfDay();

        return AttendanceExportJobModel::query()
            ->where('profil_bulan_id', $profilId)
            ->whereIn('status', ['pending', 'processing', 'paused'])
            ->when($ignoreJobId, fn ($q) => $q->where('id', '!=', $ignoreJobId))
            ->orderBy('id')
            ->get()
            ->first(function (AttendanceExportJobModel $job) use ($jobTypes, $karyawanId, $newFrom, $newTo, $profil): bool {
                $scope = $this->attendanceMutationJobScope($job, $profil);
                if (! in_array($scope['job_type'], $jobTypes, true)) {
                    return false;
                }

                $existingEmployee = $scope['karyawan_id'];
                $employeeOverlaps = $existingEmployee === null || $karyawanId === null || (int) $existingEmployee === (int) $karyawanId;
                if (! $employeeOverlaps) {
                    return false;
                }

                return $scope['date_from']->lte($newTo) && $newFrom->lte($scope['date_to']);
            });
    }

    // =========================================================================
    // claimAttendanceMutationJob() - Mengklaim/mengambil alih data/job
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function claimAttendanceMutationJob(
        int $jobId,
        int $profilId,
        ?int $karyawanId,
        Carbon $dateFrom,
        Carbon $dateTo
    ): bool {
        $blockingJob = $this->findOverlappingAttendanceMutationJob(
            $profilId,
            $karyawanId,
            $dateFrom,
            $dateTo,
            ['detect', 'rebuild_planning'],
            $jobId
        );

        if (! $blockingJob) {
            return true;
        }

        if ((string) $blockingJob->status !== 'processing' && (int) $blockingJob->id > $jobId) {
            return true;
        }

        AttendanceExportJobModel::query()
            ->whereKey($jobId)
            ->update([
                'status' => 'cancelled',
                'error_message' => 'Dibatalkan karena ada job Attendance Review lain yang lebih dulu aktif pada scope yang sama.',
                'finished_at' => now(),
                'updated_at' => now(),
            ]);

        return false;
    }

    /**
     * @return array{job_type:string,karyawan_id:int|null,date_from:Carbon,date_to:Carbon}
     */
    // =========================================================================
    // attendanceMutationJobScope() - Helper terkait attendance
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function attendanceMutationJobScope(AttendanceExportJobModel $job, ProfilBulanModel $profil): array
    {
        $filters = (array) ($job->filters ?? []);
        $jobType = (string) ($filters['job_type'] ?? '');
        $periodStart = Carbon::parse($profil->start_date)->startOfDay();
        $periodEnd = Carbon::parse($profil->end_date)->startOfDay();

        $dateFrom = ! empty($filters['date_from'])
            ? Carbon::parse((string) $filters['date_from'])->startOfDay()
            : $periodStart;
        $dateTo = ! empty($filters['date_to'])
            ? Carbon::parse((string) $filters['date_to'])->startOfDay()
            : $periodEnd;

        if ($dateFrom->lt($periodStart)) {
            $dateFrom = $periodStart;
        }
        if ($dateTo->gt($periodEnd)) {
            $dateTo = $periodEnd;
        }

        return [
            'job_type' => $jobType,
            'karyawan_id' => ! empty($filters['karyawan_id']) ? (int) $filters['karyawan_id'] : null,
            'date_from' => $dateFrom,
            'date_to' => $dateTo,
        ];
    }

    // =========================================================================
    // suggestShiftProfile() - Saran shift profile berdasarkan data
    // Dipanggil dari: GET /attendance-review/detect/suggest-shift
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function suggestShiftProfile(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['required', 'integer', 'exists:master_karyawans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profil = ProfilBulanModel::query()->findOrFail((int) $request->input('profil_bulan_id'));
        $karyawanId = (int) $request->input('karyawan_id');
        $periodStart = Carbon::parse((string) $profil->start_date)->startOfDay();
        $periodEnd = Carbon::parse((string) $profil->end_date)->startOfDay();
        $filterStart = $request->filled('date_from') ? Carbon::parse((string) $request->input('date_from'))->startOfDay() : null;
        $filterEnd = $request->filled('date_to') ? Carbon::parse((string) $request->input('date_to'))->startOfDay() : null;
        $effectiveStart = $filterStart && $filterStart->gt($periodStart) ? $filterStart : $periodStart->copy();
        $effectiveEnd = $filterEnd && $filterEnd->lt($periodEnd) ? $filterEnd : $periodEnd->copy();
        if ($effectiveStart->gt($effectiveEnd)) {
            return response()->json(['message' => 'Range tanggal tidak valid.'], 422);
        }

        $assignment = ProfilBulanKaryawanModel::query()
            ->with(['karyawan:id,employee_code,full_name', 'profilJamKerja:id,code,name,start_time,end_time', 'profilJamKerjaAlt:id,code,name,start_time,end_time'])
            ->where('profil_bulan_id', (int) $profil->id)
            ->where('karyawan_id', $karyawanId)
            ->where('is_active', true)
            ->first();

        $karyawan = $assignment?->karyawan ?: KaryawanModel::query()->find($karyawanId, ['id', 'employee_code', 'full_name']);
        if (! $karyawan) {
            return response()->json(['message' => 'Data karyawan tidak ditemukan.'], 422);
        }

        $fallbackPlannedShiftId = AttendanceDailyReviewModel::query()
            ->where('profil_bulan_id', (int) $profil->id)
            ->where('karyawan_id', $karyawanId)
            ->whereNotNull('planned_profil_jam_kerja_id')
            ->orderByDesc('work_date')
            ->value('planned_profil_jam_kerja_id');
        $currentShift = $assignment?->profilJamKerja;
        if (! $currentShift && ! empty($fallbackPlannedShiftId)) {
            $currentShift = ProfilJamKerjaModel::query()->find((int) $fallbackPlannedShiftId, ['id', 'code', 'name', 'start_time', 'end_time']);
        }
        if (! $currentShift) {
            return response()->json(['message' => 'Profil jam kerja karyawan belum terpasang. Set profil dulu atau jalankan rebuild planning.'], 422);
        }

        $customScheduleRows = DB::table('master_shift_schedules')
            ->where('karyawan_id', $karyawanId)
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->where('is_active', true)
            ->where(function ($q) use ($profil): void {
                $q->whereNull('profil_bulan_id')
                    ->orWhere('profil_bulan_id', (int) $profil->id);
            })
            ->orderByRaw(
                'CASE
                    WHEN profil_bulan_id = ? AND is_locked = 1 THEN 1
                    WHEN profil_bulan_id = ? AND is_locked = 0 THEN 2
                    WHEN profil_bulan_id IS NULL AND is_locked = 1 THEN 3
                    ELSE 4
                END ASC',
                [(int) $profil->id, (int) $profil->id]
            )
            ->orderByDesc('id')
            ->get(['work_date', 'profil_jam_kerja_id']);
        $customScheduleMap = [];
        $customScheduleEmployeeIds = [];
        $customShiftIds = [];
        foreach ($customScheduleRows as $row) {
            $dateKey = Carbon::parse((string) $row->work_date)->format('Y-m-d');
            if (isset($customScheduleMap[$dateKey])) {
                continue;
            }
            $shiftId = (int) ($row->profil_jam_kerja_id ?? 0);
            if ($shiftId <= 0) {
                continue;
            }
            $customScheduleMap[$dateKey] = $shiftId;
            $customShiftIds[$shiftId] = $shiftId;
        }
        $customShiftMap = collect();
        if (! empty($customShiftIds)) {
            $customShiftMap = ProfilJamKerjaModel::query()
                ->whereIn('id', array_values($customShiftIds))
                ->get(['id', 'code', 'name', 'start_time', 'end_time'])
                ->keyBy('id');
        }

        $rawLogs = AttendanceLogModel::query()
            ->where('karyawan_id', $karyawanId)
            ->where('log_at', '>=', $effectiveStart->copy()->subDay()->startOfDay())
            ->where('log_at', '<=', $effectiveEnd->copy()->addDay()->endOfDay())
            ->orderBy('log_at')
            ->get(['log_at']);

        $sampleRows = [];
        $actualMinutes = [];
        for ($cursor = $effectiveStart->copy(); $cursor->lte($effectiveEnd); $cursor->addDay()) {
            $workDate = $cursor->copy();
            $dateKey = $workDate->format('Y-m-d');
            $customShiftId = (int) ($customScheduleMap[$dateKey] ?? 0);
            if ($customShiftId > 0 && $customShiftMap->has($customShiftId)) {
                $selectedShift = ['shift' => $customShiftMap->get($customShiftId)];
            } else {
                $selectedShift = $assignment
                    ? $this->resolveAssignedShiftForDate($assignment, $workDate)
                    : ['shift' => $currentShift];
            }
            if (! $selectedShift || empty($selectedShift['shift'])) {
                continue;
            }

            $shift = $selectedShift['shift'];
            $shiftStart = Carbon::parse($dateKey.' '.substr((string) $shift->start_time, 0, 8));
            $windowStart = $shiftStart->copy()->subHours(6);
            $windowEnd = $shiftStart->copy()->addHours(4);
            $firstIn = $rawLogs
                ->first(fn ($log) => $log->log_at && $log->log_at->between($windowStart, $windowEnd));
            if (! $firstIn || ! $firstIn->log_at) {
                continue;
            }
            $actualAt = Carbon::parse((string) $firstIn->log_at);
            $actualMinute = ((int) $actualAt->hour * 60) + (int) $actualAt->minute;

            $sampleRows[] = [
                'work_date' => $dateKey,
                'actual_checkin' => $actualAt->format('H:i'),
                'planned_start' => substr((string) $shift->start_time, 0, 5),
            ];
            $actualMinutes[] = $actualMinute;
        }

        $sampleDays = count($actualMinutes);
        $minSampleDays = 3;
        $insufficientSample = $sampleDays < $minSampleDays;
        $avgActualMinute = $sampleDays > 0
            ? (int) round(array_sum($actualMinutes) / $sampleDays)
            : $this->timeToMinute((string) $currentShift->start_time);

        $activeShifts = ProfilJamKerjaModel::query()
            ->where('is_active', true)
            ->orderBy('start_time')
            ->get(['id', 'code', 'name', 'start_time', 'end_time']);
        $currentStartMinute = $this->timeToMinute((string) $currentShift->start_time);
        $currentDiff = $this->minuteDistance($currentStartMinute, $avgActualMinute);

        $best = null;
        $candidates = [];
        foreach ($activeShifts as $shift) {
            $startMinute = $this->timeToMinute((string) $shift->start_time);
            $diff = $this->minuteDistance($startMinute, $avgActualMinute);
            $candidates[] = [
                'id' => (int) $shift->id,
                'code' => (string) $shift->code,
                'name' => (string) $shift->name,
                'start_time' => substr((string) $shift->start_time, 0, 5),
                'end_time' => substr((string) $shift->end_time, 0, 5),
                'diff_minutes' => $diff,
            ];
            if (! $best || $diff < (int) $best['diff_minutes']) {
                $best = [
                    'id' => (int) $shift->id,
                    'code' => (string) $shift->code,
                    'name' => (string) $shift->name,
                    'start_time' => substr((string) $shift->start_time, 0, 5),
                    'end_time' => substr((string) $shift->end_time, 0, 5),
                    'diff_minutes' => $diff,
                ];
            }
        }

        if (! $best) {
            return response()->json(['message' => 'Profil jam kerja aktif tidak ditemukan.'], 422);
        }

        usort($candidates, function (array $a, array $b): int {
            return (int) ($a['diff_minutes'] ?? 9999) <=> (int) ($b['diff_minutes'] ?? 9999);
        });
        $candidateTop = $candidates;
        $currentExistsInTop = collect($candidateTop)->contains(fn ($row) => (int) ($row['id'] ?? 0) === (int) $currentShift->id);
        if (! $currentExistsInTop) {
            $candidateTop[] = [
                'id' => (int) $currentShift->id,
                'code' => (string) $currentShift->code,
                'name' => (string) $currentShift->name,
                'start_time' => substr((string) $currentShift->start_time, 0, 5),
                'end_time' => substr((string) $currentShift->end_time, 0, 5),
                'diff_minutes' => $currentDiff,
            ];
        }

        $shouldSuggestChange = ! $insufficientSample
            && ((int) $best['id'] !== (int) $currentShift->id)
            && ($currentDiff >= 45)
            && ((int) $best['diff_minutes'] <= 30);
        $summaryReason = $insufficientSample
            ? "Data sampel belum cukup untuk suggest otomatis (minimal {$minSampleDays} hari ada log masuk). Anda tetap bisa pilih profil secara manual."
            : ($shouldSuggestChange
                ? 'Disarankan ganti profil jam kerja agar lebih dekat ke rata-rata jam masuk aktual.'
                : 'Profil saat ini masih dianggap sesuai (selisih masih wajar).');

        return response()->json([
            'data' => [
                'profil_bulan_id' => (int) $profil->id,
                'karyawan_id' => $karyawanId,
                'employee_code' => (string) ($karyawan->employee_code ?? ''),
                'employee_name' => (string) ($karyawan->full_name ?? ''),
                'sample_days' => $sampleDays,
                'min_sample_days' => $minSampleDays,
                'insufficient_sample' => $insufficientSample,
                'avg_checkin_time' => sprintf('%02d:%02d', intdiv($avgActualMinute, 60), $avgActualMinute % 60),
                'current_shift' => [
                    'id' => (int) $currentShift->id,
                    'code' => (string) $currentShift->code,
                    'name' => (string) $currentShift->name,
                    'start_time' => substr((string) $currentShift->start_time, 0, 5),
                    'end_time' => substr((string) $currentShift->end_time, 0, 5),
                    'diff_minutes' => $currentDiff,
                ],
                'suggested_shift' => $best,
                'candidates' => array_values($candidateTop),
                'candidate_total' => count($candidateTop),
                'suggest_change' => $shouldSuggestChange,
                'reason' => $summaryReason,
                'samples' => array_slice($sampleRows, 0, 10),
            ],
        ]);
    }

    // =========================================================================
    // applySuggestedShiftProfile() - Terapkan saran shift profile
    // Dipanggil dari: POST /attendance-review/detect/suggest-shift/apply
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function applySuggestedShiftProfile(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['required', 'integer', 'exists:master_karyawans,id'],
            'suggested_profil_jam_kerja_id' => ['required', 'integer', 'exists:master_profil_jam_kerjas,id'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profilId = (int) $request->input('profil_bulan_id');
        $karyawanId = (int) $request->input('karyawan_id');
        $suggestedShiftId = (int) $request->input('suggested_profil_jam_kerja_id');
        if ($guard = $this->guardProfilBulanOpenForAttendance(ProfilBulanModel::query()->find($profilId))) {
            return $guard;
        }

        $assignment = ProfilBulanKaryawanModel::query()
            ->where('profil_bulan_id', $profilId)
            ->where('karyawan_id', $karyawanId)
            ->where('is_active', true)
            ->first();

        $shift = ProfilJamKerjaModel::query()->findOrFail($suggestedShiftId);
        $oldShiftId = $assignment ? (int) ($assignment->profil_jam_kerja_id ?? 0) : 0;
        if ($oldShiftId === $suggestedShiftId) {
            return response()->json(['message' => 'Profil jam kerja karyawan sudah sama dengan suggestion.']);
        }

        if (! $assignment) {
            $assignment = new ProfilBulanKaryawanModel;
            $assignment->profil_bulan_id = $profilId;
            $assignment->karyawan_id = $karyawanId;
            $assignment->is_active = true;
        }

        $note = trim((string) ($assignment->notes ?? ''));
        $stamp = now()->format('Y-m-d H:i');
        $suffix = "[{$stamp}] Updated from Attendance Review Suggestion.";
        $assignment->profil_jam_kerja_id = $suggestedShiftId;
        $assignment->notes = trim($note."\n".$suffix);
        $assignment->save();

        return response()->json([
            'message' => 'Profil jam kerja karyawan berhasil diperbarui dari suggestion.',
            'data' => [
                'profil_bulan_id' => $profilId,
                'karyawan_id' => $karyawanId,
                'old_profil_jam_kerja_id' => $oldShiftId,
                'new_profil_jam_kerja_id' => $suggestedShiftId,
                'new_profil_jam_kerja' => [
                    'code' => (string) $shift->code,
                    'name' => (string) $shift->name,
                    'start_time' => substr((string) $shift->start_time, 0, 5),
                    'end_time' => substr((string) $shift->end_time, 0, 5),
                ],
            ],
        ]);
    }

    // =========================================================================
    // queueHealth() - Cek kesehatan queue job
    // Dipanggil dari: GET /attendance-review/queue/health
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function queueHealth(Request $request): JsonResponse
    {
        $queueName = trim((string) $request->input('queue', self::QUEUE_NAME)) ?: self::QUEUE_NAME;
        $nowTs = now()->timestamp;

        $pendingCount = (int) DB::table('jobs')
            ->where('queue', $queueName)
            ->whereNull('reserved_at')
            ->where('available_at', '<=', $nowTs)
            ->count();
        $delayedCount = (int) DB::table('jobs')
            ->where('queue', $queueName)
            ->whereNull('reserved_at')
            ->where('available_at', '>', $nowTs)
            ->count();
        $reservedCount = (int) DB::table('jobs')
            ->where('queue', $queueName)
            ->whereNotNull('reserved_at')
            ->count();

        $oldestPendingTs = DB::table('jobs')
            ->where('queue', $queueName)
            ->whereNull('reserved_at')
            ->where('available_at', '<=', $nowTs)
            ->min('created_at');
        $oldestPendingAgeSec = $oldestPendingTs ? max(0, $nowTs - (int) $oldestPendingTs) : 0;

        $likelyWorkerOffline = $pendingCount > 0 && $reservedCount === 0 && $oldestPendingAgeSec >= 120;
        $status = 'idle';
        if ($reservedCount > 0) {
            $status = 'busy';
        } elseif ($likelyWorkerOffline) {
            $status = 'stalled';
        } elseif ($pendingCount > 0) {
            $status = 'queued';
        }

        $openByType = $this->summarizeOpenAttendanceJobs();
        $detectPending = (int) ($openByType['detect'] ?? 0);

        return response()->json([
            'data' => [
                'queue' => $queueName,
                'status' => $status,
                'likely_worker_offline' => $likelyWorkerOffline,
                'pending' => $pendingCount,
                'delayed' => $delayedCount,
                'reserved' => $reservedCount,
                'oldest_pending_age_sec' => $oldestPendingAgeSec,
                'detect_jobs_open' => (int) $detectPending,
                'open_by_type' => $openByType,
            ],
        ]);
    }

    // =========================================================================
    // queueProcessOnce() - Proses satu job dari queue
    // Dipanggil dari: POST /attendance-review/queue/process-once
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function queueProcessOnce(Request $request): JsonResponse
    {
        $queueName = trim((string) $request->input('queue', self::QUEUE_NAME)) ?: self::QUEUE_NAME;
        $healthBefore = $this->queueHealth(new Request(['queue' => $queueName]))->getData(true);
        $healthData = (array) ($healthBefore['data'] ?? []);

        if ((int) ($healthData['reserved'] ?? 0) > 0) {
            return response()->json([
                'message' => 'Queue sudah sedang diproses worker lain.',
                'health' => $healthData,
            ]);
        }

        if ((int) ($healthData['pending'] ?? 0) <= 0) {
            return response()->json([
                'message' => 'Tidak ada job pending di queue.',
                'health' => $healthData,
            ]);
        }

        $startedDetached = false;
        $output = '';

        try {
            $phpBinary = $this->phpCliBinary();
            $logFile = storage_path('logs/queue-attendance-review-once.log');
            $this->startDetachedProcess([
                $phpBinary,
                base_path('artisan'),
                'queue:work',
                '--queue='.$queueName,
                '--once',
                '--tries=1',
                '--timeout=7200',
            ], base_path(), $logFile);
            $startedDetached = true;
            usleep(350000);
        } catch (Throwable $e) {
            // Fallback ke mode sinkron jika proses background gagal dibuka.
            Artisan::call('queue:work', [
                '--queue' => $queueName,
                '--once' => true,
                '--tries' => 1,
                '--timeout' => 7200,
            ]);
            $output = Artisan::output();
        }

        $health = $this->queueHealth(new Request(['queue' => $queueName]))->getData(true);

        return response()->json([
            'message' => $startedDetached
                ? 'Worker queue dipicu di background. Status akan bergerak otomatis saat job mulai diambil.'
                : 'Process queue sekali jalan selesai.',
            'output' => (string) $output,
            'health' => $health['data'] ?? [],
        ]);
    }

    /**
     * @return array<int, int>
     */
    // =========================================================================
    // queuedAttendanceJobIds() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function queuedAttendanceJobIds(string $queueName = self::QUEUE_NAME): array
    {
        $orderedIds = [];

        DB::table('jobs')
            ->where('queue', $queueName)
            ->orderBy('id')
            ->get(['payload'])
            ->each(function (object $row) use (&$orderedIds): void {
                $jobId = $this->extractAttendanceQueueJobId((string) ($row->payload ?? ''));
                if ($jobId > 0 && ! in_array($jobId, $orderedIds, true)) {
                    $orderedIds[] = $jobId;
                }
            });

        return $orderedIds;
    }

    // =========================================================================
    // extractAttendanceQueueJobId() - Mengekstrak data dari sumber
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function extractAttendanceQueueJobId(string $payload): int
    {
        if ($payload === '') {
            return 0;
        }

        $decoded = json_decode($payload, true);
        $serializedCommand = (string) data_get($decoded, 'data.command', '');
        $haystack = $serializedCommand !== '' ? $serializedCommand : $payload;

        if (preg_match('/jobId";i:(\d+)/', $haystack, $matches) === 1) {
            return (int) ($matches[1] ?? 0);
        }

        return 0;
    }

    /**
     * @return array<string, int>
     */
    // =========================================================================
    // summarizeOpenAttendanceJobs() - Meringkas data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function summarizeOpenAttendanceJobs(string $queueName = self::QUEUE_NAME): array
    {
        $summary = [];
        $queuedIds = $this->queuedAttendanceJobIds($queueName);
        if (empty($queuedIds)) {
            return $summary;
        }

        AttendanceExportJobModel::query()
            ->whereIn('id', $queuedIds)
            ->orderBy('id')
            ->get(['id', 'filters'])
            ->each(function (AttendanceExportJobModel $job) use (&$summary): void {
                $filters = (array) ($job->filters ?? []);
                $type = trim((string) ($filters['job_type'] ?? 'unknown')) ?: 'unknown';
                $summary[$type] = (int) ($summary[$type] ?? 0) + 1;
            });

        ksort($summary);

        return $summary;
    }

    /**
     * @return array<string, mixed>
     */
    // =========================================================================
    // buildAttendanceJobRuntimeMeta() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildAttendanceJobRuntimeMeta(AttendanceExportJobModel $job): array
    {
        $now = now();
        $createdAt = $job->created_at ? Carbon::parse($job->created_at) : null;
        $updatedAt = $job->updated_at ? Carbon::parse($job->updated_at) : null;
        $ageSeconds = $createdAt ? max(0, $createdAt->diffInSeconds($now)) : 0;
        $updatedAgeSeconds = $updatedAt ? max(0, $updatedAt->diffInSeconds($now)) : 0;
        $status = (string) ($job->status ?? 'pending');
        $isStale = in_array($status, ['pending', 'processing'], true) && $updatedAgeSeconds >= 180;
        $queuedIds = $this->queuedAttendanceJobIds();
        $queuePosition = array_search((int) $job->id, $queuedIds, true);
        $isQueued = $queuePosition !== false;
        $openJobsAhead = $isQueued ? (int) $queuePosition : 0;
        $otherProcessingJobs = empty($queuedIds)
            ? 0
            : (int) AttendanceExportJobModel::query()
                ->whereIn('id', $queuedIds)
                ->where('id', '!=', (int) $job->id)
                ->where('status', 'processing')
                ->count();
        $openByType = $this->summarizeOpenAttendanceJobs();

        $statusHint = '';
        if ($status === 'pending') {
            if (! $isQueued) {
                $statusHint = 'Record job masih pending, tetapi tidak ditemukan lagi di tabel queue. Biasanya ini job lama/orphan dan tidak sedang diproses worker.';
            } elseif ($otherProcessingJobs > 0) {
                $statusHint = 'Masih menunggu job lain yang sedang diproses di queue attendance-review.';
            } elseif ($openJobsAhead > 0) {
                $statusHint = 'Masih antre di belakang '.$openJobsAhead.' job lain pada queue attendance-review.';
            } else {
                $statusHint = 'Job sudah dibuat dan sedang menunggu worker mengambil antrean.';
            }

            if ($updatedAgeSeconds >= 120) {
                $statusHint .= ' Belum ada update '.$updatedAgeSeconds.' detik, jadi aman cek worker/queue bila perlu.';
            }
        } elseif ($status === 'processing') {
            $statusHint = 'Job sedang diproses. Progress detection/rebuild diperbarui bertahap, umumnya per 10 karyawan.';
            if ($updatedAgeSeconds >= 120) {
                $statusHint .= ' Update terakhir '.$updatedAgeSeconds.' detik lalu, jadi cek worker/log jika terasa terlalu lama.';
            }
        } elseif ($status === 'paused') {
            $statusHint = 'Job sedang dipause dan bisa dilanjutkan lagi dari tombol Resume.';
        } elseif ($status === 'done') {
            $statusHint = 'Job selesai. Jika badge queue masih queued, biasanya itu job lain yang masih antre.';
        } elseif ($status === 'failed') {
            $statusHint = 'Job gagal. Lihat pesan error untuk detail penyebabnya.';
        } elseif ($status === 'cancelled') {
            $statusHint = 'Job dibatalkan sebelum seluruh batch selesai diproses.';
        }

        return [
            'status_hint' => $statusHint,
            'age_seconds' => $ageSeconds,
            'updated_age_seconds' => $updatedAgeSeconds,
            'is_stale' => $isStale,
            'is_queued' => $isQueued,
            'open_jobs_ahead' => $openJobsAhead,
            'other_processing_jobs' => $otherProcessingJobs,
            'queue_open_by_type' => $openByType,
        ];
    }

    // =========================================================================
    // phpCliBinary() - Helper terkait PHP binary/path
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function phpCliBinary(): string
    {
        $env = trim((string) env('PHP_CLI_PATH', ''));
        if ($env !== '' && File::exists($env)) {
            return $env;
        }

        try {
            if (PHP_OS_FAMILY === 'Windows') {
                $out = (new \Symfony\Component\Process\Process(['cmd', '/c', 'where php']))->setTimeout(3);
                $out->run();
                if ($out->isSuccessful()) {
                    $line = trim((string) strtok(trim($out->getOutput()), "\r\n"));
                    if ($line !== '' && File::exists($line)) {
                        return $line;
                    }
                }
            } else {
                $out = (new \Symfony\Component\Process\Process(['bash', '-lc', 'command -v php']))->setTimeout(3);
                $out->run();
                if ($out->isSuccessful()) {
                    $line = trim((string) strtok(trim($out->getOutput()), "\r\n"));
                    if ($line !== '' && File::exists($line)) {
                        return $line;
                    }
                }
            }
        } catch (Throwable $e) {
            // Ignore and fallback to plain "php".
        }

        return 'php';
    }

    /**
     * @param  array<int, string>  $command
     */
    // =========================================================================
    // startDetachedProcess() - Memulai proses tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function startDetachedProcess(array $command, string $workdir, string $logFile): void
    {
        $escaped = array_map(static fn (string $arg) => escapeshellarg($arg), $command);
        $cmdLine = implode(' ', $escaped);

        if (PHP_OS_FAMILY === 'Windows') {
            $log = str_replace('/', '\\', $logFile);
            $inner = $cmdLine.' > '.escapeshellarg($log).' 2>&1';
            $detached = 'start "" /B cmd /c '.escapeshellarg($inner);
            pclose(popen('cmd /c '.$detached, 'r'));

            return;
        }

        exec('cd '.escapeshellarg($workdir).' && nohup '.$cmdLine.' > '.escapeshellarg($logFile).' 2>&1 &');
    }

    // =========================================================================
    // processDetectionJob() - Proses job deteksi attendance
    // Dipanggil dari: Route/API endpoint
    // Output: Response (bervariasi)
    // =========================================================================
    public function processDetectionJob(int $profilId, ?int $roundingRuleId = null, ?int $karyawanId = null, ?int $jobId = null): array
    {
        @ini_set('max_execution_time', '0');
        @set_time_limit(0);

        $profil = ProfilBulanModel::query()->findOrFail($profilId);
        $rounding = $roundingRuleId ? PembulatanJamModel::query()->find($roundingRuleId) : null;
        $startDate = Carbon::parse($profil->start_date)->startOfDay();
        $endDate = Carbon::parse($profil->end_date)->startOfDay();

        if ($jobId && ! $this->claimAttendanceMutationJob((int) $jobId, $profilId, $karyawanId, $startDate, $endDate)) {
            return ['affected' => 0, 'cancelled' => true];
        }

        $assignments = ProfilBulanKaryawanModel::query()
            ->with('profilJamKerja:id,start_time,end_time')
            ->with('profilJamKerjaAlt:id,start_time,end_time')
            ->with('roundingRule')
            ->where('profil_bulan_id', (int) $profil->id)
            ->where('is_active', true)
            ->when($karyawanId, fn ($q) => $q->where('karyawan_id', $karyawanId))
            ->orderBy('karyawan_id')
            ->get();

        if ($assignments->isEmpty()) {
            return ['affected' => 0];
        }

        $affected = 0;
        $totalAssignments = (int) $assignments->count();
        $processedAssignments = 0;

        $job = null;
        if ($jobId) {
            $job = AttendanceExportJobModel::query()->find((int) $jobId);
            if ($job) {
                $job->refresh();
                if ((string) $job->status === 'cancelled') {
                    return ['affected' => 0, 'cancelled' => true];
                }
                if ((string) $job->status === 'paused') {
                    return ['affected' => 0, 'paused' => true];
                }
                $resumeOffset = min(max(0, (int) ($job->processed_users ?? 0)), $totalAssignments);
                if ($resumeOffset > 0) {
                    $assignments = $assignments->slice($resumeOffset)->values();
                    $processedAssignments = $resumeOffset;
                }
                $job->total_users = $totalAssignments;
                $job->processed_users = $processedAssignments;
                $job->save();
            }
        }

        foreach ($assignments->chunk(150) as $chunk) {
            if ($job) {
                $job->refresh();
                if ((string) $job->status === 'cancelled') {
                    return ['affected' => $affected, 'cancelled' => true];
                }
                if ((string) $job->status === 'paused') {
                    return ['affected' => $affected, 'paused' => true];
                }
            }

            $chunkEmployeeIds = $chunk->pluck('karyawan_id')->filter()->map(fn ($v) => (int) $v)->unique()->values();
            if ($chunkEmployeeIds->isEmpty()) {
                continue;
            }

            $existingReviews = AttendanceDailyReviewModel::query()
                ->where('profil_bulan_id', (int) $profil->id)
                ->whereIn('karyawan_id', $chunkEmployeeIds->all())
                ->whereDate('work_date', '>=', $startDate->format('Y-m-d'))
                ->whereDate('work_date', '<=', $endDate->format('Y-m-d'))
                ->get()
                ->keyBy(function (AttendanceDailyReviewModel $row): string {
                    $dateKey = $row->work_date instanceof Carbon
                        ? $row->work_date->format('Y-m-d')
                        : Carbon::parse((string) $row->work_date)->format('Y-m-d');

                    return ((int) $row->karyawan_id).'|'.$dateKey;
                });
            $manualTimeSnapshotByReviewId = [];
            $existingReviewIds = $existingReviews->pluck('id')->filter()->map(fn ($id) => (int) $id)->values();
            if ($existingReviewIds->isNotEmpty()) {
                DB::table('attendance_daily_review_histories')
                    ->whereIn('attendance_daily_review_id', $existingReviewIds)
                    ->where('action', 'manual_time_set')
                    ->orderByDesc('id')
                    ->get(['attendance_daily_review_id', 'after_data'])
                    ->each(function ($history) use (&$manualTimeSnapshotByReviewId): void {
                        $reviewId = (int) $history->attendance_daily_review_id;
                        if ($reviewId <= 0 || isset($manualTimeSnapshotByReviewId[$reviewId])) {
                            return;
                        }
                        $after = $history->after_data ?? [];
                        if (is_string($after)) {
                            $decoded = json_decode($after, true);
                            $after = is_array($decoded) ? $decoded : [];
                        }
                        if (! is_array($after)) {
                            $after = [];
                        }
                        if (! empty($after['checkin_at']) || ! empty($after['checkout_at'])) {
                            $manualTimeSnapshotByReviewId[$reviewId] = $after;
                        }
                    });
            }

            $logs = AttendanceLogModel::query()
                ->whereIn('karyawan_id', $chunkEmployeeIds)
                ->where('log_at', '>=', $startDate->copy()->subDay()->startOfDay())
                ->where('log_at', '<=', $endDate->copy()->addDay()->endOfDay())
                ->orderBy('log_at')
                ->get()
                ->groupBy(fn ($row) => (int) $row->karyawan_id);
            $approvedOvertimeMap = $this->buildOvertimeApprovedMap($chunkEmployeeIds, $startDate->copy(), $endDate->copy());
            $continuesNextDayMap = $this->buildContinuesNextDayBridgeMap($chunkEmployeeIds, $startDate->copy(), $endDate->copy());

            $customScheduleRows = DB::table('master_shift_schedules')
                ->whereIn('karyawan_id', $chunkEmployeeIds)
                ->whereDate('work_date', '>=', $startDate->format('Y-m-d'))
                ->whereDate('work_date', '<=', $endDate->format('Y-m-d'))
                ->where('is_active', true)
                ->where(function ($q) use ($profil): void {
                    $q->whereNull('profil_bulan_id')
                        ->orWhere('profil_bulan_id', (int) $profil->id);
                })
                ->orderByRaw(
                    'CASE
                        WHEN profil_bulan_id = ? AND is_locked = 1 THEN 1
                        WHEN profil_bulan_id = ? AND is_locked = 0 THEN 2
                        WHEN profil_bulan_id IS NULL AND is_locked = 1 THEN 3
                        ELSE 4
                    END ASC',
                    [(int) $profil->id, (int) $profil->id]
                )
                ->orderByDesc('id')
                ->get(['karyawan_id', 'work_date', 'profil_jam_kerja_id', 'profil_bulan_id', 'is_locked']);
            $customScheduleMap = [];
            $customShiftIds = [];
            foreach ($customScheduleRows as $row) {
                $dateKey = Carbon::parse((string) $row->work_date)->format('Y-m-d');
                $mapKey = ((int) $row->karyawan_id).'|'.$dateKey;
                if (isset($customScheduleMap[$mapKey])) {
                    continue;
                }
                $shiftId = (int) ($row->profil_jam_kerja_id ?? 0);
                if ($shiftId <= 0) {
                    continue;
                }
                $customScheduleMap[$mapKey] = $shiftId;
                $customShiftIds[$shiftId] = $shiftId;
            }
            $customShiftMap = collect();
            if (count($customShiftIds) > 0) {
                $customShiftMap = ProfilJamKerjaModel::query()
                    ->whereIn('id', array_values($customShiftIds))
                    ->get(['id', 'start_time', 'end_time'])
                    ->keyBy('id');
            }

            foreach ($chunk as $assignment) {
                if (! $assignment->profilJamKerja) {
                    $processedAssignments++;

                    continue;
                }

                $karyawanLogs = $logs->get((int) $assignment->karyawan_id, collect());
                $consumedLogAtKeys = [];

                for ($cursor = $startDate->copy(); $cursor->lte($endDate); $cursor->addDay()) {
                    $workDate = $cursor->copy();
                    $mapKey = ((int) $assignment->karyawan_id).'|'.$workDate->format('Y-m-d');
                    $customShiftId = isset($customScheduleMap[$mapKey]) ? (int) $customScheduleMap[$mapKey] : 0;
                    $selectedShift = null;
                    if ($customShiftId > 0 && $customShiftMap->has($customShiftId)) {
                        $selectedShift = [
                            'shift' => $customShiftMap->get($customShiftId),
                            'shift_id' => $customShiftId,
                        ];
                    } else {
                        $selectedShift = $this->resolveAssignedShiftForDate($assignment, $workDate);
                    }
                    if (! $selectedShift) {
                        continue;
                    }

                    $shift = $selectedShift['shift'];
                    $selectedShiftId = (int) ($selectedShift['shift_id'] ?? 0);
                    $shiftStart = Carbon::parse($workDate->format('Y-m-d').' '.substr((string) $shift->start_time, 0, 8));
                    $shiftEnd = Carbon::parse($workDate->format('Y-m-d').' '.substr((string) $shift->end_time, 0, 8));
                    $isCrossDay = $shiftEnd->lte($shiftStart);
                    if ($isCrossDay) {
                        $shiftEnd->addDay();
                    }
                    $approvedSplWindow = $this->resolveApprovedOvertimeWindowForShift(
                        $approvedOvertimeMap[((int) $assignment->karyawan_id).'|'.$workDate->format('Y-m-d')] ?? [],
                        $shiftStart,
                        $shiftEnd
                    );
                    $autoOvertimeWithoutSpl = $this->assignmentAllowsAutomaticOvertimeWithoutSpl($assignment);
                    $hasApprovedSpl = (bool) ($approvedSplWindow['has_any'] ?? false);
                    $continuesBridge = $continuesNextDayMap[((int) $assignment->karyawan_id).'|'.$workDate->format('Y-m-d')] ?? null;
                    $isContinuesStartDay = is_array($continuesBridge) && ($continuesBridge['mode'] ?? '') === 'start';

                    $windowStart = $shiftStart->copy()->subHours(6);
                    $windowEnd = $shiftEnd->copy()->addHours(8);
                    $candidate = $karyawanLogs
                        ->filter(fn ($l) => $l->log_at
                            && $l->log_at->between($windowStart, $windowEnd)
                            && ! isset($consumedLogAtKeys[$l->log_at->format('Y-m-d H:i:s')]))
                        ->sortBy('log_at')
                        ->values();

                    // Shift lintas hari: IN shift berikutnya bukan OUT shift malam.
                    // Gunakan tipe log mesin bila tersedia; fallback tetap memakai kandidat lama.
                    if ($isCrossDay) {
                        $typedIn = $candidate->filter(function ($log) use ($shiftStart, $shiftEnd): bool {
                            $type = strtolower(trim((string) ($log->log_type ?? '')));

                            return in_array($type, ['in', 'check_in', 'checkin', '0'], true)
                                && $log->log_at->lt($shiftEnd);
                        });
                        $typedOut = $candidate->filter(function ($log) use ($shiftStart): bool {
                            $type = strtolower(trim((string) ($log->log_type ?? '')));

                            return in_array($type, ['out', 'check_out', 'checkout', '1'], true)
                                && $log->log_at->gte($shiftStart);
                        });
                        if ($typedIn->isNotEmpty() || $typedOut->isNotEmpty()) {
                            $candidate = $typedIn->concat($typedOut)
                                ->unique(fn ($log) => $log->log_at->format('Y-m-d H:i:s'))
                                ->sortBy('log_at')
                                ->values();
                        }
                    }

                    $status = 'no_log';
                    $reason = 'Tidak ada log dalam window shift.';
                    $confidence = 0.0;
                    $checkin = null;
                    $checkout = null;
                    $suggestedIn = null;
                    $suggestedOut = null;

                    if ($candidate->count() === 1) {
                        $single = $candidate->first()->log_at;
                        if ($single->lte($shiftStart->copy()->addHours(4))) {
                            $checkin = $single->copy();
                            $nextDayCheckout = null;
                            if ($isContinuesStartDay) {
                                $nextDayCheckoutRow = $karyawanLogs
                                    ->filter(fn ($l) => $l->log_at
                                        && ! isset($consumedLogAtKeys[$l->log_at->format('Y-m-d H:i:s')])
                                        && $l->log_at->gt($shiftEnd)
                                        && $l->log_at->lte($shiftStart->copy()->addHours(30)))
                                    ->sortBy('log_at')
                                    ->first();
                                $nextDayCheckout = $nextDayCheckoutRow?->log_at?->copy();
                            }

                            if ($nextDayCheckout && $nextDayCheckout->gt($checkin)) {
                                $status = 'shift_transition';
                                $reason = trim($this->buildContinuesNextDayReason($continuesBridge)."\nAuto checkout +1 terdeteksi dari log besok pagi.");
                                $checkout = $nextDayCheckout;
                                $confidence = 72.5;
                                $consumedLogAtKeys[$nextDayCheckout->format('Y-m-d H:i:s')] = true;
                            } else {
                                $status = 'missing_out';
                                $reason = 'Terdeteksi IN tanpa OUT.';
                                $suggestedOut = $shiftEnd->copy();
                                $confidence = 62.5;
                            }
                        } else {
                            $status = 'missing_in';
                            $reason = 'Terdeteksi OUT tanpa IN.';
                            $checkout = $single->copy();
                            $suggestedIn = $shiftStart->copy();
                            $confidence = 58.0;
                        }
                    } elseif ($candidate->count() >= 2) {
                        $firstCandidate = $candidate->first()->log_at?->copy();
                        $lastCandidate = $candidate->last()->log_at?->copy();
                        $clusteredCandidate = $this->collapseNearbyLogsWithMobilePriority($candidate);
                        $clusteredCount = $clusteredCandidate->count();
                        $firstRow = $clusteredCandidate->first();
                        $lastRow = $clusteredCandidate->last();
                        $first = $firstRow?->log_at?->copy() ?: $firstCandidate;
                        $last = $lastRow?->log_at?->copy() ?: $lastCandidate;
                        $clusterGapMinutes = ($firstCandidate && $lastCandidate) ? abs($firstCandidate->diffInMinutes($lastCandidate, false)) : null;

                        if ($clusteredCount <= 1 && $clusterGapMinutes !== null && $clusterGapMinutes <= 10) {
                            $status = 'unpaired';
                            $reason = 'Terdeteksi beberapa percobaan log berdekatan, bukan pasangan IN/OUT.';
                            $checkin = $first;
                            $checkout = null;
                            $suggestedIn = null;
                            $suggestedOut = null;
                            $confidence = 18.0;
                        } else {
                            $checkin = $first;
                            $checkout = $last;

                            $startDiff = abs($shiftStart->diffInMinutes($checkin, false));
                            $endDiff = abs($shiftEnd->diffInMinutes($checkout, false));
                            $confidence = max(10, min(100, 100 - (($startDiff + $endDiff) / 4)));

                            if ($startDiff <= 180 && $endDiff <= 240) {
                                $status = 'normal';
                                $reason = 'Log IN/OUT terdeteksi normal.';
                            } elseif ($startDiff > 240 && $endDiff <= 240) {
                                $status = 'shift_transition';
                                $reason = 'Kemungkinan transisi shift, jam IN jauh dari rencana.';
                            } elseif ($startDiff <= 180 && $endDiff > 300) {
                                $status = 'shift_transition';
                                $reason = 'Kemungkinan transisi shift, jam OUT jauh dari rencana.';
                            } else {
                                $status = 'unpaired';
                                $reason = 'Log tidak match dengan pola shift yang direncanakan.';
                                $suggestedIn = $shiftStart->copy();
                                $suggestedOut = $shiftEnd->copy();
                            }
                        }
                    }

                    if ($status === 'unpaired' && $clusteredCount <= 1 && $clusterGapMinutes !== null && $clusterGapMinutes <= 10) {
                        $checkin = $first;
                        $checkout = null;
                        $suggestedIn = null;
                        $suggestedOut = null;
                        $confidence = 18.0;
                        $reason = 'Terdeteksi beberapa percobaan log berdekatan, bukan pasangan IN/OUT.';
                    }

                    $effectiveRounding = $rounding ?: $assignment->roundingRule;
                    if ($effectiveRounding) {
                        if ($checkin && in_array($effectiveRounding->target_type, ['checkin', 'both'], true)) {
                            $checkin = $this->applyRounding($checkin, $effectiveRounding, 'checkin');
                        }
                        if ($checkout && in_array($effectiveRounding->target_type, ['checkout', 'both'], true)) {
                            $checkout = $this->applyRounding($checkout, $effectiveRounding, 'checkout');
                        }
                        if ($suggestedIn && in_array($effectiveRounding->target_type, ['checkin', 'both'], true)) {
                            $suggestedIn = $this->applyRounding($suggestedIn, $effectiveRounding, 'checkin');
                        }
                        if ($suggestedOut && in_array($effectiveRounding->target_type, ['checkout', 'both'], true)) {
                            $suggestedOut = $this->applyRounding($suggestedOut, $effectiveRounding, 'checkout');
                        }
                    }

                    $autoOtWorkdayMode = $this->assignmentAutomaticOvertimeWorkdayMode($assignment);
                    if ($checkin && $checkin->lt($shiftStart)) {
                        if ($autoOvertimeWithoutSpl && $autoOtWorkdayMode === 'full_actual') {
                            $reason = trim(($reason ? $reason."\n" : '').'OT otomatis tanpa SPL mode full actual aktif; checkin mengikuti log aktual.');
                        } elseif (! $approvedSplWindow['allow_pre']) {
                            $checkin = $shiftStart->copy();
                            $reason = trim(($reason ? $reason."\n" : '').'Checkin awal dibatasi jam masuk karena SPL awal belum approved.');
                        } elseif ($approvedSplWindow['pre_start'] instanceof Carbon && $checkin->lt($approvedSplWindow['pre_start'])) {
                            $checkin = $approvedSplWindow['pre_start']->copy();
                            $reason = trim(($reason ? $reason."\n" : '').'Checkin awal dibatasi sesuai window SPL awal approved.');
                        }
                    }

                    if ($checkout && $checkout->gt($shiftEnd)) {
                        if ($autoOvertimeWithoutSpl) {
                            $reason = trim(($reason ? $reason."\n" : '').'OT otomatis tanpa SPL aktif; checkout lembur mengikuti log aktual dan tidak dibatasi window SPL.');
                        } elseif (! $approvedSplWindow['allow_post']) {
                            $checkout = $shiftEnd->copy();
                            $reason = trim(($reason ? $reason."\n" : '').'Checkout dibatasi jam pulang karena SPL lembur akhir belum approved. Jika lembur lebih lama, ajukan Extend SPL (alasan) untuk tambahan jam.');
                        } elseif ($approvedSplWindow['post_end'] instanceof Carbon && $checkout->gt($approvedSplWindow['post_end'])) {
                            $checkout = $approvedSplWindow['post_end']->copy();
                            $reason = trim(($reason ? $reason."\n" : '').'Checkout dibatasi sesuai window SPL approved. Jika lembur lebih lama dari pengajuan, ajukan Extend SPL (alasan); jika tidak, jam di luar window tidak dihitung.');
                        }
                    }

                    // True jika pada tanggal tsb ada SPL approved (dipakai untuk penambahan reason SPL Approved).
                    $splApproved = (bool) ($approvedSplWindow['has_any'] ?? false);

                    // If there is approved SPL on this date, append SPL + Job info into reason for traceability.
                    if ($splApproved && ! str_contains((string) $reason, 'SPL Approved')) {
                        $splWindows = $overtimeApprovedMap[$assignment->karyawan_id.'|'.$workDate->format('Y-m-d')] ?? [];
                        $docNos = collect($splWindows)->pluck('document_no')->filter()->unique()->values()->all();
                        $jobCodes = collect($splWindows)->pluck('job_code')->filter()->unique()->values()->all();
                        $splLine = 'SPL Approved: '.(! empty($docNos) ? implode(', ', $docNos) : '-');
                        if (! empty($jobCodes)) {
                            $splLine .= ' | No Job: '.implode(', ', $jobCodes);
                        }
                        $reason = trim(($reason ? $reason."\n" : '').$splLine);
                    }

                    $key = [
                        'profil_bulan_id' => (int) $profil->id,
                        'karyawan_id' => (int) $assignment->karyawan_id,
                        'work_date' => $workDate->format('Y-m-d'),
                    ];
                    $reviewKey = ((int) $assignment->karyawan_id).'|'.$workDate->format('Y-m-d');
                    $payload = [
                        'planned_profil_jam_kerja_id' => $selectedShiftId > 0 ? $selectedShiftId : ($assignment->profil_jam_kerja_id ?: null),
                        'planned_shift_start' => $shiftStart->format('Y-m-d H:i:s'),
                        'planned_shift_end' => $shiftEnd->format('Y-m-d H:i:s'),
                        'is_cross_day' => $isCrossDay,
                        'checkin_at' => $checkin?->format('Y-m-d H:i:s'),
                        'checkout_at' => $checkout?->format('Y-m-d H:i:s'),
                        'suggested_checkin_at' => $suggestedIn?->format('Y-m-d H:i:s'),
                        'suggested_checkout_at' => $suggestedOut?->format('Y-m-d H:i:s'),
                        'status' => $status,
                        'confidence_score' => round($confidence, 2),
                        'reason' => $reason,
                    ];

                    $review = $existingReviews->get($reviewKey);
                    if (! $review) {
                        $review = new AttendanceDailyReviewModel($key);
                    }
                    $before = $review->exists ? $this->snapshotReview($review) : null;
                    $preserveApproval = false;
                    if ($review->exists && (bool) $review->is_approved) {
                        $preserveApproval = $this->isDetectionCoreUnchanged($review, $payload);
                    }
                    if (! $preserveApproval) {
                        $payload['is_approved'] = false;
                        $payload['approved_by'] = null;
                        $payload['approved_at'] = null;
                    }
                    $manualSnapshot = $review->exists ? ($manualTimeSnapshotByReviewId[(int) $review->id] ?? null) : null;
                    if ($review->exists && (str_contains((string) ($review->reason ?? ''), 'MANUAL_TIME_LOCK::') || is_array($manualSnapshot))) {
                        $manualSnapshot = (array) ($manualSnapshot ?? []);
                        $restoreDateTime = static function ($value): ?string {
                            if (empty($value)) {
                                return null;
                            }

                            return Carbon::parse((string) $value)
                                ->setTimezone(config('app.timezone'))
                                ->format('Y-m-d H:i:s');
                        };
                        $payload['checkin_at'] = array_key_exists('checkin_at', $manualSnapshot) ? $restoreDateTime($manualSnapshot['checkin_at']) : $review->checkin_at?->format('Y-m-d H:i:s');
                        $payload['checkout_at'] = array_key_exists('checkout_at', $manualSnapshot) ? $restoreDateTime($manualSnapshot['checkout_at']) : $review->checkout_at?->format('Y-m-d H:i:s');
                        $payload['suggested_checkin_at'] = array_key_exists('suggested_checkin_at', $manualSnapshot) ? $restoreDateTime($manualSnapshot['suggested_checkin_at']) : $review->suggested_checkin_at?->format('Y-m-d H:i:s');
                        $payload['suggested_checkout_at'] = array_key_exists('suggested_checkout_at', $manualSnapshot) ? $restoreDateTime($manualSnapshot['suggested_checkout_at']) : $review->suggested_checkout_at?->format('Y-m-d H:i:s');
                        $payload['status'] = (string) ($manualSnapshot['status'] ?? $review->status);
                        if (! empty($payload['checkin_at']) && ! empty($payload['checkout_at'])) {
                            $payload['status'] = 'normal';
                        } elseif (! empty($payload['checkin_at']) && empty($payload['checkout_at'])) {
                            $payload['status'] = 'missing_out';
                        } elseif (empty($payload['checkin_at']) && ! empty($payload['checkout_at'])) {
                            $payload['status'] = 'missing_in';
                        }
                        $payload['confidence_score'] = (float) ($manualSnapshot['confidence_score'] ?? $review->confidence_score ?? 100);
                        $manualReason = (string) ($manualSnapshot['reason'] ?? $review->reason ?? '');
                        if (! str_contains($manualReason, 'MANUAL_TIME_LOCK::')) {
                            $manualReason = trim(($manualReason ? $manualReason."\n" : '').'MANUAL_TIME_LOCK::Jam dikunci dari koreksi manual.');
                        }
                        $payload['reason'] = $manualReason;
                    }
                    $review->fill($payload);

                    if (! $review->exists || $review->isDirty()) {
                        $action = $review->exists ? 'updated_by_detection' : 'created_by_detection';
                        $review->save();
                        $existingReviews->put($reviewKey, $review);
                        $this->saveHistory($review, $action, $before, $this->snapshotReview($review), $reason);
                    }
                    $affected++;
                }

                $processedAssignments++;
                if ($job && ($processedAssignments % 10 === 0 || $processedAssignments === $totalAssignments)) {
                    $job->refresh();
                    if ((string) $job->status === 'cancelled') {
                        return ['affected' => $affected, 'cancelled' => true];
                    }
                    if ((string) $job->status === 'paused') {
                        return ['affected' => $affected, 'paused' => true];
                    }
                    $job->processed_users = $processedAssignments;
                    $job->save();
                }
            }
        }

        return ['affected' => $affected];
    }

    // =========================================================================
    // isMobileAttendanceSource() - Cek kondisi tertentu, return bool
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function isMobileAttendanceSource(?string $source): bool
    {
        $raw = strtolower(trim((string) ($source ?? '')));
        if ($raw === '') {
            return false;
        }

        return str_contains($raw, 'mobile')
            || str_contains($raw, 'android')
            || str_contains($raw, 'ios')
            || str_contains($raw, 'app');
    }

    // =========================================================================
    // sourcePriorityScore() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function sourcePriorityScore(?string $source): int
    {
        return $this->isMobileAttendanceSource($source) ? 0 : 1;
    }

    /**
     * Collapse near-duplicate check events and prefer mobile rows inside the same time cluster.
     * This lets machine logs stay valid as fallback, while HP remains the source of truth when both exist.
     *
     * @param  \Illuminate\Support\Collection<int, mixed>  $candidate
     * @return \Illuminate\Support\Collection<int, mixed>
     */
    // =========================================================================
    // collapseNearbyLogsWithMobilePriority() - Menggabungkan/merapikan data yang berdekatan
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function collapseNearbyLogsWithMobilePriority($candidate)
    {
        $sorted = collect($candidate)
            ->filter(fn ($row) => $row && $row->log_at)
            ->sortBy('log_at')
            ->values();

        if ($sorted->count() <= 1) {
            return $sorted;
        }

        $toleranceMinutes = 5;
        $clusters = [];
        foreach ($sorted as $row) {
            if (empty($clusters)) {
                $clusters[] = [$row];

                continue;
            }

            $lastClusterIndex = count($clusters) - 1;
            $lastCluster = $clusters[$lastClusterIndex];
            $lastRow = end($lastCluster);
            if ($lastRow && $lastRow->log_at instanceof Carbon && $row->log_at instanceof Carbon) {
                $gapMinutes = abs($lastRow->log_at->diffInMinutes($row->log_at, false));
                if ($gapMinutes <= $toleranceMinutes) {
                    $clusters[$lastClusterIndex][] = $row;

                    continue;
                }
            }

            $clusters[] = [$row];
        }

        $representatives = [];
        foreach ($clusters as $cluster) {
            $rep = collect($cluster)
                ->sort(function ($a, $b): int {
                    $sourceCompare = $this->sourcePriorityScore($a->source ?? null) <=> $this->sourcePriorityScore($b->source ?? null);
                    if ($sourceCompare !== 0) {
                        return $sourceCompare;
                    }

                    $aAt = $a->log_at instanceof Carbon ? $a->log_at->getTimestamp() : 0;
                    $bAt = $b->log_at instanceof Carbon ? $b->log_at->getTimestamp() : 0;

                    return $aAt <=> $bAt;
                })
                ->first();

            if ($rep) {
                $representatives[] = $rep;
            }
        }

        return collect($representatives)
            ->sortBy('log_at')
            ->values();
    }

    /**
     * @return array{shift:ProfilJamKerjaModel,shift_id:int}|null
     */
    // =========================================================================
    // resolveAssignedShiftForDate() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveAssignedShiftForDate(ProfilBulanKaryawanModel $assignment, Carbon $workDate): ?array
    {
        $primary = $assignment->profilJamKerja;
        if (! $primary) {
            return null;
        }

        $mode = strtolower(trim((string) ($assignment->shift_mode ?? 'fixed')));
        if ($mode !== 'weekly_rotate') {
            return [
                'shift' => $primary,
                'shift_id' => (int) ($assignment->profil_jam_kerja_id ?? 0),
            ];
        }

        $alt = $assignment->profilJamKerjaAlt;
        $anchorDate = $assignment->rotation_anchor_date
            ? Carbon::parse((string) $assignment->rotation_anchor_date)->startOfDay()
            : null;
        $rotationDays = max(1, (int) ($assignment->rotation_days ?? 7));
        if (! $alt || ! $anchorDate) {
            return [
                'shift' => $primary,
                'shift_id' => (int) ($assignment->profil_jam_kerja_id ?? 0),
            ];
        }

        $diffDays = $anchorDate->diffInDays($workDate->copy()->startOfDay(), false);
        if ($diffDays < 0) {
            return [
                'shift' => $primary,
                'shift_id' => (int) ($assignment->profil_jam_kerja_id ?? 0),
            ];
        }

        $block = (int) floor($diffDays / $rotationDays);
        $isPrimaryBlock = ($block % 2) === 0;
        if ($isPrimaryBlock) {
            return [
                'shift' => $primary,
                'shift_id' => (int) ($assignment->profil_jam_kerja_id ?? 0),
            ];
        }

        return [
            'shift' => $alt,
            'shift_id' => (int) ($assignment->profil_jam_kerja_id_alt ?? 0),
        ];
    }

    // =========================================================================
    // reviewData() - Data review attendance untuk DataTable
    // Dipanggil dari: GET /attendance-review/reviews
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function reviewData(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['required_without:karyawan_id', 'array', 'min:1', 'max:50'],
            'karyawan_ids.*' => ['integer', 'distinct', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['nullable', 'array'],
            'karyawan_ids.*' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
            'page' => ['nullable', 'integer', 'min:1'],
            'per_page' => ['nullable', 'integer', 'min:10', 'max:500'],
            'status_filter' => ['nullable', 'in:missing,missing_out,missing_in'],
            'profile_scope' => ['nullable', 'string', 'in:all,both,main,sub,selected'],
            'urgency_shadow' => ['nullable', 'boolean'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profilId = (int) $request->input('profil_bulan_id');
        $profil = ProfilBulanModel::query()->findOrFail($profilId);
        $scopeProfilIds = [$profilId];
        $filterKaryawanIds = $this->resolveAttendanceReviewKaryawanIds($request);
        $statusFilter = (string) $request->input('status_filter', '');
        $page = max(1, (int) $request->input('page', 1));
        $perPage = max(10, min(500, (int) $request->input('per_page', 50)));

        $periodStart = Carbon::parse($profil->start_date)->startOfDay();
        $periodEnd = Carbon::parse($profil->end_date)->startOfDay();
        $filterDateFrom = $request->filled('date_from') ? Carbon::parse($request->input('date_from'))->startOfDay() : null;
        $filterDateTo = $request->filled('date_to') ? Carbon::parse($request->input('date_to'))->startOfDay() : null;
        $effectiveStart = $filterDateFrom && $filterDateFrom->gt($periodStart) ? $filterDateFrom : $periodStart->copy();
        $effectiveEnd = $filterDateTo && $filterDateTo->lt($periodEnd) ? $filterDateTo : $periodEnd->copy();
        if ($effectiveStart->gt($effectiveEnd)) {
            return response()->json([
                'data' => [],
                'meta' => [
                    'holiday_map' => [],
                    'holiday_special_map' => [],
                    'workday_map' => [],
                    'date_from' => $effectiveStart->format('Y-m-d'),
                    'date_to' => $effectiveEnd->format('Y-m-d'),
                    'status_filter' => '',
                    'pagination' => [
                        'page' => $page,
                        'per_page' => $perPage,
                        'total_employees' => 0,
                        'total_pages' => 0,
                    ],
                ],
            ]);
        }

        $assignmentQuery = ProfilBulanKaryawanModel::query()
            ->with('karyawan:id,employee_code,finger_id,full_name')
            ->with('profilJamKerja:id,code,name,start_time,end_time')
            ->whereIn('profil_bulan_id', $scopeProfilIds)
            ->where('is_active', true);

        if (! empty($filterKaryawanIds)) {
            $assignmentQuery->whereIn('karyawan_id', $filterKaryawanIds);
        }

        $assignmentEmployees = $assignmentQuery
            ->orderBy('karyawan_id')
            ->get()
            ->filter(fn ($row) => ! empty($row->karyawan_id))
            ->map(fn ($row) => [
                'karyawan_id' => (int) $row->karyawan_id,
                'employee_code' => $row->karyawan?->employee_code,
                'finger_id' => $row->karyawan?->finger_id,
                'employee_name' => $row->karyawan?->full_name,
                'contract_start_date' => ! empty($row->contract_start_date)
                    ? Carbon::parse((string) $row->contract_start_date)->format('Y-m-d')
                    : null,
                'contract_end_date' => ! empty($row->contract_end_date)
                    ? Carbon::parse((string) $row->contract_end_date)->format('Y-m-d')
                    : null,
                'applied_shift_code' => (string) ($row->profilJamKerja?->code ?? ''),
                'applied_shift_name' => (string) ($row->profilJamKerja?->name ?? ''),
                'applied_shift_time' => $row->profilJamKerja
                    ? (substr((string) $row->profilJamKerja->start_time, 0, 5).'-'.substr((string) $row->profilJamKerja->end_time, 0, 5))
                    : '',
                'applied_break_start_time' => $row->profilJamKerja?->break_start_time
                    ? substr((string) $row->profilJamKerja->break_start_time, 0, 8)
                    : '',
                'applied_break_end_time' => $row->profilJamKerja?->break_end_time
                    ? substr((string) $row->profilJamKerja->break_end_time, 0, 8)
                    : '',
                'overtime_auto_without_spl' => $this->assignmentAllowsAutomaticOvertimeWithoutSpl($row),
                'auto_no_rest_normal_included' => $this->assignmentAllowsAutomaticNoRestNormalIncluded($row),
                'auto_no_rest_skip_break' => $this->assignmentAllowsAutomaticNoRestSkipBreak($row),
            ])
            ->unique('karyawan_id')
            ->values();

        $missingAssignment = false;
        $missingAssignmentEmployee = null;

        // Fallback: jika filter user tidak match assignment profil, tampilkan karyawan yang dipilih
        // agar user paham bahwa karyawan belum masuk profil bulan.
        if ($assignmentEmployees->isEmpty() && count($filterKaryawanIds) === 1) {
            $missingAssignment = true;
            $missingAssignmentEmployee = KaryawanModel::query()
                ->select('id', 'employee_code', 'finger_id', 'full_name')
                ->find((int) $filterKaryawanIds[0]);

            if ($missingAssignmentEmployee) {
                $assignmentEmployees = collect([[
                    'karyawan_id' => (int) $missingAssignmentEmployee->id,
                    'employee_code' => $missingAssignmentEmployee->employee_code,
                    'finger_id' => $missingAssignmentEmployee->finger_id,
                    'employee_name' => $missingAssignmentEmployee->full_name,
                    'applied_shift_code' => '',
                    'applied_shift_name' => '',
                    'applied_shift_time' => '',
                    'overtime_auto_without_spl' => false,
                    'applied_break_start_time' => '',
                    'applied_break_end_time' => '',
                    'auto_no_rest_normal_included' => false,
                    'auto_no_rest_skip_break' => false,
                ]]);
            }
        }

        if (in_array($statusFilter, ['missing', 'missing_out', 'missing_in'], true) && $assignmentEmployees->isNotEmpty()) {
            $statusValues = $statusFilter === 'missing'
                ? ['missing_in', 'missing_out']
                : [$statusFilter];
            $missingEmployeeIds = AttendanceDailyReviewModel::query()
                ->whereIn('profil_bulan_id', $scopeProfilIds)
                ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
                ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
                ->whereIn('status', $statusValues)
                ->pluck('karyawan_id')
                ->map(fn ($id) => (int) $id)
                ->unique()
                ->values();

            if ($missingEmployeeIds->isEmpty()) {
                $assignmentEmployees = collect();
            } else {
                $missingEmployeeIdMap = $missingEmployeeIds->flip();
                $assignmentEmployees = $assignmentEmployees
                    ->filter(fn ($row) => $missingEmployeeIdMap->has((int) ($row['karyawan_id'] ?? 0)))
                    ->values();
            }
        }

        $totalEmployees = $assignmentEmployees->count();
        if ($totalEmployees > 0) {
            $maxPage = (int) ceil($totalEmployees / max(1, $perPage));
            if ($page > $maxPage) {
                $page = 1;
            }
        }
        $pagedEmployees = $assignmentEmployees->forPage($page, $perPage)->values();

        $employeeIds = $pagedEmployees->pluck('karyawan_id')->map(fn ($v) => (int) $v)->values();

        $customScheduleRows = DB::table('master_shift_schedules')
            ->whereIn('karyawan_id', $employeeIds->all())
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->where('is_active', true)
            ->where(function ($q) use ($scopeProfilIds): void {
                $q->whereNull('profil_bulan_id')
                    ->orWhereIn('profil_bulan_id', $scopeProfilIds);
            })
            ->orderByRaw(
                'CASE
                    WHEN profil_bulan_id = ? AND is_locked = 1 THEN 1
                    WHEN profil_bulan_id = ? AND is_locked = 0 THEN 2
                    WHEN profil_bulan_id IS NULL AND is_locked = 1 THEN 3
                    ELSE 4
                END ASC',
                [(int) $profil->id, (int) $profil->id]
            )
            ->orderByDesc('id')
            ->get(['karyawan_id', 'work_date', 'profil_jam_kerja_id']);
        $customScheduleMap = [];
        $customScheduleEmployeeIds = [];
        $customShiftIds = [];
        foreach ($customScheduleRows as $row) {
            $dateKey = Carbon::parse((string) $row->work_date)->format('Y-m-d');
            $mapKey = ((int) $row->karyawan_id).'|'.$dateKey;
            if (isset($customScheduleMap[$mapKey])) {
                continue;
            }
            $shiftId = (int) ($row->profil_jam_kerja_id ?? 0);
            if ($shiftId <= 0) {
                continue;
            }
            $customScheduleMap[$mapKey] = $shiftId;
            $customScheduleEmployeeIds[(int) $row->karyawan_id] = true;
            $customShiftIds[$shiftId] = $shiftId;
        }
        $customShiftMap = collect();
        if (! empty($customShiftIds)) {
            $customShiftMap = ProfilJamKerjaModel::query()
                ->whereIn('id', array_values($customShiftIds))
                ->get(['id', 'code', 'name', 'start_time', 'end_time', 'break_start_time', 'break_end_time'])
                ->keyBy('id');
        }

        if (
            ! $request->filled('date_from')
            && ! $request->filled('date_to')
            && $employeeIds->isNotEmpty()
        ) {
            $dateBounds = AttendanceDailyReviewModel::query()
                ->whereIn('profil_bulan_id', $scopeProfilIds)
                ->whereIn('karyawan_id', $employeeIds)
                ->selectRaw('MIN(work_date) as min_work_date, MAX(work_date) as max_work_date')
                ->first();

            if (! empty($dateBounds?->min_work_date) && ! empty($dateBounds?->max_work_date)) {
                $actualStart = Carbon::parse($dateBounds->min_work_date)->startOfDay();
                $actualEnd = Carbon::parse($dateBounds->max_work_date)->startOfDay();
                if ($actualStart->lte($actualEnd)) {
                    $effectiveStart = $actualStart;
                    $effectiveEnd = $actualEnd;
                }
            }
        }

        $existing = AttendanceDailyReviewModel::query()
            ->with('karyawan:id,employee_code,finger_id,full_name')
            ->withCount('histories')
            ->whereIn('profil_bulan_id', $scopeProfilIds)
            ->whereIn('karyawan_id', $employeeIds)
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->get()
            ->keyBy(fn (AttendanceDailyReviewModel $row) => ((int) $row->karyawan_id).'|'.optional($row->work_date)->format('Y-m-d'));

        $plannedShiftIds = $existing->values()
            ->pluck('planned_profil_jam_kerja_id')
            ->filter(fn ($id) => ! empty($id))
            ->map(fn ($id) => (int) $id)
            ->unique()
            ->values();
        $plannedShiftMap = collect();
        if ($plannedShiftIds->isNotEmpty()) {
            $plannedShiftMap = ProfilJamKerjaModel::query()
                ->whereIn('id', $plannedShiftIds->all())
                ->get(['id', 'code', 'name', 'start_time', 'end_time', 'break_start_time', 'break_end_time'])
                ->keyBy('id');
        }

        $reviewIds = $existing->values()->pluck('id')->filter()->map(fn ($id) => (int) $id)->values();
        $restorableReviewIdMap = [];
        if ($reviewIds->isNotEmpty()) {
            $restorableReviewIdMap = AttendanceDailyReviewHistoryModel::query()
                ->whereIn('attendance_daily_review_id', $reviewIds)
                ->where('action', 'rejected_hours_holiday')
                ->pluck('attendance_daily_review_id')
                ->map(fn ($id) => (int) $id)
                ->flip()
                ->all();
        }

        $periodDates = collect(CarbonPeriod::create(
            $effectiveStart->copy(),
            $effectiveEnd->copy()
        ))
            ->map(fn (Carbon $date) => $date->format('Y-m-d'))
            ->values();

        $calendarMarks = $this->buildCalendarMarks($effectiveStart->copy(), $effectiveEnd->copy());
        $holidayMap = $calendarMarks['holiday_map'];
        $workdayMap = $calendarMarks['workday_map'];
        $holidaySpecialMap = $calendarMarks['holiday_special_map'] ?? [];
        $leaveApprovedMap = $this->buildLeaveApprovedMap($employeeIds, $effectiveStart->copy(), $effectiveEnd->copy());
        $overtimeApprovedMap = $this->buildOvertimeApprovedMap($employeeIds, $effectiveStart->copy(), $effectiveEnd->copy());
        $overtimeTagMap = $this->buildOvertimeTagMap($employeeIds, $effectiveStart->copy(), $effectiveEnd->copy());
        $continuesNextDayMap = $this->buildContinuesNextDayBridgeMap($employeeIds, $effectiveStart->copy(), $effectiveEnd->copy());
        $forgettingClockTagMap = $this->buildForgettingClockTagMap($employeeIds, $effectiveStart->copy(), $effectiveEnd->copy());
        $offlinePendingMap = $this->buildOfflinePendingMap($employeeIds, $effectiveStart->copy(), $effectiveEnd->copy());

        // Ambil log absensi mentah (min/max per karyawan per tanggal) untuk menampilkan "jam asli"
        // meskipun jam IN/OUT di review sudah dibulatkan/di-cut mengikuti shift planning.
        // Ini juga dipakai untuk mendeteksi "OT tanpa SPL" (raw out > planned end tetapi belum ada SPL).
        $rawLogMinMaxMap = [];
        if ($employeeIds->isNotEmpty()) {
            try {
                $rawLogAgg = AttendanceLogModel::query()
                    ->whereIn('karyawan_id', $employeeIds->all())
                    ->whereBetween('log_at', [
                        $effectiveStart->copy()->startOfDay(),
                        $effectiveEnd->copy()->endOfDay(),
                    ])
                    ->selectRaw('karyawan_id, DATE(log_at) as d, MIN(log_at) as min_at, MAX(log_at) as max_at')
                    ->groupBy('karyawan_id', 'd')
                    ->get();

                foreach ($rawLogAgg as $row) {
                    $karyawanId = (int) ($row->karyawan_id ?? 0);
                    $d = (string) ($row->d ?? '');
                    if ($karyawanId <= 0 || $d === '') {
                        continue;
                    }
                    $rawLogMinMaxMap[$karyawanId.'|'.$d] = [
                        'min_at' => ! empty($row->min_at) ? (string) $row->min_at : null,
                        'max_at' => ! empty($row->max_at) ? (string) $row->max_at : null,
                    ];
                }
            } catch (\Throwable $e) {
                // Optional: jika query agregasi gagal (mis. driver berbeda), UI tetap jalan tanpa raw logs.
                $rawLogMinMaxMap = [];
            }
        }

        $crossDayConsumedLogMap = [];
        foreach ($existing as $existingReview) {
            if (empty($existingReview->checkout_at) || empty($existingReview->work_date)) {
                continue;
            }
            try {
                $checkoutAt = Carbon::parse((string) $existingReview->checkout_at);
                $existingWorkDate = Carbon::parse((string) $existingReview->work_date)->startOfDay();
            } catch (\Throwable) {
                continue;
            }
            if ($checkoutAt->toDateString() <= $existingWorkDate->toDateString()) {
                continue;
            }
            $crossDayConsumedLogMap[((int) $existingReview->karyawan_id).'|'.$checkoutAt->toDateString().'|'.$checkoutAt->format('Y-m-d H:i')] = true;
        }

        if (! empty($crossDayConsumedLogMap)) {
            foreach ($rawLogMinMaxMap as $rawKey => $rawLog) {
                [$employeeId, $rawDate] = array_pad(explode('|', (string) $rawKey, 2), 2, '');
                foreach (['min_at', 'max_at'] as $field) {
                    if (empty($rawLog[$field])) {
                        continue;
                    }
                    $rawAt = Carbon::parse((string) $rawLog[$field]);
                    $consumeKey = ((int) $employeeId).'|'.$rawDate.'|'.$rawAt->format('Y-m-d H:i');
                    if (isset($crossDayConsumedLogMap[$consumeKey])) {
                        $rawLogMinMaxMap[$rawKey][$field] = null;
                    }
                }
            }
        }

        $rawLogsByEmployee = collect();
        if ($employeeIds->isNotEmpty()) {
            try {
                $rawLogsByEmployee = AttendanceLogModel::query()
                    ->whereIn('karyawan_id', $employeeIds->all())
                    ->whereBetween('log_at', [
                        $effectiveStart->copy()->subDay()->startOfDay(),
                        $effectiveEnd->copy()->addDay()->endOfDay(),
                    ])
                    ->orderBy('log_at')
                    ->get(['karyawan_id', 'log_at', 'log_type'])
                    ->map(function (AttendanceLogModel $row) {
                        if (! ($row->log_at instanceof Carbon) && ! empty($row->log_at)) {
                            $row->log_at = Carbon::parse((string) $row->log_at);
                        }

                        return $row;
                    })
                    ->filter(fn (AttendanceLogModel $row) => $row->log_at instanceof Carbon)
                    ->groupBy(fn (AttendanceLogModel $row) => (int) $row->karyawan_id);
            } catch (\Throwable $e) {
                $rawLogsByEmployee = collect();
            }
        }

        $resolveRawLogByShiftWindow = function (?AttendanceDailyReviewModel $review, array $fallback = []) use ($rawLogsByEmployee, $existing): array {
            $fallback = [
                'min_at' => $fallback['min_at'] ?? null,
                'max_at' => $fallback['max_at'] ?? null,
            ];

            if (
                ! $review
                || empty($review->planned_shift_start)
                || empty($review->planned_shift_end)
                || $rawLogsByEmployee->isEmpty()
            ) {
                return $fallback;
            }

            try {
                $karyawanId = (int) $review->karyawan_id;
                $workDate = $review->work_date instanceof Carbon
                    ? $review->work_date->copy()->format('Y-m-d')
                    : Carbon::parse((string) $review->work_date)->format('Y-m-d');
                $plannedStart = Carbon::parse((string) $review->planned_shift_start);
                $plannedEnd = Carbon::parse((string) $review->planned_shift_end);
                $windowStart = $plannedStart->copy()->subHours(6);
                $windowEnd = $plannedEnd->copy()->addHours(8)->endOfMinute();
                $inWindowEnd = $plannedStart->copy()->addHours(6);
                if ($inWindowEnd->gt($plannedEnd)) {
                    $inWindowEnd = $plannedEnd->copy();
                }
                $outWindowStart = $plannedEnd->copy()->subHours(6);

                $logs = ($rawLogsByEmployee->get($karyawanId) ?: collect())
                    ->filter(function (AttendanceLogModel $row) use ($windowStart, $windowEnd) {
                        if (! ($row->log_at instanceof Carbon)) {
                            return false;
                        }

                        return $row->log_at->between($windowStart, $windowEnd, true);
                    })
                    ->sortBy('log_at')
                    ->values();

                if ($logs->isEmpty()) {
                    return $fallback;
                }

                $isInLog = static function (AttendanceLogModel $row): bool {
                    $type = strtolower(trim((string) ($row->log_type ?? '')));

                    return in_array($type, ['in', 'check_in', 'checkin', '0'], true);
                };
                $isOutLog = static function (AttendanceLogModel $row): bool {
                    $type = strtolower(trim((string) ($row->log_type ?? '')));

                    return in_array($type, ['out', 'check_out', 'checkout', '1'], true);
                };

                $inLogs = $logs
                    ->filter(fn (AttendanceLogModel $row) => $isInLog($row) && $row->log_at->between($windowStart, $inWindowEnd, true))
                    ->values();
                $outLogs = $logs
                    ->filter(fn (AttendanceLogModel $row) => $isOutLog($row) && $row->log_at->between($outWindowStart, $windowEnd, true))
                    ->values();

                return [
                    'min_at' => ($inLogs->first() ?: $logs->first())->log_at->format('Y-m-d H:i:s'),
                    'max_at' => ($outLogs->last() ?: $logs->last())->log_at->format('Y-m-d H:i:s'),
                ];
            } catch (\Throwable $e) {
                return $fallback;
            }
        };

        $rows = collect();
        foreach ($pagedEmployees as $emp) {
            foreach ($periodDates as $dateKey) {
                $key = $emp['karyawan_id'].'|'.$dateKey;
                $customShiftIdForDate = isset($customScheduleMap[$key]) ? (int) $customScheduleMap[$key] : 0;
                $customShiftForDate = $customShiftIdForDate > 0 && $customShiftMap->has($customShiftIdForDate)
                    ? $customShiftMap->get($customShiftIdForDate)
                    : null;
                $review = $existing->get($key);
                $isHolidaySpecial = isset($holidaySpecialMap[$dateKey]);
                $holidayKind = $isHolidaySpecial
                    ? 'holiday_special'
                    : (isset($holidayMap[$dateKey])
                        ? (strcasecmp((string) ($holidayMap[$dateKey] ?? ''), 'Weekend') === 0 ? 'weekend' : 'holiday')
                        : null);
                $holidayDisplayName = $isHolidaySpecial
                    ? ($holidaySpecialMap[$dateKey] ?? $holidayMap[$dateKey] ?? 'Holiday Special')
                    : ($holidayMap[$dateKey] ?? null);

                // Contract window marker (per assignment): dates outside the contract should not be treated as alpha/no_log.
                $contractStart = ! empty($emp['contract_start_date'])
                    ? Carbon::parse((string) $emp['contract_start_date'])->startOfDay()
                    : null;
                $contractEnd = ! empty($emp['contract_end_date'])
                    ? Carbon::parse((string) $emp['contract_end_date'])->startOfDay()
                    : null;
                $workDate = Carbon::parse((string) $dateKey)->startOfDay();
                $contractState = 'active';
                if ($contractStart && $workDate->lt($contractStart)) {
                    $contractState = 'before';
                } elseif ($contractEnd && $workDate->gt($contractEnd)) {
                    $contractState = 'ended';
                }

                if ($contractState !== 'active') {
                    $contractCode = $contractState === 'before' ? 'BK' : 'KS';
                    $contractLabel = $contractState === 'before' ? 'Belum Mulai Kontrak' : 'Kontrak Selesai';
                    $calendarRawLog = $rawLogMinMaxMap[((int) ($emp['karyawan_id'] ?? 0)).'|'.$dateKey] ?? ['min_at' => null, 'max_at' => null];
                    $windowRawLog = $review ? $resolveRawLogByShiftWindow($review, $calendarRawLog) : $calendarRawLog;
                    $rawLogMinAtStr = $windowRawLog['min_at'] ?? null;
                    $rawLogMaxAtStr = $windowRawLog['max_at'] ?? null;

                    $rows->push([
                        'id' => $review ? (int) $review->id : null,
                        'karyawan_id' => (int) ($review?->karyawan_id ?? $emp['karyawan_id']),
                        'employee_code' => $review?->karyawan?->employee_code ?: $emp['employee_code'],
                        'finger_id' => $review?->karyawan?->finger_id ?: ($emp['finger_id'] ?? null),
                        'employee_name' => $review?->karyawan?->full_name ?: $emp['employee_name'],
                        'applied_shift_code' => (string) ($customShiftForDate->code ?? ($emp['applied_shift_code'] ?? '')),
                        'applied_shift_name' => (string) ($customShiftForDate->name ?? ($emp['applied_shift_name'] ?? '')),
                        'applied_shift_time' => $customShiftForDate
                            ? (substr((string) $customShiftForDate->start_time, 0, 5).'-'.substr((string) $customShiftForDate->end_time, 0, 5))
                            : (string) ($emp['applied_shift_time'] ?? ''),
                        'is_custom_schedule' => $customShiftForDate !== null,
                        'work_date' => $dateKey,
                        'is_holiday' => isset($holidayMap[$dateKey]),
                        'is_holiday_special' => $isHolidaySpecial,
                        'holiday_kind' => $holidayKind,
                        'holiday_name' => $holidayDisplayName,
                        'is_workday' => isset($workdayMap[$dateKey]),
                        'workday_name' => $workdayMap[$dateKey] ?? null,
                        'status' => $review ? (string) $review->status : 'no_log',
                        'effective_status' => $contractState === 'before' ? 'contract_not_started' : 'contract_ended',
                        'attendance_tag' => null,
                        'attendance_tag_label' => null,
                        'attendance_tag_notes' => null,
                        'attendance_tag_reference_id' => null,
                        'attendance_tag_status' => null,
                        'can_reject_hours' => false,
                        'can_restore_hours' => false,
                        'confidence_score' => $review ? (float) ($review->confidence_score ?? 0) : 0.0,
                        'checkin_at' => $review ? optional($review->checkin_at)->format('Y-m-d H:i:s') : null,
                        'checkout_at' => $review ? optional($review->checkout_at)->format('Y-m-d H:i:s') : null,
                        'suggested_checkin_at' => $review ? optional($review->suggested_checkin_at)->format('Y-m-d H:i:s') : null,
                        'suggested_checkout_at' => $review ? optional($review->suggested_checkout_at)->format('Y-m-d H:i:s') : null,
                        'raw_log_in_at' => $rawLogMinAtStr,
                        'raw_log_out_at' => $rawLogMaxAtStr,
                        'reason' => $contractLabel,
                        'needs_action' => false,
                        'overtime_auto_without_spl' => false,
                        'missing_spl_overtime' => false,
                        'missing_spl_overtime_minutes' => 0,
                        'needs_extend_spl' => false,
                        'extend_spl_minutes' => 0,
                        'auto_no_rest_normal_included' => false,
                        'needs_no_rest_normal_included' => false,
                        'no_rest_normal_included_minutes' => 0,
                        'auto_no_rest_skip_break' => false,
                        'needs_no_rest_skip_break' => false,
                        'no_rest_skip_break_minutes' => 0,
                        'is_approved' => true,
                        'offline_pending_count' => 0,
                        'offline_pending' => false,
                        'histories_count' => $review ? (int) ($review->histories_count ?? 0) : 0,
                        'contract_state' => $contractState,
                        'contract_code' => $contractCode,
                        'contract_label' => $contractLabel,
                        'contract_start_date' => $emp['contract_start_date'] ?? null,
                        'contract_end_date' => $emp['contract_end_date'] ?? null,
                    ]);

                    continue;
                }

                if ($review) {
                    $reasonRaw = (string) ($review->reason ?? '');
                    $needsAction = str_starts_with($reasonRaw, 'ACTION_REQUIRED::');
                    $attTag = $this->resolveAttendanceTag($dateKey, (int) $review->karyawan_id, $leaveApprovedMap, $overtimeTagMap, $forgettingClockTagMap);
                    $continuesBridge = $continuesNextDayMap[((int) $review->karyawan_id).'|'.$dateKey] ?? null;
                    $previousDateKey = Carbon::parse($dateKey)->subDay()->format('Y-m-d');
                    $previousReview = $existing->get(((int) $review->karyawan_id).'|'.$previousDateKey);
                    $manualCarryFromPrevious = $previousReview
                        && str_contains((string) ($previousReview->reason ?? ''), 'MANUAL_TIME_LOCK::')
                        && $previousReview->checkout_at
                        && Carbon::parse((string) $previousReview->checkout_at)->toDateString() === $dateKey;
                    $effectiveStatus = $attTag['tag_key'] === 'leave_approved'
                        ? 'leave_approved'
                        : ($attTag['tag_key'] === 'overtime_approved' && $review->status === 'no_log' ? 'overtime_approved' : $review->status);
                    if ($manualCarryFromPrevious) {
                        $effectiveStatus = 'continues_carry';
                        $reasonRaw = 'Sisa Cut 1 Day dari '.Carbon::parse($previousDateKey)->format('d/m/Y').'.';
                    } elseif (is_array($continuesBridge)) {
                        $bridgeLabel = $continuesBridge['mode'] === 'carry'
                            ? 'SPL Continue Carry'
                            : 'SPL ContinuesNextDay';
                        $bridgeReason = $this->buildContinuesNextDayReason($continuesBridge);
                        $reasonRaw = $bridgeReason;
                        $effectiveStatus = $continuesBridge['mode'] === 'carry'
                            ? 'continues_carry'
                            : 'continues_workday';
                        $attTag = [
                            'tag_key' => 'overtime_approved',
                            'tag_label' => $bridgeLabel,
                            'tag_notes' => $bridgeReason,
                            'reference_id' => $continuesBridge['reference_id'] ?? null,
                            'status' => 'approved',
                        ];
                    }
                    $hasAnyCustomSchedule = isset($customScheduleEmployeeIds[(int) $review->karyawan_id]);
                    $hasExplicitSchedule = isset($customScheduleMap[((int) $review->karyawan_id).'|'.$dateKey]) && (int) $customScheduleMap[((int) $review->karyawan_id).'|'.$dateKey] > 0;
                    $hasExplicitSchedule = $hasExplicitSchedule || (!$hasAnyCustomSchedule && trim((string) ($emp['applied_shift_time'] ?? '')) !== '');
                    if (!$hasExplicitSchedule) {
                        $effectiveStatus = 'waiting_schedule';
                        $reasonRaw = 'Belum ada jadwal master untuk tanggal ini.';
                        $needsAction = false;
                    }
                    $isOvertimeTagged = str_starts_with((string) ($attTag['tag_key'] ?? ''), 'overtime_');
                    $hasAttendanceHours = (bool) ($review->checkin_at || $review->checkout_at);
                    $canRejectHours = isset($holidayMap[$dateKey]) && ! $isOvertimeTagged && $hasAttendanceHours;
                    $canRestoreHours = isset($restorableReviewIdMap[(int) $review->id]) && ! $hasAttendanceHours;
                    $calendarRawLog = $rawLogMinMaxMap[((int) $review->karyawan_id).'|'.$dateKey] ?? ['min_at' => null, 'max_at' => null];
                    $windowRawLog = $resolveRawLogByShiftWindow($review, $calendarRawLog);
                    $rawLogMinAtStr = $windowRawLog['min_at'] ?? null;
                    $rawLogMaxAtStr = $windowRawLog['max_at'] ?? null;

                    // Penanda "overtime tanpa SPL" (agar operator tidak lupa membuat pengajuan SPL).
                    // Rule: jika jam OUT (raw) melebihi planned shift end dan TIDAK ada SPL apapun
                    // (draft/submitted/in_review/approved) pada tanggal tsb, maka tampilkan badge "Butuh SPL".
                    $missingSplOvertime = false;
                    $missingSplOvertimeMinutes = 0;
                    $splKey = ((int) $review->karyawan_id).'|'.$dateKey;
                    $hasAnySpl = isset($overtimeTagMap[$splKey]);
                    $autoOvertimeWithoutSpl = (bool) ($emp['overtime_auto_without_spl'] ?? false);
                    if (! $hasAnySpl && ! $autoOvertimeWithoutSpl) {
                        try {
                            $plannedEnd = $review->planned_shift_end ? Carbon::parse((string) $review->planned_shift_end) : null;
                            $rawOut = $rawLogMaxAtStr ?: ($review->suggested_checkout_at ?: $review->checkout_at);
                            $rawOutAt = $rawOut ? Carbon::parse((string) $rawOut) : null;
                            if ($plannedEnd && $rawOutAt && $rawOutAt->gt($plannedEnd)) {
                                $missingSplOvertimeMinutes = $plannedEnd->diffInMinutes($rawOutAt);
                                $threshold = (int) env('ATTENDANCE_MISSING_SPL_THRESHOLD_MINUTES', 30);
                                if ($threshold < 1) {
                                    $threshold = 1;
                                }
                                $missingSplOvertime = $missingSplOvertimeMinutes >= $threshold;
                            }
                        } catch (\Throwable $e) {
                            // ignore parsing errors
                        }
                    }

                    // Penanda "Butuh Extend SPL": jika SPL sudah approved tetapi jam OUT asli (raw) masih
                    // melewati batas window SPL approved (checkout di review akan ter-cut di window SPL).
                    // Ini untuk mengingatkan operator agar membuat Extend SPL (tambahan jam) bila memang lembur lebih lama.
                    $needsExtendSpl = false;
                    $extendSplMinutes = 0;
                    try {
                        $hasApprovedSpl = isset($overtimeApprovedMap[$splKey]);
                        if ($hasApprovedSpl && ! $autoOvertimeWithoutSpl) {
                            $shiftStart = $review->planned_shift_start ? Carbon::parse((string) $review->planned_shift_start) : null;
                            $shiftEnd = $review->planned_shift_end ? Carbon::parse((string) $review->planned_shift_end) : null;
                            $windows = $overtimeApprovedMap[$splKey] ?? [];
                            $approvedWindow = $this->resolveApprovedOvertimeWindowForShift($windows, $shiftStart, $shiftEnd);

                            $rawOut = $rawLogMaxAtStr ?: ($review->suggested_checkout_at ?: $review->checkout_at);
                            $rawOutAt = $rawOut ? Carbon::parse((string) $rawOut) : null;

                            if (
                                $rawOutAt
                                && ($approvedWindow['post_end'] ?? null) instanceof Carbon
                                && $rawOutAt->gt($approvedWindow['post_end'])
                            ) {
                                /** @var Carbon $postEnd */
                                $postEnd = $approvedWindow['post_end'];
                                $extendSplMinutes = $postEnd->diffInMinutes($rawOutAt);
                                $threshold = (int) env('ATTENDANCE_EXTEND_SPL_THRESHOLD_MINUTES', 30);
                                if ($threshold < 1) {
                                    $threshold = 1;
                                }
                                $needsExtendSpl = $extendSplMinutes >= $threshold;
                            }
                        }
                    } catch (\Throwable $e) {
                        // ignore parsing errors
                    }

                    $autoNoRestNormalIncluded = (bool) ($emp['auto_no_rest_normal_included'] ?? false);
                    $needsNoRestNormalIncluded = false;
                    $noRestNormalIncludedMinutes = 0;
                    $autoNoRestSkipBreak = (bool) ($emp['auto_no_rest_skip_break'] ?? false);
                    $needsNoRestSkipBreak = false;
                    $noRestSkipBreakMinutes = 0;
                    try {
                        $hasApprovedNoRestNormalIncluded = $this->hasApprovedOvertimeType(
                            $overtimeApprovedMap[$splKey] ?? [],
                            SuratPerintahLemburModel::OVERTIME_TYPE_NO_REST
                        );
                        $hasApprovedNoRestSkipBreak = $this->hasApprovedOvertimeType(
                            $overtimeApprovedMap[$splKey] ?? [],
                            defined(SuratPerintahLemburModel::class.'::OVERTIME_TYPE_NO_REST_SKIP_BREAK')
                                ? SuratPerintahLemburModel::OVERTIME_TYPE_NO_REST_SKIP_BREAK
                                : 'no_rest_skip_break'
                        );
                        $breakStartTime = (string) ($emp['applied_break_start_time'] ?? '');
                        $breakEndTime = (string) ($emp['applied_break_end_time'] ?? '');
                        if (
                            ($breakStartTime === '' || $breakEndTime === '')
                            && ! empty($review->planned_profil_jam_kerja_id)
                            && $plannedShiftMap->has((int) $review->planned_profil_jam_kerja_id)
                        ) {
                            $plannedShift = $plannedShiftMap->get((int) $review->planned_profil_jam_kerja_id);
                            $breakStartTime = (string) ($plannedShift->break_start_time ?? '');
                            $breakEndTime = (string) ($plannedShift->break_end_time ?? '');
                        }

                        $noRestDetection = ['candidate' => false, 'minutes' => 0];
                        if (
                            ($autoNoRestNormalIncluded || $autoNoRestSkipBreak)
                            && $effectiveStatus !== 'leave_approved'
                            && ! is_array($continuesBridge)
                        ) {
                            $noRestDetection = $this->detectNoRestSkipBreakCandidate(
                                $dateKey,
                                isset($workdayMap[$dateKey]) ? 'workday' : 'non_workday',
                                $breakStartTime,
                                $breakEndTime,
                                $rawLogMinAtStr,
                                $rawLogMaxAtStr
                            );
                        }
                        if ($autoNoRestNormalIncluded && ! $hasApprovedNoRestNormalIncluded) {
                            $needsNoRestNormalIncluded = (bool) ($noRestDetection['candidate'] ?? false);
                            $noRestNormalIncludedMinutes = (int) ($noRestDetection['minutes'] ?? 0);
                        }
                        if ($autoNoRestSkipBreak && ! $hasApprovedNoRestSkipBreak) {
                            $needsNoRestSkipBreak = (bool) ($noRestDetection['candidate'] ?? false);
                            $noRestSkipBreakMinutes = (int) ($noRestDetection['minutes'] ?? 0);
                        }
                    } catch (\Throwable $e) {
                        // ignore parsing errors
                    }

                    $appliedShiftCode = (string) ($emp['applied_shift_code'] ?? '');
                    $appliedShiftName = (string) ($emp['applied_shift_name'] ?? '');
                    $appliedShiftTime = (string) ($emp['applied_shift_time'] ?? '');
                    $customShiftId = isset($customScheduleMap[$splKey]) ? (int) $customScheduleMap[$splKey] : 0;
                    if ($customShiftId > 0 && $customShiftMap->has($customShiftId)) {
                        $customShift = $customShiftMap->get($customShiftId);
                        $appliedShiftCode = (string) ($customShift->code ?? '');
                        $appliedShiftName = (string) ($customShift->name ?? '');
                        $appliedShiftTime = substr((string) $customShift->start_time, 0, 5).'-'.substr((string) $customShift->end_time, 0, 5);
                    } elseif ($appliedShiftCode === '' && ! empty($review->planned_profil_jam_kerja_id) && $plannedShiftMap->has((int) $review->planned_profil_jam_kerja_id)) {
                        $plannedShift = $plannedShiftMap->get((int) $review->planned_profil_jam_kerja_id);
                        $appliedShiftCode = (string) ($plannedShift->code ?? '');
                        $appliedShiftName = (string) ($plannedShift->name ?? '');
                        $appliedShiftTime = substr((string) $plannedShift->start_time, 0, 5).'-'.substr((string) $plannedShift->end_time, 0, 5);
                    }

                    $pairingHint = null;
                    $isOffShift = strtolower(trim($appliedShiftCode)) === 'off'
                        && substr((string) $appliedShiftTime, 0, 5) === '00:00'
                        && substr((string) $appliedShiftTime, -5) === '00:00';
                    $isCrossDayShift = ! $isOffShift && (bool) ($review->is_cross_day ?? false);
                    $pairingRole = $this->resolveCrossDayPairingRole(
                        $dateKey,
                        $rawLogMinAtStr,
                        $rawLogMaxAtStr,
                        $isCrossDayShift,
                        is_array($continuesBridge) ? $continuesBridge : null
                    );
                    if ($isCrossDayShift) {
                        if ($pairingRole === 'anchor') {
                            $pairingHint = 'Anchor shift malam';
                        } elseif ($pairingRole === 'carry') {
                            $pairingHint = 'Carry dari shift semalam';
                        } elseif ($review->status === 'missing_in') {
                            $pairingHint = 'Cari IN dari shift semalam';
                        } elseif ($review->status === 'missing_out') {
                            $pairingHint = 'Cari OUT di hari berikutnya';
                        } elseif (! empty($rawLogMaxAtStr) && substr((string) $rawLogMaxAtStr, 0, 10) > $dateKey) {
                            $pairingHint = 'OUT berpasangan di +1 hari';
                        } elseif (! empty($rawLogMinAtStr) && substr((string) $rawLogMinAtStr, 0, 10) < $dateKey) {
                            $pairingHint = 'IN terbawa dari -1 hari';
                        } else {
                            $pairingHint = 'Pairing lintas hari';
                        }
                    }

                    $rows->push([
                        'id' => (int) $review->id,
                        'karyawan_id' => (int) $review->karyawan_id,
                        'employee_code' => $review->karyawan?->employee_code ?: $emp['employee_code'],
                        'finger_id' => $review->karyawan?->finger_id ?: ($emp['finger_id'] ?? null),
                        'employee_name' => $review->karyawan?->full_name ?: $emp['employee_name'],
                        'applied_shift_code' => $appliedShiftCode,
                        'applied_shift_name' => $appliedShiftName,
                        'applied_shift_time' => $hasExplicitSchedule ? $appliedShiftTime : '',
                        'is_custom_schedule' => $customShiftId > 0,
                        'work_date' => $dateKey,
                        'is_holiday' => isset($holidayMap[$dateKey]),
                        'is_holiday_special' => $isHolidaySpecial,
                        'holiday_kind' => $holidayKind,
                        'holiday_name' => $holidayDisplayName,
                        'is_workday' => isset($workdayMap[$dateKey]),
                        'workday_name' => $workdayMap[$dateKey] ?? null,
                        'status' => $hasExplicitSchedule ? $review->status : 'waiting_schedule',
                        'effective_status' => $effectiveStatus,
                        'attendance_tag' => $attTag['tag_key'],
                        'attendance_tag_label' => $attTag['tag_label'],
                        'attendance_tag_notes' => $attTag['tag_notes'],
                        'attendance_tag_reference_id' => $attTag['reference_id'] ?? null,
                        'attendance_tag_status' => $attTag['status'] ?? null,
                        'can_reject_hours' => $canRejectHours,
                        'can_restore_hours' => $canRestoreHours,
                        'confidence_score' => (float) ($review->confidence_score ?? 0),
                        'checkin_at' => optional($review->checkin_at)->format('Y-m-d H:i:s'),
                        'checkout_at' => optional($review->checkout_at)->format('Y-m-d H:i:s'),
                        'suggested_checkin_at' => optional($review->suggested_checkin_at)->format('Y-m-d H:i:s'),
                        'suggested_checkout_at' => optional($review->suggested_checkout_at)->format('Y-m-d H:i:s'),
                        'planned_shift_start' => $hasExplicitSchedule && $review->planned_shift_start ? Carbon::parse((string) $review->planned_shift_start)->format('Y-m-d H:i:s') : null,
                        'planned_shift_end' => $hasExplicitSchedule && $review->planned_shift_end ? Carbon::parse((string) $review->planned_shift_end)->format('Y-m-d H:i:s') : null,
                        'is_cross_day' => $isCrossDayShift,
                        'pairing_role' => $manualCarryFromPrevious ? 'carry' : $pairingRole,
                        'pairing_hint' => $manualCarryFromPrevious ? 'Sisa Cut 1 Day / '.($rawLogMaxAtStr ? Carbon::parse($rawLogMaxAtStr)->minute >= 30 ? Carbon::parse($rawLogMaxAtStr)->copy()->addHour()->format('H:00') : Carbon::parse($rawLogMaxAtStr)->format('H:00') : '-') : $pairingHint,
                        'raw_log_in_at' => $rawLogMinAtStr,
                        'raw_log_out_at' => $rawLogMaxAtStr,
                        'reason' => $reasonRaw,
                        'needs_action' => $needsAction,
                        'overtime_auto_without_spl' => $autoOvertimeWithoutSpl,
                        'missing_spl_overtime' => $missingSplOvertime,
                        'missing_spl_overtime_minutes' => (int) $missingSplOvertimeMinutes,
                        'needs_extend_spl' => (bool) $needsExtendSpl,
                        'extend_spl_minutes' => (int) $extendSplMinutes,
                        'auto_no_rest_normal_included' => $autoNoRestNormalIncluded,
                        'needs_no_rest_normal_included' => $needsNoRestNormalIncluded,
                        'no_rest_normal_included_minutes' => $noRestNormalIncludedMinutes,
                        'auto_no_rest_skip_break' => $autoNoRestSkipBreak,
                        'needs_no_rest_skip_break' => $needsNoRestSkipBreak,
                        'no_rest_skip_break_minutes' => $noRestSkipBreakMinutes,
                        'is_approved' => (bool) $review->is_approved,
                        'offline_pending_count' => (int) ($offlinePendingMap[((int) $review->karyawan_id).'|'.$dateKey] ?? 0),
                        'offline_pending' => (int) ($offlinePendingMap[((int) $review->karyawan_id).'|'.$dateKey] ?? 0) > 0,
                        'histories_count' => (int) ($review->histories_count ?? 0),
                        'contract_state' => 'active',
                        'contract_code' => null,
                        'contract_label' => null,
                        'contract_start_date' => $emp['contract_start_date'] ?? null,
                        'contract_end_date' => $emp['contract_end_date'] ?? null,
                    ]);

                    continue;
                }

                $attTag = $this->resolveAttendanceTag($dateKey, (int) $emp['karyawan_id'], $leaveApprovedMap, $overtimeTagMap, $forgettingClockTagMap);
                $continuesBridge = $continuesNextDayMap[((int) $emp['karyawan_id']).'|'.$dateKey] ?? null;
                $effectiveStatus = $attTag['tag_key'] === 'leave_approved'
                    ? 'leave_approved'
                    : ($attTag['tag_key'] === 'overtime_approved' ? 'overtime_approved' : 'no_log');
                $reasonTextNoReview = 'Belum proses detection.';
                if (is_array($continuesBridge)) {
                    $bridgeLabel = $continuesBridge['mode'] === 'carry'
                        ? 'SPL Continue Carry'
                        : 'SPL ContinuesNextDay';
                    $bridgeReason = $this->buildContinuesNextDayReason($continuesBridge);
                    $effectiveStatus = $continuesBridge['mode'] === 'carry'
                        ? 'continues_carry'
                        : 'continues_workday';
                    $reasonTextNoReview = $bridgeReason;
                    $attTag = [
                        'tag_key' => 'overtime_approved',
                        'tag_label' => $bridgeLabel,
                        'tag_notes' => $bridgeReason,
                        'reference_id' => $continuesBridge['reference_id'] ?? null,
                        'status' => 'approved',
                    ];
                }

                $rawLogMinAtStr = $rawLogMinMaxMap[((int) $emp['karyawan_id']).'|'.$dateKey]['min_at'] ?? null;
                $rawLogMaxAtStr = $rawLogMinMaxMap[((int) $emp['karyawan_id']).'|'.$dateKey]['max_at'] ?? null;
                $customShiftId = isset($customScheduleMap[((int) $emp['karyawan_id']).'|'.$dateKey]) ? (int) $customScheduleMap[((int) $emp['karyawan_id']).'|'.$dateKey] : 0;
                $displayShiftCode = (string) ($emp['applied_shift_code'] ?? '');
                $displayShiftName = (string) ($emp['applied_shift_name'] ?? '');
                $displayShiftTime = (string) ($emp['applied_shift_time'] ?? '');
                $plannedShiftStart = null;
                $plannedShiftEnd = null;
                $isCrossDayShift = false;
                if ($customShiftId > 0 && $customShiftMap->has($customShiftId)) {
                    $customShift = $customShiftMap->get($customShiftId);
                    $displayShiftCode = (string) ($customShift->code ?? '');
                    $displayShiftName = (string) ($customShift->name ?? '');
                    $displayShiftTime = substr((string) $customShift->start_time, 0, 5).'-'.substr((string) $customShift->end_time, 0, 5);
                    $plannedShiftStart = $dateKey.' '.substr((string) $customShift->start_time, 0, 8);
                    $plannedShiftEnd = $dateKey.' '.substr((string) $customShift->end_time, 0, 8);
                    $isCrossDayShift = substr((string) $customShift->end_time, 0, 8) <= substr((string) $customShift->start_time, 0, 8);
                    if ($isCrossDayShift) {
                        $plannedShiftEnd = Carbon::parse((string) $plannedShiftEnd)->addDay()->format('Y-m-d H:i:s');
                    }
                }
                $pairingRole = $this->resolveCrossDayPairingRole(
                    $dateKey,
                    $rawLogMinAtStr,
                    $rawLogMaxAtStr,
                    $isCrossDayShift,
                    is_array($continuesBridge) ? $continuesBridge : null
                );
                $pairingHint = $isCrossDayShift
                    ? match ($pairingRole) {
                        'anchor' => 'Anchor shift malam',
                        'carry' => 'Carry dari shift semalam',
                        default => 'Shift malam lintas hari',
                    }
                : null;

                $rows->push([
                    'id' => null,
                    'karyawan_id' => (int) $emp['karyawan_id'],
                    'employee_code' => $emp['employee_code'],
                    'finger_id' => $emp['finger_id'] ?? null,
                    'employee_name' => $emp['employee_name'],
                    'applied_shift_code' => $displayShiftCode,
                    'applied_shift_name' => $displayShiftName,
                    'applied_shift_time' => $displayShiftTime,
                    'is_custom_schedule' => $customShiftId > 0,
                    'work_date' => $dateKey,
                    'is_holiday' => isset($holidayMap[$dateKey]),
                    'is_holiday_special' => $isHolidaySpecial,
                    'holiday_kind' => $holidayKind,
                    'holiday_name' => $holidayDisplayName,
                    'is_workday' => isset($workdayMap[$dateKey]),
                    'workday_name' => $workdayMap[$dateKey] ?? null,
                    'status' => 'no_log',
                    'effective_status' => $effectiveStatus,
                    'attendance_tag' => $attTag['tag_key'],
                    'attendance_tag_label' => $attTag['tag_label'],
                    'attendance_tag_notes' => $attTag['tag_notes'],
                    'attendance_tag_reference_id' => $attTag['reference_id'] ?? null,
                    'attendance_tag_status' => $attTag['status'] ?? null,
                    'can_reject_hours' => false,
                    'can_restore_hours' => false,
                    'confidence_score' => 0.0,
                    'checkin_at' => null,
                    'checkout_at' => null,
                    'suggested_checkin_at' => null,
                    'suggested_checkout_at' => null,
                    'planned_shift_start' => $plannedShiftStart,
                    'planned_shift_end' => $plannedShiftEnd,
                    'is_cross_day' => $isCrossDayShift,
                    'pairing_role' => $pairingRole,
                    'pairing_hint' => $pairingHint,
                    'raw_log_in_at' => $rawLogMinAtStr,
                    'raw_log_out_at' => $rawLogMaxAtStr,
                    'reason' => $reasonTextNoReview,
                    'needs_action' => false,
                    'overtime_auto_without_spl' => false,
                    'missing_spl_overtime' => false,
                    'missing_spl_overtime_minutes' => 0,
                    'needs_extend_spl' => false,
                    'extend_spl_minutes' => 0,
                    'auto_no_rest_normal_included' => false,
                    'needs_no_rest_normal_included' => false,
                    'no_rest_normal_included_minutes' => 0,
                    'auto_no_rest_skip_break' => false,
                    'needs_no_rest_skip_break' => false,
                    'no_rest_skip_break_minutes' => 0,
                    'is_approved' => false,
                    'offline_pending_count' => (int) ($offlinePendingMap[((int) $emp['karyawan_id']).'|'.$dateKey] ?? 0),
                    'offline_pending' => (int) ($offlinePendingMap[((int) $emp['karyawan_id']).'|'.$dateKey] ?? 0) > 0,
                    'histories_count' => 0,
                    'contract_state' => 'active',
                    'contract_code' => null,
                    'contract_label' => null,
                    'contract_start_date' => $emp['contract_start_date'] ?? null,
                    'contract_end_date' => $emp['contract_end_date'] ?? null,
                ]);
            }
        }

        $rows = $rows
            ->sortBy([
                ['work_date', 'desc'],
                ['employee_code', 'asc'],
            ])
            ->values();

        if ($request->boolean('urgency_shadow') && $rows->isNotEmpty() && Schema::hasTable('attendance_urgency_records')) {
            $shadowMap = AttendanceUrgencyRecordModel::query()
                ->where('profil_bulan_id', $profilId)
                ->whereIn('karyawan_id', $employeeIds)
                ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
                ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
                ->whereIn('status', ['active', 'needs_review'])
                ->get()
                ->groupBy(fn ($record) => ((int) $record->karyawan_id).'|'.$record->work_date->format('Y-m-d'));
            $rows = $rows->map(function (array $row) use ($shadowMap): array {
                $records = $shadowMap->get(((int) $row['karyawan_id']).'|'.$row['work_date'], collect());
                $shadowIn = $records->firstWhere('clock_type', 'in');
                $shadowOut = $records->firstWhere('clock_type', 'out');
                $row['display_checkin_at'] = $row['checkin_at'] ?: optional($shadowIn?->planned_at)->format('Y-m-d H:i:s');
                $row['display_checkout_at'] = $row['checkout_at'] ?: optional($shadowOut?->planned_at)->format('Y-m-d H:i:s');
                $row['urgency_shadow_applied'] = (!$row['checkin_at'] && $shadowIn) || (!$row['checkout_at'] && $shadowOut);
                $row['urgency_shadow_status'] = $records->contains('status', 'needs_review') ? 'needs_review' : ($records->isNotEmpty() ? 'active' : null);
                return $row;
            });
        }
        return response()->json([
            'data' => $rows,
            'meta' => [
                'holiday_map' => $holidayMap,
                'holiday_special_map' => $holidaySpecialMap,
                'workday_map' => $workdayMap,
                'date_from' => $effectiveStart->format('Y-m-d'),
                'date_to' => $effectiveEnd->format('Y-m-d'),
                'status_filter' => $statusFilter,
                'leave_map_count' => count($leaveApprovedMap),
                'overtime_map_count' => count($overtimeTagMap),
                'forgetting_clock_map_count' => count($forgettingClockTagMap),
                'missing_assignment' => $missingAssignment,
                'missing_assignment_employee' => $missingAssignmentEmployee
                    ? [
                        'id' => (int) $missingAssignmentEmployee->id,
                        'employee_code' => $missingAssignmentEmployee->employee_code,
                        'finger_id' => $missingAssignmentEmployee->finger_id,
                        'employee_name' => $missingAssignmentEmployee->full_name,
                    ]
                    : null,
                'pagination' => [
                    'page' => $page,
                    'per_page' => $perPage,
                    'total_employees' => $totalEmployees,
                    'total_pages' => (int) ceil($totalEmployees / max(1, $perPage)),
                ],
            ],
        ]);
    }

    // =========================================================================
    // exportReviews() - Export data review ke file
    // Dipanggil dari: GET /attendance-review/reviews-export
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function exportReviews(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['required_without:karyawan_id', 'array', 'min:1', 'max:50'],
            'karyawan_ids.*' => ['integer', 'distinct', 'exists:master_karyawans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
            'format' => ['nullable', 'in:excel,pdf'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $exportData = $this->buildReviewExportData(
            (int) $request->input('profil_bulan_id'),
            $request->filled('karyawan_id') ? (int) $request->input('karyawan_id') : null,
            $request->filled('date_from') ? Carbon::parse($request->input('date_from'))->startOfDay() : null,
            $request->filled('date_to') ? Carbon::parse($request->input('date_to'))->startOfDay() : null
        );
        if (! $exportData['ok']) {
            return response()->json(['message' => $exportData['message'] ?: 'Gagal export.'], 422);
        }

        $profil = $exportData['profil'];
        $effectiveStart = $exportData['effective_start'];
        $effectiveEnd = $exportData['effective_end'];
        $exportRows = $exportData['rows'];
        $printGroups = $exportData['print_groups'] ?? [];

        $format = (string) $request->input('format', 'excel');
        if ($format === 'pdf') {
            $rowCount = count($exportRows);
            $serverPdfLimit = (int) env('ATTENDANCE_REVIEW_SERVER_PDF_ROW_LIMIT', 600);
            $forceServerPdf = $request->boolean('server_pdf', false);

            if (! $forceServerPdf && ($rowCount > $serverPdfLimit || ! $request->filled('karyawan_id'))) {
                return response()->view('attendancereview::exports.reviews_pdf', [
                    'rows' => $exportRows,
                    'profil' => $profil,
                    'date_from' => $effectiveStart->format('Y-m-d'),
                    'date_to' => $effectiveEnd->format('Y-m-d'),
                    'generated_at' => now()->format('Y-m-d H:i:s'),
                    'print_mode' => true,
                    'auto_print' => true,
                    'row_count' => $rowCount,
                    'print_groups' => $printGroups,
                ]);
            }

            $pdf = Pdf::loadView('attendancereview::exports.reviews_pdf', [
                'rows' => $exportRows,
                'profil' => $profil,
                'date_from' => $effectiveStart->format('Y-m-d'),
                'date_to' => $effectiveEnd->format('Y-m-d'),
                'generated_at' => now()->format('Y-m-d H:i:s'),
                'print_mode' => false,
                'auto_print' => false,
                'row_count' => $rowCount,
                'print_groups' => $printGroups,
            ])->setPaper('a4', 'landscape');

            $filename = 'attendance-review-'.now()->format('Ymd-His').'.pdf';

            return $pdf->download($filename);
        }

        $filename = 'attendance-review-'.now()->format('Ymd-His').'.xlsx';

        return Excel::download(new AttendanceReviewExport($exportRows), $filename);
    }

    // =========================================================================
    // exportActualRecordsExcel() - Export record aktual ke Excel
    // Dipanggil dari: GET /attendance-review/reviews-export-actual-excel
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function exportActualRecordsExcel(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['nullable', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['required_without:karyawan_id', 'array', 'min:1', 'max:50'],
            'karyawan_ids.*' => ['integer', 'distinct', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['nullable', 'array'],
            'karyawan_ids.*' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'finger_numbers' => ['nullable', 'string', 'max:10000'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
            'profile_scope' => ['nullable', 'string', 'in:all,both,main,sub,selected'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profilId = $request->filled('profil_bulan_id') ? (int) $request->input('profil_bulan_id') : 0;
        $profil = $profilId > 0 ? ProfilBulanModel::query()->findOrFail($profilId) : null;
        $profileScope = (string) $request->input('profile_scope', 'selected');
        $profileScope = $profileScope === 'all' ? 'both' : $profileScope;
        if ($profileScope === 'selected' && ! $profil) {
            return response()->json(['message' => 'Profil Bulan wajib dipilih untuk scope profil terpilih.'], 422);
        }

        $dateFromInput = trim((string) $request->input('date_from', ''));
        $dateToInput = trim((string) $request->input('date_to', ''));
        $filterDateFrom = $dateFromInput !== '' ? Carbon::parse($dateFromInput) : null;
        $filterDateTo = $dateToInput !== '' ? Carbon::parse($dateToInput) : null;
        if ($filterDateFrom && preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateFromInput)) {
            $filterDateFrom->startOfDay();
        }
        if ($filterDateTo && preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateToInput)) {
            $filterDateTo->endOfDay();
        }
        if (! $profil && (! $filterDateFrom || ! $filterDateTo)) {
            return response()->json(['message' => 'Dari Tanggal dan Sampai Tanggal wajib diisi.'], 422);
        }

        if ($profil) {
            $periodStart = Carbon::parse($profil->start_date)->startOfDay();
            $periodEnd = Carbon::parse($profil->end_date)->endOfDay();
            $effectiveStart = $filterDateFrom && $filterDateFrom->gt($periodStart) ? $filterDateFrom->copy() : $periodStart->copy();
            $effectiveEnd = $filterDateTo && $filterDateTo->lt($periodEnd) ? $filterDateTo->copy() : $periodEnd->copy();
            $scopeProfilIds = $profileScope === 'selected'
                ? collect([$profilId])
                : collect($this->summaryProfileIds($profil, $profileScope));
        } else {
            $effectiveStart = $filterDateFrom->copy();
            $effectiveEnd = $filterDateTo->copy();
            $scopeProfilIds = ProfilBulanModel::query()
                ->whereDate('start_date', '<=', $effectiveEnd->toDateString())
                ->whereDate('end_date', '>=', $effectiveStart->toDateString())
                ->when($profileScope === 'main', fn ($q) => $q->where(function ($kind) {
                    $kind->whereNull('profile_kind')
                        ->orWhereRaw("LOWER(TRIM(COALESCE(profile_kind, ''))) <> 'sub'");
                }))
                ->when($profileScope === 'sub', fn ($q) => $q->where('profile_kind', 'sub'))
                ->pluck('id')
                ->map(fn ($id) => (int) $id)
                ->values();
        }

        if ($effectiveStart->gt($effectiveEnd)) {
            return response()->json(['message' => 'Rentang tanggal tidak valid.'], 422);
        }

        $fingerNumbers = collect(preg_split('/[\s,;\t]+/', trim((string) $request->input('finger_numbers', ''))) ?: [])
            ->map(fn ($value) => trim((string) $value))
            ->filter()
            ->unique()
            ->values();
        $filterKaryawanIds = $this->resolveAttendanceReviewKaryawanIds($request);
        if ($fingerNumbers->isNotEmpty()) {
            $employeeIds = KaryawanModel::query()
                ->where(function ($query) use ($fingerNumbers): void {
                    $query->whereIn('finger_id', $fingerNumbers->all())
                        ->orWhereIn('employee_code', $fingerNumbers->all());
                })
                ->where('is_active', true)
                ->pluck('id')
                ->map(fn ($id) => (int) $id)
                ->unique()
                ->values();
        } elseif (! empty($filterKaryawanIds)) {
            $employeeIds = collect($filterKaryawanIds)
                ->map(fn ($id) => (int) $id)
                ->filter(fn ($id) => $id > 0)
                ->unique()
                ->values();
        } else {
            $employeeIds = ProfilBulanKaryawanModel::query()
                ->whereIn('profil_bulan_id', $scopeProfilIds->all())
                ->where('is_active', true)
                ->pluck('karyawan_id')
                ->map(fn ($id) => (int) $id)
                ->filter(fn ($id) => $id > 0)
                ->unique()
                ->values();
        }

        if ($employeeIds->isEmpty()) {
            return response()->json(['message' => 'Tidak ada user terfilter untuk diexport.'], 422);
        }

        $rows = AttendanceLogModel::query()
            ->with('karyawan:id,employee_code,finger_id,full_name')
            ->whereIn('karyawan_id', $employeeIds->all())
            ->whereBetween('log_at', [$effectiveStart, $effectiveEnd])
            ->where('is_active', true)
            ->orderByDesc('log_at')
            ->orderBy('karyawan_id')
            ->get(['karyawan_id', 'employee_code', 'finger_id', 'log_at', 'log_type', 'device_code', 'validation_reason', 'notes'])
            ->map(function (AttendanceLogModel $row) {
                $acNo = trim((string) ($row->finger_id ?: $row->employee_code ?: $row->karyawan?->finger_id ?: $row->karyawan?->employee_code ?: ''));
                $employeeCode = trim((string) ($row->employee_code ?: $row->karyawan?->employee_code ?: $row->finger_id ?: $row->karyawan?->finger_id ?: ''));
                $displayName = trim((string) ($row->karyawan?->full_name ?: ''));
                $logType = strtolower(trim((string) ($row->log_type ?? 'unknown')));
                $state = match ($logType) {
                    'in' => 'C/In',
                    'out' => 'C/Out',
                    default => 'C/Unknown',
                };

                return [
                    $acNo,
                    $employeeCode !== '' ? $employeeCode : $acNo,
                    '',
                    $row->log_at instanceof Carbon ? $row->log_at->format('d/m/Y H:i') : '',
                    $state,
                    '',
                    '',
                    trim((string) ($row->device_code ?: '')),
                ];
            })
            ->values()
            ->all();

        $selectedUserLabel = count($filterKaryawanIds) === 1 ? ('-'.(string) $filterKaryawanIds[0]) : '';
        $filename = 'attendance_actual_record'.$selectedUserLabel.'_'.$effectiveStart->format('Y-m-d').'-'.$effectiveEnd->format('Y-m-d').'.xlsx';

        return Excel::download(new AttendanceActualRecordExport($rows), $filename);
    }
    public function exportForgettingClockApprovedExcel(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['nullable', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['required_without:karyawan_id', 'array', 'min:1', 'max:50'],
            'karyawan_ids.*' => ['integer', 'distinct', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['nullable', 'array'],
            'karyawan_ids.*' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'finger_numbers' => ['nullable', 'string', 'max:10000'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
            'profile_scope' => ['nullable', 'string', 'in:all,both,main,sub,selected'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profilId = $request->filled('profil_bulan_id') ? (int) $request->input('profil_bulan_id') : 0;
        $profil = $profilId > 0 ? ProfilBulanModel::query()->findOrFail($profilId) : null;
        $profileScope = (string) $request->input('profile_scope', 'selected');
        $profileScope = $profileScope === 'all' ? 'both' : $profileScope;
        if ($profileScope === 'selected' && ! $profil) {
            return response()->json(['message' => 'Profil Bulan wajib dipilih untuk scope profil terpilih.'], 422);
        }

        $dateFromInput = trim((string) $request->input('date_from', ''));
        $dateToInput = trim((string) $request->input('date_to', ''));
        $effectiveStart = $dateFromInput !== '' ? Carbon::parse($dateFromInput)->startOfDay() : null;
        $effectiveEnd = $dateToInput !== '' ? Carbon::parse($dateToInput)->endOfDay() : null;
        if ($profil) {
            $periodStart = Carbon::parse($profil->start_date)->startOfDay();
            $periodEnd = Carbon::parse($profil->end_date)->endOfDay();
            $effectiveStart = $effectiveStart && $effectiveStart->gt($periodStart) ? $effectiveStart : $periodStart;
            $effectiveEnd = $effectiveEnd && $effectiveEnd->lt($periodEnd) ? $effectiveEnd : $periodEnd;
            $scopeProfilIds = $profileScope === 'selected' ? collect([$profilId]) : collect($this->summaryProfileIds($profil, $profileScope));
        } elseif (! $effectiveStart || ! $effectiveEnd) {
            return response()->json(['message' => 'Dari Tanggal dan Sampai Tanggal wajib diisi.'], 422);
        } else {
            $scopeProfilIds = ProfilBulanModel::query()
                ->whereDate('start_date', '<=', $effectiveEnd->toDateString())
                ->whereDate('end_date', '>=', $effectiveStart->toDateString())
                ->pluck('id');
        }

        $filterKaryawanIds = $this->resolveAttendanceReviewKaryawanIds($request);
        $fingerNumbers = collect(preg_split('/[\s,;\t]+/', trim((string) $request->input('finger_numbers', ''))) ?: [])->filter()->unique()->values();
        if ($fingerNumbers->isNotEmpty()) {
            $employeeIds = KaryawanModel::query()
                ->whereIn('finger_id', $fingerNumbers->all())
                ->orWhereIn('employee_code', $fingerNumbers->all())
                ->pluck('id');
        } elseif (! empty($filterKaryawanIds)) {
            $employeeIds = collect($filterKaryawanIds);
        } else {
            $employeeIds = ProfilBulanKaryawanModel::query()
                ->whereIn('profil_bulan_id', collect($scopeProfilIds)->all())
                ->where('is_active', true)
                ->pluck('karyawan_id');
        }
        $employeeIds = collect($employeeIds)->map(fn ($id) => (int) $id)->filter()->unique()->values();
        if ($employeeIds->isEmpty()) {
            return response()->json(['message' => 'Tidak ada user terfilter untuk diexport.'], 422);
        }

        $actualRows = AttendanceLogModel::query()
            ->with('karyawan:id,employee_code,finger_id,full_name')
            ->whereIn('karyawan_id', $employeeIds->all())
            ->whereBetween('log_at', [$effectiveStart, $effectiveEnd])
            ->where('is_active', true)
            ->orderByDesc('log_at')
            ->orderBy('karyawan_id')
            ->get(['karyawan_id', 'employee_code', 'finger_id', 'log_at', 'log_type', 'device_code'])
            ->map(function (AttendanceLogModel $row) {
                $acNo = trim((string) ($row->finger_id ?: $row->employee_code ?: $row->karyawan?->finger_id ?: $row->karyawan?->employee_code ?: ''));
                $employeeCode = trim((string) ($row->employee_code ?: $row->karyawan?->employee_code ?: $acNo));
                $state = match (strtolower(trim((string) ($row->log_type ?? 'unknown')))) {
                    'in' => 'C/In',
                    'out' => 'C/Out',
                    default => 'C/Unknown',
                };

                return [
                    $acNo,
                    $employeeCode,
                    '',
                    $row->log_at instanceof Carbon ? $row->log_at->format('d/m/Y H:i') : '',
                    $state,
                    '',
                    '',
                    trim((string) ($row->device_code ?? '')),
                ];
            });

        $forgettingClockRows = ForgettingClockRequestModel::query()
            ->with([
                'karyawan:id,employee_code,finger_id,full_name',
                'approvalRequest.steps.approver:id,name',
                'approvalRequest.steps.approverKaryawan:id,full_name',
            ])
            ->whereIn('karyawan_id', $employeeIds->all())
            ->whereDate('work_date', '>=', $effectiveStart->toDateString())
            ->whereDate('work_date', '<=', $effectiveEnd->toDateString())
            ->where('status', 'approved')
            ->where('is_active', true)
            ->orderBy('work_date')
            ->orderBy('karyawan_id')
            ->get()
            ->flatMap(function (ForgettingClockRequestModel $row) {
                $acNo = trim((string) ($row->karyawan?->finger_id ?: $row->karyawan?->employee_code ?: ''));
                $employeeCode = trim((string) ($row->karyawan?->employee_code ?: $acNo));
                $approvedStep = $row->approvalRequest?->steps
                    ?->where('status', 'approved')
                    ->sortByDesc(fn ($step) => $step->acted_at?->timestamp ?? $step->step_order ?? 0)
                    ->first();
                $approver = trim((string) ($approvedStep?->approver?->name ?: $approvedStep?->approverKaryawan?->full_name ?: ''));
                $operation = $approver !== '' ? $approver : 'FC Approved';
                $rows = [];

                if ($row->requested_checkin_at) {
                    $rows[] = [
                        $acNo,
                        $employeeCode,
                        '',
                        $row->requested_checkin_at->format('d/m/Y H:i'),
                        'C/In',
                        '',
                        '',
                        $operation,
                    ];
                }
                if ($row->requested_checkout_at) {
                    $rows[] = [
                        $acNo,
                        $employeeCode,
                        '',
                        $row->requested_checkout_at->format('d/m/Y H:i'),
                        'C/Out',
                        '',
                        '',
                        $operation,
                    ];
                }

                return $rows;
            });

        $rows = $actualRows->concat($forgettingClockRows)->values()->all();
        $filename = 'attendance_actual_inc_lupa_finger_approved_'.$effectiveStart->format('Y-m-d').'-'.$effectiveEnd->format('Y-m-d').'.xlsx';

        return Excel::download(new AttendanceActualRecordExport($rows), $filename);
    }

    // =========================================================================
    // sendReviewsExport() - Kirim export review via email
    // Dipanggil dari: POST /attendance-review/reviews-export/send
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function sendReviewsExport(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['required_without:karyawan_id', 'array', 'min:1', 'max:50'],
            'karyawan_ids.*' => ['integer', 'distinct', 'exists:master_karyawans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
            'channel' => ['required', 'in:email,wa'],
            'recipient' => ['required', 'string', 'max:500'],
            'subject' => ['nullable', 'string', 'max:200'],
            'message' => ['nullable', 'string', 'max:5000'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $exportData = $this->buildReviewExportData(
            (int) $request->input('profil_bulan_id'),
            $request->filled('karyawan_id') ? (int) $request->input('karyawan_id') : null,
            $request->filled('date_from') ? Carbon::parse($request->input('date_from'))->startOfDay() : null,
            $request->filled('date_to') ? Carbon::parse($request->input('date_to'))->startOfDay() : null
        );
        if (! $exportData['ok']) {
            return response()->json(['message' => $exportData['message'] ?: 'Data export tidak valid.'], 422);
        }

        $profil = $exportData['profil'];
        $effectiveStart = $exportData['effective_start'];
        $effectiveEnd = $exportData['effective_end'];
        $exportRows = $exportData['rows'];
        $printGroups = $exportData['print_groups'] ?? [];

        $pdfBinary = Pdf::loadView('attendancereview::exports.reviews_pdf', [
            'rows' => $exportRows,
            'print_groups' => $printGroups,
            'profil' => $profil,
            'date_from' => $effectiveStart->format('Y-m-d'),
            'date_to' => $effectiveEnd->format('Y-m-d'),
            'generated_at' => now()->format('Y-m-d H:i:s'),
            'print_mode' => false,
            'auto_print' => false,
            'row_count' => count($exportRows),
        ])->setPaper('a4', 'landscape')->output();

        $filename = 'attendance-review-'.$profil->code.'-'.$effectiveStart->format('Ymd').'-'.$effectiveEnd->format('Ymd').'.pdf';
        $channel = (string) $request->input('channel');

        if ($channel === 'email') {
            $recipients = collect(explode(',', (string) $request->input('recipient')))
                ->map(fn ($email) => strtolower(trim((string) $email)))
                ->filter(fn ($email) => $email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL))
                ->unique()
                ->values()
                ->all();
            if (count($recipients) === 0) {
                return response()->json(['message' => 'Email tujuan tidak valid.'], 422);
            }

            $subject = trim((string) $request->input('subject', ''));
            if ($subject === '') {
                $subject = '[AHSP] Attendance Review '.($profil->code ?: '');
            }
            $body = trim((string) $request->input('message', ''));
            if ($body === '') {
                $body = 'Terlampir PDF Attendance Review untuk periode '
                    .$effectiveStart->format('Y-m-d').' s/d '.$effectiveEnd->format('Y-m-d').'.';
            }

            Mail::raw($body, function ($message) use ($recipients, $subject, $pdfBinary, $filename): void {
                $message->to($recipients)
                    ->subject($subject)
                    ->attachData($pdfBinary, $filename, ['mime' => 'application/pdf']);
            });

            return response()->json([
                'message' => 'PDF berhasil dikirim ke email.',
                'data' => [
                    'channel' => 'email',
                    'recipients' => $recipients,
                    'filename' => $filename,
                ],
            ]);
        }

        $waBaseUrl = trim((string) (AppSetting::query()->where('key', 'login.wa_base_url')->value('value') ?: ''));
        $waApiKey = trim((string) (AppSetting::query()->where('key', 'login.wa_api_key')->value('value') ?: ''));
        $waSender = trim((string) (AppSetting::query()->where('key', 'login.wa_sender')->value('value') ?: ''));
        $waDeviceId = trim((string) (AppSetting::query()->where('key', 'login.wa_device_id')->value('value') ?: ''));
        $waDelay = (int) (AppSetting::query()->where('key', 'login.wa_delay_seconds')->value('value') ?: 0);
        $waRetry = (int) (AppSetting::query()->where('key', 'login.wa_retry_count')->value('value') ?: 0);
        $waRetryDelay = (int) (AppSetting::query()->where('key', 'login.wa_retry_delay_seconds')->value('value') ?: 5);

        if ($waBaseUrl === '' || $waApiKey === '') {
            return response()->json([
                'message' => 'WA Gateway belum dikonfigurasi. Isi Login Settings: WA Base URL dan WA API Key.',
            ], 422);
        }

        $waTarget = trim((string) $request->input('recipient', ''));
        if ($waTarget === '') {
            return response()->json(['message' => 'Nomor WhatsApp tujuan wajib diisi.'], 422);
        }

        $messageText = trim((string) $request->input('message', ''));
        if ($messageText === '') {
            $messageText = "Laporan Attendance Review\n"
                ."Profil: {$profil->code} - {$profil->name}\n"
                .'Periode: '.$effectiveStart->format('Y-m-d').' s/d '.$effectiveEnd->format('Y-m-d')."\n"
                .'Jumlah baris: '.count($exportRows)."\n"
                .'PDF tersedia di dashboard AHSP (menu Attendance Review).';
        }

        $payload = [
            'target' => $waTarget,
            'message' => $messageText,
            'sender' => $waSender,
            'device_id' => $waDeviceId,
            'delay' => $waDelay,
            'retry' => $waRetry,
            'retry_delay' => $waRetryDelay,
        ];

        $waResp = Http::withToken($waApiKey)
            ->acceptJson()
            ->post(rtrim($waBaseUrl, '/').'/send', $payload);

        if (! $waResp->successful()) {
            return response()->json([
                'message' => 'Gagal kirim WhatsApp ke gateway.',
                'data' => [
                    'status' => $waResp->status(),
                    'response' => $waResp->json() ?: $waResp->body(),
                ],
            ], 422);
        }

        return response()->json([
            'message' => 'Notifikasi WhatsApp berhasil dikirim.',
            'data' => [
                'channel' => 'wa',
                'recipient' => $waTarget,
                'provider_response' => $waResp->json() ?: $waResp->body(),
            ],
        ]);
    }

    // =========================================================================
    // buildReviewExportData() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildReviewExportData(int $profilId, ?int $karyawanId, ?Carbon $filterDateFrom, ?Carbon $filterDateTo): array
    {
        $profil = ProfilBulanModel::query()->findOrFail($profilId);

        $periodStart = Carbon::parse($profil->start_date)->startOfDay();
        $periodEnd = Carbon::parse($profil->end_date)->startOfDay();
        $effectiveStart = $filterDateFrom && $filterDateFrom->gt($periodStart) ? $filterDateFrom->copy() : $periodStart->copy();
        $effectiveEnd = $filterDateTo && $filterDateTo->lt($periodEnd) ? $filterDateTo->copy() : $periodEnd->copy();

        if ($effectiveStart->gt($effectiveEnd)) {
            return ['ok' => false, 'message' => 'Rentang tanggal tidak valid.'];
        }

        $query = AttendanceDailyReviewModel::query()
            ->with('karyawan:id,employee_code,full_name,employee_group')
            ->where('profil_bulan_id', $profilId)
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'));

        if ($karyawanId) {
            $query->where('karyawan_id', $karyawanId);
        }

        $rows = $query
            ->orderBy('work_date')
            ->orderBy('karyawan_id')
            ->get();

        $employeeIds = $rows->pluck('karyawan_id')->filter()->map(fn ($id) => (int) $id)->unique()->values();
        $exportGroupByEmployee = [];
        if ($employeeIds->isNotEmpty() && Schema::hasColumn('master_profil_bulan_karyawans', 'export_employee_group')) {
            $exportGroupByEmployee = ProfilBulanKaryawanModel::query()
                ->where('profil_bulan_id', $profilId)
                ->whereIn('karyawan_id', $employeeIds)
                ->pluck('export_employee_group', 'karyawan_id')
                ->map(fn ($value) => trim((string) $value))
                ->all();
        }
        $calendarMarks = $this->buildCalendarMarks($effectiveStart->copy(), $effectiveEnd->copy());
        $holidayMap = $calendarMarks['holiday_map'];
        $workdayMap = $calendarMarks['workday_map'];
        $holidaySpecialMap = $calendarMarks['holiday_special_map'] ?? [];
        $leaveApprovedMap = $this->buildLeaveApprovedMap($employeeIds, $effectiveStart->copy(), $effectiveEnd->copy());
        $overtimeTagMap = $this->buildOvertimeTagMap($employeeIds, $effectiveStart->copy(), $effectiveEnd->copy());
        $forgettingClockTagMap = $this->buildForgettingClockTagMap($employeeIds, $effectiveStart->copy(), $effectiveEnd->copy());

        $structuredRows = [];
        foreach ($rows as $row) {
            $dateKey = optional($row->work_date)->format('Y-m-d');
            $attTag = $dateKey
                ? $this->resolveAttendanceTag($dateKey, (int) $row->karyawan_id, $leaveApprovedMap, $overtimeTagMap, $forgettingClockTagMap)
                : ['tag_label' => null, 'tag_key' => null];
            $calendarLabel = '-';
            if ($dateKey && isset($holidaySpecialMap[$dateKey])) {
                $calendarLabel = 'Holiday Special - '.$holidaySpecialMap[$dateKey];
            } elseif ($dateKey && isset($holidayMap[$dateKey])) {
                $calendarLabel = 'Libur - '.$holidayMap[$dateKey];
            } elseif ($dateKey && isset($workdayMap[$dateKey])) {
                $calendarLabel = 'Workday - '.$workdayMap[$dateKey];
            }

            $employeeId = (int) ($row->karyawan_id ?? 0);
            $employeeCode = (string) ($row->karyawan?->employee_code ?: '-');
            $employeeName = (string) ($row->karyawan?->full_name ?: '-');
            $exportGroup = trim((string) ($exportGroupByEmployee[$employeeId] ?? ''));
            $employeeGroup = trim((string) ($row->karyawan?->employee_group ?? ''));
            $groupLabel = $exportGroup !== '' ? $exportGroup : ($employeeGroup !== '' ? $employeeGroup : 'Tanpa Group');
            $cells = [
                $dateKey ?: '-',
                $employeeCode,
                $employeeName,
                $calendarLabel,
                $row->status ?: 'no_log',
                $attTag['tag_label'] ?: '-',
                optional($row->checkin_at)->format('Y-m-d H:i:s') ?: '-',
                optional($row->checkout_at)->format('Y-m-d H:i:s') ?: '-',
                optional($row->suggested_checkin_at)->format('Y-m-d H:i:s') ?: '-',
                optional($row->suggested_checkout_at)->format('Y-m-d H:i:s') ?: '-',
                number_format((float) ($row->confidence_score ?? 0), 2, '.', ''),
                $row->reason ?: '-',
                $row->is_approved ? 'Yes' : 'No',
            ];
            $structuredRows[] = [
                'group' => $groupLabel,
                'employee_id' => $employeeId,
                'employee_code' => $employeeCode,
                'employee_name' => $employeeName,
                'date' => $dateKey ?: '',
                'cells' => $cells,
            ];
        }
        $structuredRows = collect($structuredRows)
            ->sortBy([
                ['group', 'asc'],
                ['employee_code', 'asc'],
                ['employee_name', 'asc'],
                ['date', 'asc'],
            ])
            ->values();
        $exportRows = $structuredRows->pluck('cells')->values()->all();
        $printGroups = $structuredRows
            ->groupBy('group')
            ->map(function ($groupRows, string $groupName) {
                return [
                    'group' => $groupName,
                    'employees' => $groupRows
                        ->groupBy(fn ($row) => ((int) ($row['employee_id'] ?? 0)).'|'.($row['employee_code'] ?? '').'|'.($row['employee_name'] ?? ''))
                        ->map(function ($employeeRows) {
                            $first = $employeeRows->first();

                            return [
                                'employee_code' => (string) ($first['employee_code'] ?? '-'),
                                'employee_name' => (string) ($first['employee_name'] ?? '-'),
                                'rows' => $employeeRows->pluck('cells')->values()->all(),
                            ];
                        })
                        ->values()
                        ->all(),
                ];
            })
            ->values()
            ->all();

        return [
            'ok' => true,
            'profil' => $profil,
            'effective_start' => $effectiveStart,
            'effective_end' => $effectiveEnd,
            'rows' => $exportRows,
            'print_groups' => $printGroups,
        ];
    }

    // =========================================================================
    // calculationData() - Data kalkulasi untuk DataTable
    // Dipanggil dari: GET /attendance-review/calculations
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function calculationData(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['required_without:karyawan_id', 'array', 'min:1', 'max:50'],
            'karyawan_ids.*' => ['integer', 'distinct', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['nullable', 'array'],
            'karyawan_ids.*' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
            'draw' => ['nullable', 'integer'],
            'start' => ['nullable', 'integer', 'min:0'],
            'length' => ['nullable', 'integer', 'min:1', 'max:100'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profilId = (int) $request->input('profil_bulan_id');
        $profil = ProfilBulanModel::query()->findOrFail($profilId);
        $profileScope = (string) $request->input('profile_scope', 'selected');
        $profileScope = $profileScope === 'all' ? 'both' : $profileScope;
        $scopeProfilIds = $profileScope === 'selected'
            ? [$profilId]
            : $this->summaryProfileIds($profil, $profileScope);
        $filterKaryawanIds = $this->resolveAttendanceReviewKaryawanIds($request);

        $periodStart = Carbon::parse($profil->start_date)->startOfDay();
        $periodEnd = Carbon::parse($profil->end_date)->startOfDay();
        $filterDateFrom = $request->filled('date_from') ? Carbon::parse($request->input('date_from'))->startOfDay() : null;
        $filterDateTo = $request->filled('date_to') ? Carbon::parse($request->input('date_to'))->startOfDay() : null;
        $effectiveStart = $filterDateFrom && $filterDateFrom->gt($periodStart) ? $filterDateFrom : $periodStart->copy();
        $effectiveEnd = $filterDateTo && $filterDateTo->lt($periodEnd) ? $filterDateTo : $periodEnd->copy();

        if ($effectiveStart->gt($effectiveEnd)) {
            return response()->json(['data' => [], 'meta' => ['summary' => []]]);
        }

        $assignmentsQuery = ProfilBulanKaryawanModel::query()
            ->with('karyawan:id,employee_code,full_name')
            ->whereIn('profil_bulan_id', $scopeProfilIds)
            ->where('is_active', true);
        if (! empty($filterKaryawanIds)) {
            $assignmentsQuery->whereIn('karyawan_id', $filterKaryawanIds);
        }
        $searchValue = trim((string) data_get($request->input('search'), 'value', ''));
        if ($searchValue !== '') {
            $assignmentsQuery->whereHas('karyawan', function ($q) use ($searchValue): void {
                $q->where('employee_code', 'like', '%'.$searchValue.'%')
                    ->orWhere('full_name', 'like', '%'.$searchValue.'%');
            });
        }

        $isDataTables = $request->filled('draw');
        $recordsFiltered = (clone $assignmentsQuery)->count();
        if ($isDataTables) {
            $start = max(0, (int) $request->input('start', 0));
            $length = min(100, max(1, (int) $request->input('length', 10)));
            $assignmentsQuery->skip($start)->take($length);
        }
        $assignments = $assignmentsQuery->get();
        $filteredOutEmployeeCount = ! empty($filterKaryawanIds)
            ? max(0, count($filterKaryawanIds) - $assignments->pluck('karyawan_id')->filter()->map(fn ($id) => (int) $id)->unique()->count())
            : 0;
        if ($assignments->isEmpty()) {
            $emptyPayload = [
                'data' => [],
                'meta' => [
                    'filtered_employee_count' => count($filterKaryawanIds),
                    'filtered_out_employee_count' => $filteredOutEmployeeCount,
                    'summary' => [
                        'employees' => 0,
                        'days_present' => 0,
                        'actual_hours' => 0,
                        'normal_hours' => 0,
                        'overtime_hours' => 0,
                        'weighted_overtime_hours' => 0,
                    ],
                ],
            ];
            if ($isDataTables) {
                $emptyPayload['draw'] = (int) $request->input('draw', 0);
                $emptyPayload['recordsTotal'] = 0;
                $emptyPayload['recordsFiltered'] = 0;
            }

            return response()->json($emptyPayload);
        }

        $employeeIds = $assignments->pluck('karyawan_id')->filter()->map(fn ($id) => (int) $id)->unique()->values();
        $assignmentByEmployee = $assignments->keyBy(fn ($row) => (int) $row->karyawan_id);

        if (
            ! $request->filled('date_from')
            && ! $request->filled('date_to')
            && $employeeIds->isNotEmpty()
        ) {
            $dateBounds = AttendanceDailyReviewModel::query()
                ->whereIn('profil_bulan_id', $scopeProfilIds)
                ->whereIn('karyawan_id', $employeeIds)
                ->selectRaw('MIN(work_date) as min_work_date, MAX(work_date) as max_work_date')
                ->first();
            if (! empty($dateBounds?->min_work_date) && ! empty($dateBounds?->max_work_date)) {
                $actualStart = Carbon::parse($dateBounds->min_work_date)->startOfDay();
                $actualEnd = Carbon::parse($dateBounds->max_work_date)->startOfDay();
                if ($actualStart->lte($actualEnd)) {
                    $effectiveStart = $actualStart;
                    $effectiveEnd = $actualEnd;
                }
            }
        }

        $reviewRows = AttendanceDailyReviewModel::query()
            ->whereIn('profil_bulan_id', $scopeProfilIds)
            ->whereIn('karyawan_id', $employeeIds)
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->get()
            ->groupBy(fn (AttendanceDailyReviewModel $row) => ((int) $row->karyawan_id).'|'.optional($row->work_date)->format('Y-m-d'));
        $plannedShiftProfileIds = $reviewRows->flatten()
            ->pluck('planned_profil_jam_kerja_id')
            ->filter()
            ->map(fn ($id) => (int) $id)
            ->unique()
            ->values();
        $workMinutesPerDayMap = [];
        $plannedShiftMetaMap = [];
        if ($plannedShiftProfileIds->isNotEmpty()) {
            $plannedShiftProfiles = ProfilJamKerjaModel::query()
                ->whereIn('id', $plannedShiftProfileIds)
                ->get(['id', 'code', 'name', 'start_time', 'end_time', 'break_start_time', 'break_end_time', 'work_minutes_per_day']);
            $workMinutesPerDayMap = $plannedShiftProfiles
                ->pluck('work_minutes_per_day', 'id')
                ->map(fn ($v) => (int) $v)
                ->all();
            $plannedShiftMetaMap = $plannedShiftProfiles
                ->mapWithKeys(fn ($row) => [
                    (int) $row->id => [
                        'code' => (string) ($row->code ?? ''),
                        'name' => (string) ($row->name ?? ''),
                        'start_time' => $row->start_time ? substr((string) $row->start_time, 0, 8) : null,
                        'end_time' => $row->end_time ? substr((string) $row->end_time, 0, 8) : null,
                        'break_start_time' => $row->break_start_time ? substr((string) $row->break_start_time, 0, 8) : null,
                        'break_end_time' => $row->break_end_time ? substr((string) $row->break_end_time, 0, 8) : null,
                        'work_minutes_per_day' => (int) ($row->work_minutes_per_day ?? 0),
                    ],
                ])
                ->all();
        }

        $calendarMarks = $this->buildCalendarMarks($effectiveStart->copy(), $effectiveEnd->copy());
        $holidayMap = $calendarMarks['holiday_map'] ?? [];
        $workdayMap = $calendarMarks['workday_map'] ?? [];
        $holidaySpecialMap = $calendarMarks['holiday_special_map'] ?? [];
        $overtimeApprovedMap = $this->buildOvertimeApprovedMap($employeeIds, $effectiveStart->copy(), $effectiveEnd->copy());

        $profileIds = $assignments->pluck('profil_perkalian_jam_id')->filter()->map(fn ($id) => (int) $id)->unique()->values();
        $rulesByProfile = [];
        if ($profileIds->isNotEmpty()) {
            $rulesByProfile = ProfilPerkalianJamDetailModel::query()
                ->whereIn('profil_perkalian_jam_id', $profileIds)
                ->where('is_active', true)
                ->orderBy('sort_order')
                ->orderBy('hour_start')
                ->get()
                ->groupBy('profil_perkalian_jam_id')
                ->map(function ($rows) {
                    return $rows->map(fn ($row) => [
                        'day_type' => (string) $row->day_type,
                        'hour_start' => (float) ($row->hour_start ?? 0),
                        'hour_end' => (float) ($row->hour_end ?? 0),
                        'multiplier' => (float) ($row->multiplier ?? 1),
                        'is_break' => (bool) ($row->is_break ?? false),
                    ])->values()->all();
                })
                ->all();
        }
        $globalOtColumns = collect($rulesByProfile)
            ->flatMap(fn ($rows) => collect($rows)->pluck('multiplier'))
            ->filter(fn ($v) => is_numeric($v))
            ->map(fn ($v) => (float) $v)
            ->unique()
            ->sort()
            ->values()
            ->map(function (float $v) {
                $key = number_format($v, 1, '.', '');

                return [
                    'key' => $key,
                    'multiplier' => $v,
                    'label' => 'OT x'.rtrim(rtrim(number_format($v, 2, '.', ''), '0'), '.'),
                ];
            })
            ->values();
        if ($globalOtColumns->isEmpty()) {
            $globalOtColumns = collect([1.5, 2.0, 3.0, 4.0])->map(function (float $v) {
                $key = number_format($v, 1, '.', '');

                return [
                    'key' => $key,
                    'multiplier' => $v,
                    'label' => 'OT x'.rtrim(rtrim(number_format($v, 2, '.', ''), '0'), '.'),
                ];
            });
        }
        $globalOtColumnKeys = $globalOtColumns->pluck('key')->values();

        $periodDates = collect(CarbonPeriod::create($effectiveStart->copy(), $effectiveEnd->copy()))
            ->map(fn (Carbon $date) => $date->format('Y-m-d'))
            ->values();

        $result = [];
        $dailyRows = [];
        foreach ($employeeIds as $karyawanId) {
            $assignment = $assignmentByEmployee->get((int) $karyawanId);
            if (! $assignment) {
                continue;
            }

            $detailData = $this->buildCalculationDetailPayload([
                'profil_bulan_id' => $profilId,
                'assignment_profil_bulan_id' => (int) ($assignment->profil_bulan_id ?? 0),
                'karyawan_id' => (int) $karyawanId,
                'date_from' => $effectiveStart->format('Y-m-d'),
                'date_to' => $effectiveEnd->format('Y-m-d'),
            ]);
            $detailRows = is_array($detailData['rows'] ?? null) ? (array) $detailData['rows'] : [];
            $detailOtColumns = $globalOtColumns->values()->all();
            $detailOtColumns = is_array($detailData['otColumns'] ?? null) ? (array) $detailData['otColumns'] : $detailOtColumns;

            $summarySnapshot = $this->summarizeCalculationDetailRowsForReview($detailRows, $detailOtColumns, $profil);
            foreach ($detailRows as $detailRow) {
                if (! (bool) ($detailRow['is_approved'] ?? false)) {
                    continue;
                }
                $dailyRows[] = [
                    'work_date' => (string) ($detailRow['work_date'] ?? ''),
                    'karyawan_id' => (int) $karyawanId,
                    'employee_code' => $assignment->karyawan?->employee_code,
                    'employee_name' => $assignment->karyawan?->full_name,
                    'day_type' => (string) ($detailRow['day_type'] ?? 'workday'),
                    'actual_hours' => round((float) ($detailRow['actual_hours'] ?? 0), 2),
                    'normal_hours' => round((float) ($detailRow['normal_hours'] ?? 0), 2),
                    'overtime_hours' => round((float) ($detailRow['overtime_hours'] ?? 0), 2),
                    'overtime_hours_gross' => round((float) ($detailRow['overtime_hours_gross'] ?? 0), 2),
                    'overtime_break_hours' => round((float) ($detailRow['overtime_break_hours'] ?? 0), 2),
                    'weighted_overtime_hours' => round((float) ($detailRow['weighted_overtime_hours'] ?? 0), 2),
                    'ot_dynamic' => collect($globalOtColumnKeys)->mapWithKeys(
                        fn ($k) => [$k => round((float) (($detailRow['ot_dynamic'] ?? [])[$k] ?? 0), 2)]
                    )->all(),
                    'is_approved' => true,
                ];
            }

            $result[] = [
                'karyawan_id' => (int) $karyawanId,
                'employee_code' => $assignment->karyawan?->employee_code,
                'employee_name' => $assignment->karyawan?->full_name,
                'days_present' => round((float) ($summarySnapshot['days_present'] ?? 0), 2),
                'actual_hours' => round((float) ($summarySnapshot['actual_hours'] ?? 0), 2),
                'normal_hours' => round((float) ($summarySnapshot['normal_hours'] ?? 0), 2),
                'overtime_hours' => round((float) ($summarySnapshot['overtime_hours'] ?? 0), 2),
                'weighted_overtime_hours' => round((float) ($summarySnapshot['weighted_overtime_hours'] ?? 0), 2),
                'ot_dynamic' => collect($globalOtColumnKeys)->mapWithKeys(
                    fn ($k) => [$k => round((float) (($summarySnapshot['ot_dynamic'] ?? [])[$k] ?? 0), 2)]
                )->all(),
                'profil_perkalian_jam_id' => $assignment->profil_perkalian_jam_id ? (int) $assignment->profil_perkalian_jam_id : null,
            ];
        }

        $summary = [
            'employees' => count($result),
            'days_present' => array_sum(array_column($result, 'days_present')),
            'actual_hours' => round(array_sum(array_column($result, 'actual_hours')), 2),
            'normal_hours' => round(array_sum(array_column($result, 'normal_hours')), 2),
            'overtime_hours' => round(array_sum(array_column($result, 'overtime_hours')), 2),
            'weighted_overtime_hours' => round(array_sum(array_column($result, 'weighted_overtime_hours')), 2),
        ];

        $payload = [
            'data' => collect($result)->sortBy([['employee_code', 'asc'], ['employee_name', 'asc']])->values(),
            'meta' => [
                'date_from' => $effectiveStart->format('Y-m-d'),
                'date_to' => $effectiveEnd->format('Y-m-d'),
                'filtered_employee_count' => count($filterKaryawanIds),
                'filtered_out_employee_count' => $filteredOutEmployeeCount,
                'summary' => $summary,
                'ot_columns' => $globalOtColumns->values(),
                'daily_rows' => collect($dailyRows)->sortBy([['work_date', 'asc'], ['employee_code', 'asc']])->values(),
            ],
        ];
        if ($isDataTables) {
            $payload['draw'] = (int) $request->input('draw', 0);
            $payload['recordsTotal'] = (int) $recordsFiltered;
            $payload['recordsFiltered'] = (int) $recordsFiltered;
        }

        return response()->json($payload);
    }

    // =========================================================================
    // summarizeCalculationDetailRowsForReview() - Meringkas data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function summarizeCalculationDetailRowsForReview(array $rows, array $otColumns, ProfilBulanModel $profil): array
    {
        $hkBasis = (int) ($profil->hk_basis ?? 21);
        $hkHoursPerDay = (float) ($profil->jam_per_hari ?? 8);
        $hkBaseHours = $hkBasis * $hkHoursPerDay;
        $resolveAttendanceDayCredit = static fn (array $detailRow): array => AttendanceDayCreditResolver::resolve(
            $detailRow,
            $profil,
            $hkHoursPerDay
        );

        $sumActualHours = 0.0;
        $sumOvertime = 0.0;
        $sumWeightedOvertime = 0.0;
        $otTotals = [];
        foreach ($otColumns as $otCol) {
            $key = (string) ($otCol['key'] ?? '');
            if ($key !== '') {
                $otTotals[$key] = 0.0;
            }
        }

        foreach ($rows as $row) {
            $sumActualHours += (float) ($row['actual_hours'] ?? 0);
            $sumOvertime += (float) ($row['overtime_hours'] ?? 0);
            $sumWeightedOvertime += (float) ($row['weighted_overtime_hours'] ?? 0);
            foreach ((array) ($row['ot_dynamic'] ?? []) as $key => $value) {
                if (! isset($otTotals[$key])) {
                    $otTotals[$key] = 0.0;
                }
                $otTotals[$key] += (float) $value;
            }
        }

        $totalDeficitHours = 0.0;
        foreach ($rows as $row) {
            $dayCredit = $resolveAttendanceDayCredit((array) $row);
            if ((int) ($dayCredit['hk_flag'] ?? 0) !== 1 && (float) ($dayCredit['deficit_hours'] ?? 0) <= 0) {
                continue;
            }
            $totalDeficitHours += max(0.0, (float) ($dayCredit['deficit_hours'] ?? 0));
        }

        $jamMasukNormal = max(0.0, $hkBaseHours - $totalDeficitHours);
        $hkMasuk = $hkHoursPerDay > 0 ? ($jamMasukNormal / $hkHoursPerDay) : 0.0;

        return [
            'days_present' => round($hkMasuk, 2),
            'actual_hours' => round($sumActualHours, 2),
            'normal_hours' => round($jamMasukNormal, 2),
            'overtime_hours' => round($sumOvertime, 2),
            'weighted_overtime_hours' => round($sumWeightedOvertime, 2),
            'ot_dynamic' => collect($otTotals)->map(fn ($value) => round((float) $value, 2))->all(),
        ];
    }

    // =========================================================================
    // buildCalculationDetailContextPayload() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildCalculationDetailContextPayload(
        ProfilBulanModel $profil,
        ProfilBulanKaryawanModel $assignment,
        Carbon $effectiveStart,
        Carbon $effectiveEnd
    ): array {
        $profilId = (int) $profil->id;
        $karyawanId = (int) $assignment->karyawan_id;
        $payableRule = $this->resolveAssignmentPayableRule($assignment);
        $hkHoursPerDay = (float) ($profil->jam_per_hari ?? 8);
        $hkMinutesPerDay = (int) round($hkHoursPerDay * 60);

        $overtimeRuleMode = 'legacy';
                $rules = [];
        $beforeRules = [];
        if ($assignment->profil_perkalian_jam_id) {
            $overtimeRuleMode = (string) (DB::table('master_profil_perkalian_jams')
                ->where('id', (int) $assignment->profil_perkalian_jam_id)
                ->value('overtime_rule_mode') ?? 'legacy');
        }
        if ($assignment->profil_perkalian_jam_id) {
            $rules = ProfilPerkalianJamDetailModel::query()
                ->where('profil_perkalian_jam_id', (int) $assignment->profil_perkalian_jam_id)
                ->where('is_active', true)
                ->orderBy('sort_order')
                ->orderBy('hour_start')
                ->get()
                ->map(fn ($row) => [
                    'day_type' => (string) $row->day_type,
                    'overtime_segment' => (string) ($row->overtime_segment ?? ''),
                    'hour_start' => (float) ($row->hour_start ?? 0),
                    'hour_end' => (float) ($row->hour_end ?? 0),
                    'multiplier' => (float) ($row->multiplier ?? 1),
                    'is_break' => (bool) ($row->is_break ?? false),
                ])
                ->values()
                ->all();
        }
        $beforeRules = collect($rules)
            ->filter(fn (array $rule) => ($rule['overtime_segment'] ?? '') === 'before')
            ->values()->all();
        $legacyRules = collect($rules)
            ->filter(fn (array $rule) => ($rule['overtime_segment'] ?? '') !== 'before' && ($rule['overtime_segment'] ?? '') !== 'after')
            ->values()->all();
        $otColumns = collect($this->resolveOvertimeColumnsFromRules($legacyRules));

        $reviews = AttendanceDailyReviewModel::query()
            ->where('profil_bulan_id', $profilId)
            ->where('karyawan_id', $karyawanId)
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->orderBy('work_date')
            ->get()
            ->keyBy(fn ($row) => optional($row->work_date)->format('Y-m-d'));
        $pendingCount = $reviews->filter(fn ($row) => ! (bool) $row->is_approved)->count();
        $calendarMarks = $this->buildCalendarMarks($effectiveStart->copy(), $effectiveEnd->copy());
        $holidayMap = $calendarMarks['holiday_map'] ?? [];
        $workdayMap = $calendarMarks['workday_map'] ?? [];
        $holidaySpecialMap = $calendarMarks['holiday_special_map'] ?? [];
        $leaveApprovedMap = $this->buildLeaveApprovedMap(collect([$karyawanId]), $effectiveStart->copy(), $effectiveEnd->copy());
        $overtimeApprovedMap = $this->buildOvertimeApprovedMap(collect([$karyawanId]), $effectiveStart->copy(), $effectiveEnd->copy());
        $continuesNextDayMap = $this->buildContinuesNextDayBridgeMap(collect([$karyawanId]), $effectiveStart->copy(), $effectiveEnd->copy());
        $employeeLogs = AttendanceLogModel::query()
            ->where('karyawan_id', $karyawanId)
            ->where('log_at', '>=', $effectiveStart->copy()->subDay()->startOfDay())
            ->where('log_at', '<=', $effectiveEnd->copy()->addDay()->endOfDay())
            ->orderBy('log_at')
            ->get()
            ->map(function (AttendanceLogModel $row) {
                if ($row->log_at instanceof Carbon) {
                    return $row;
                }
                $row->log_at = $row->log_at ? Carbon::parse((string) $row->log_at) : null;

                return $row;
            })
            ->filter(fn (AttendanceLogModel $row) => $row->log_at instanceof Carbon)
            ->values();

        $customScheduleRows = DB::table('master_shift_schedules')
            ->where('karyawan_id', $karyawanId)
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->where('is_active', true)
            ->where(function ($q) use ($profil): void {
                $q->whereNull('profil_bulan_id')
                    ->orWhere('profil_bulan_id', (int) $profil->id);
            })
            ->orderByRaw(
                'CASE
                    WHEN profil_bulan_id = ? AND is_locked = 1 THEN 1
                    WHEN profil_bulan_id = ? AND is_locked = 0 THEN 2
                    WHEN profil_bulan_id IS NULL AND is_locked = 1 THEN 3
                    ELSE 4
                END ASC',
                [(int) $profil->id, (int) $profil->id]
            )
            ->orderByDesc('id')
            ->get(['work_date', 'profil_jam_kerja_id']);
        $customScheduleMap = [];
        $customScheduleEmployeeIds = [];
        $customShiftIds = [];
        foreach ($customScheduleRows as $row) {
            $mapDateKey = Carbon::parse((string) $row->work_date)->format('Y-m-d');
            if (isset($customScheduleMap[$mapDateKey])) {
                continue;
            }
            $shiftId = (int) ($row->profil_jam_kerja_id ?? 0);
            if ($shiftId <= 0) {
                continue;
            }
            $customScheduleMap[$mapDateKey] = $shiftId;
            $customShiftIds[$shiftId] = $shiftId;
        }
        $customShiftMap = collect();
        if (! empty($customShiftIds)) {
            $customShiftMap = ProfilJamKerjaModel::query()
                ->whereIn('id', array_values($customShiftIds))
                ->get(['id', 'code', 'name', 'start_time', 'end_time', 'break_start_time', 'break_end_time', 'work_minutes_per_day'])
                ->keyBy('id');
        }

        $plannedShiftProfileIds = $reviews
            ->pluck('planned_profil_jam_kerja_id')
            ->filter()
            ->map(fn ($id) => (int) $id)
            ->unique()
            ->values();
        $workMinutesPerDayMap = [];
        $plannedShiftMetaMap = [];
        if ($plannedShiftProfileIds->isNotEmpty()) {
            $plannedShiftProfiles = ProfilJamKerjaModel::query()
                ->whereIn('id', $plannedShiftProfileIds)
                ->get(['id', 'code', 'name', 'start_time', 'end_time', 'break_start_time', 'break_end_time', 'work_minutes_per_day']);
            $workMinutesPerDayMap = $plannedShiftProfiles
                ->pluck('work_minutes_per_day', 'id')
                ->map(fn ($v) => (int) $v)
                ->all();
            $plannedShiftMetaMap = $plannedShiftProfiles
                ->mapWithKeys(fn ($row) => [
                    (int) $row->id => [
                        'code' => (string) ($row->code ?? ''),
                        'name' => (string) ($row->name ?? ''),
                        'start_time' => $row->start_time ? substr((string) $row->start_time, 0, 8) : null,
                        'end_time' => $row->end_time ? substr((string) $row->end_time, 0, 8) : null,
                        'break_start_time' => $row->break_start_time ? substr((string) $row->break_start_time, 0, 8) : null,
                        'break_end_time' => $row->break_end_time ? substr((string) $row->break_end_time, 0, 8) : null,
                        'work_minutes_per_day' => (int) ($row->work_minutes_per_day ?? 0),
                    ],
                ])
                ->all();
        }

        $rows = [];
        foreach (CarbonPeriod::create($effectiveStart->copy(), $effectiveEnd->copy()) as $date) {
            $dateKey = $date->format('Y-m-d');
            try {
                /** @var AttendanceDailyReviewModel|null $review */
                $review = $reviews->get($dateKey);
                $dayType = $this->resolveDayTypeForCalculation($dateKey, $holidayMap, $workdayMap, $holidaySpecialMap);
                $resolvedShift = $this->resolveAssignedShiftForDate($assignment, $date->copy());
                $resolvedShiftModel = $resolvedShift['shift'] ?? null;
                $customShiftId = (int) ($customScheduleMap[$dateKey] ?? 0);
                $customShiftModel = $customShiftId > 0 ? $customShiftMap->get($customShiftId) : null;
                $plannedShiftProfileId = $review?->planned_profil_jam_kerja_id ? (int) $review->planned_profil_jam_kerja_id : null;
                $plannedShiftMeta = $plannedShiftProfileId && isset($plannedShiftMetaMap[$plannedShiftProfileId])
                    ? $plannedShiftMetaMap[$plannedShiftProfileId]
                    : null;
                $activeShiftModel = $customShiftModel ?: ($plannedShiftMeta ? (object) $plannedShiftMeta : $resolvedShiftModel);

                $activeShiftCode = trim((string) ($activeShiftModel->code ?? ($plannedShiftMeta['code'] ?? '')));
                $activeShiftName = trim((string) ($activeShiftModel->name ?? ($plannedShiftMeta['name'] ?? '')));
                $plannedIn = $review?->planned_shift_start
                    ? Carbon::parse($review->planned_shift_start)->format('H:i')
                    : (($activeShiftModel && ! empty($activeShiftModel->start_time)) ? substr((string) $activeShiftModel->start_time, 0, 5) : '-');
                $plannedOut = $review?->planned_shift_end
                    ? Carbon::parse($review->planned_shift_end)->format('H:i')
                    : (($activeShiftModel && ! empty($activeShiftModel->end_time)) ? substr((string) $activeShiftModel->end_time, 0, 5) : '-');

                $dayTypeDescription = $this->resolveDayTypeDescription($dayType, $dateKey, $holidayMap);
                $checkin = $review?->checkin_at ? Carbon::parse($review->checkin_at) : null;
                $checkout = $review?->checkout_at ? Carbon::parse($review->checkout_at) : null;
                $rawCheckin = $checkin ? $checkin->copy() : null;
                $rawCheckout = $checkout ? $checkout->copy() : null;
                $inTimeActual = $rawCheckin?->format('H:i:s');
                $outTimeActual = $rawCheckout?->format('H:i:s');
                $actualMinutes = ($checkin && $checkout && $checkout->gt($checkin)) ? $checkin->diffInMinutes($checkout) : 0;
                $plannedMinutes = $plannedShiftProfileId ? (int) ($workMinutesPerDayMap[$plannedShiftProfileId] ?? 0) : 0;
                if ($plannedMinutes <= 0 && $activeShiftModel) {
                    $plannedMinutes = (int) ($activeShiftModel->work_minutes_per_day ?? 0);
                }
                $breakMinutes = 0;
                $breakDeducted = false;
                $normalMinutes = 0;
                $overtimeHours = 0.0;
                $overtimeHoursGross = 0.0;
                $overtimeBreakHours = 0.0;
                $weightedHours = 0.0;
                $otBreakdown = [];
                $otIn = null;
                $otOut = null;
                $specialOvertimeLabel = null;
                $specialOvertimeMode = null;
                $specialOvertimeCode = null;
                $specialOvertimePayload = null;
                $previousReviewForCarry = $reviews->get($date->copy()->subDay()->format('Y-m-d'));
                $manualCarryFromPrevious = $previousReviewForCarry
                    && str_contains((string) ($previousReviewForCarry->reason ?? ''), 'MANUAL_TIME_LOCK::')
                    && $previousReviewForCarry->checkout_at
                    && Carbon::parse((string) $previousReviewForCarry->checkout_at)->toDateString() === $dateKey;
                if ($manualCarryFromPrevious) {
                    $carryOutAt = $rawCheckout ?: $checkout;
                    $carryOutDisplay = '-';
                    if ($carryOutAt instanceof Carbon) {
                        $roundedCarryOut = $carryOutAt->copy()->second(0)->microsecond(0);
                        if ((int) $roundedCarryOut->minute >= 30) {
                            $roundedCarryOut->addHour();
                        }
                        $roundedCarryOut->minute(0);
                        $carryOutDisplay = $roundedCarryOut->format('H:i');
                    }
                    $displayInTime = 'Sisa Cut 1 Day';
                    $displayOutTime = $carryOutDisplay;
                    $displayInTimeReal = '-';
                    $displayOutTimeReal = $isOffShift ? '-' : ($rawCheckout?->format('H:i:s') ?: '-');
                    $displayInShadow = null;
                    $displayOutShadow = null;
                    $reasonText = 'Sisa Cut 1 Day dari '.Carbon::parse($dateKey)->subDay()->format('d/m/Y').' sampai '.$carryOutDisplay.'.';
                }
                $payableRuleApplied = null;

                $leaveTag = $leaveApprovedMap[$karyawanId.'|'.$dateKey] ?? null;
                $leaveLabel = is_array($leaveTag) ? (string) ($leaveTag['label'] ?? '') : '';
                $isLeaveApproved = is_array($leaveTag);
                $isCutiLeave = str_contains(strtolower($leaveLabel), 'cuti');
                $splWindows = $overtimeApprovedMap[$karyawanId.'|'.$dateKey] ?? [];
                $continuesBridge = $continuesNextDayMap[$karyawanId.'|'.$dateKey] ?? null;
                $splApproved = ! empty($splWindows) || is_array($continuesBridge);
                $skipOvertimeBreak = $this->hasApprovedOvertimeType(
                    $splWindows,
                    defined(SuratPerintahLemburModel::class.'::OVERTIME_TYPE_NO_REST_SKIP_BREAK')
                        ? SuratPerintahLemburModel::OVERTIME_TYPE_NO_REST_SKIP_BREAK
                        : 'no_rest_skip_break'
                );

                $hasScheduledShift = $plannedMinutes > 0;
                $appliedShiftCode = $activeShiftCode;
                $appliedShiftName = $activeShiftName;

                // Reuse the existing detailed calculation path by delegating to the
                // same local variables and logic block already maintained below.
                // The following include-style block is intentionally mirrored from
                // calculationDetailPage so the summary table and detail page stay aligned.
                $actualOutFromLogsSameDate = null;
                $sameDateLastLog = $employeeLogs
                    ->filter(fn (AttendanceLogModel $log) => $log->log_at instanceof Carbon && $log->log_at->format('Y-m-d') === $dateKey)
                    ->last();
                if ($sameDateLastLog && $sameDateLastLog->log_at instanceof Carbon) {
                    $actualOutFromLogsSameDate = $sameDateLastLog->log_at->format('H:i');
                }

                // Fallback state when there is no concrete review row.
                if (! $review) {
                    $rows[] = [
                        'work_date' => $dateKey,
                        'day_name' => $date->locale('id')->translatedFormat('D'),
                        'day_type' => $dayType,
                        'day_type_description' => $dayTypeDescription,
                        'leave_tag_label' => $leaveLabel,
                        'special_overtime_label' => null,
                        'special_overtime_mode' => null,
                        'special_overtime_code' => null,
                        'special_overtime_payload' => null,
                        'leave_tag_notes' => is_array($leaveTag) ? ($leaveTag['notes'] ?? null) : null,
                        'in_time' => '-',
                        'in_time_real' => '-',
                        'in_time_shadow' => null,
                        'out_time' => '-',
                        'out_time_real' => '-',
                        'out_time_shadow' => null,
                        'actual_hours' => 0.0,
                        'planned_hours' => round($plannedMinutes / 60, 2),
                        'planned_in_time' => $plannedIn,
                        'planned_out_time' => $plannedOut,
                        'has_scheduled_shift' => $hasScheduledShift,
                    'auto_ot_scheduled_nonworkday' => $isAutoOtScheduledNonWorkday,
                        'applied_shift_code' => $appliedShiftCode,
                        'applied_shift_name' => $appliedShiftName,
                        'break_hours' => 0.0,
                        'break_deducted' => false,
                        'normal_hours' => 0.0,
                        'overtime_hours' => 0.0,
                        'overtime_hours_gross' => 0.0,
                        'overtime_break_hours' => 0.0,
                        'overtime_detail_segments' => [],
                        'weighted_overtime_hours' => 0.0,
                        'overtime_in_time' => '-',
                        'overtime_out_time' => '-',
                        'spl_approved' => false,
                        'is_approved' => false,
                        'reason' => $isLeaveApproved ? ($isCutiLeave ? 'Cuti approved (paid).' : 'Leave approved.') : 'Tidak ada log (window shift)',
                        'payable_rule' => null,
                        'ot_dynamic' => $otColumns->mapWithKeys(fn ($c) => [$c['key'] => 0.0])->all(),
                    ];

                    continue;
                }

                // For the summary mismatch fix we only need the final display row data.
                // Use the existing page method as the source of truth by rendering through
                // the current controller path on a per-date basis would be too costly, so
                // here we preserve the already approved final values from the review row
                // and continues bridge metadata.
                $singleData = $this->buildCalculationDetailPayload([
                    'profil_bulan_id' => $profilId,
                    'karyawan_id' => $karyawanId,
                    'date_from' => $dateKey,
                    'date_to' => $dateKey,
                ]);
                $singleRows = is_array($singleData['rows'] ?? null) ? (array) $singleData['rows'] : [];
                if (! empty($singleRows)) {
                    $rows[] = (array) $singleRows[0];

                    continue;
                }
            } catch (\Throwable $e) {
                \Log::error('Attendance review detail row build failed', [
                    'profil_bulan_id' => $profilId,
                    'karyawan_id' => $karyawanId,
                    'work_date' => $dateKey,
                    'message' => $e->getMessage(),
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                ]);

                $rows[] = [
                    'work_date' => $dateKey,
                    'day_name' => $date->locale('id')->translatedFormat('D'),
                    'day_type' => $dayType,
                    'day_type_description' => $dayTypeDescription,
                    'leave_tag_label' => '',
                    'special_overtime_label' => null,
                    'special_overtime_mode' => null,
                    'special_overtime_code' => null,
                    'special_overtime_payload' => null,
                    'leave_tag_notes' => null,
                    'in_time' => '-',
                    'in_time_real' => '-',
                    'in_time_shadow' => null,
                    'out_time' => '-',
                    'out_time_real' => '-',
                    'out_time_shadow' => null,
                    'actual_hours' => 0.0,
                    'planned_hours' => round($plannedMinutes / 60, 2),
                    'planned_in_time' => $plannedIn,
                    'planned_out_time' => $plannedOut,
                    'has_scheduled_shift' => $hasScheduledShift,
                    'auto_ot_scheduled_nonworkday' => $isAutoOtScheduledNonWorkday,
                    'applied_shift_code' => $appliedShiftCode,
                    'applied_shift_name' => $appliedShiftName,
                    'break_hours' => 0.0,
                    'break_deducted' => false,
                    'normal_hours' => 0.0,
                    'overtime_hours' => 0.0,
                    'overtime_hours_gross' => 0.0,
                    'overtime_break_hours' => 0.0,
                    'overtime_detail_segments' => [],
                    'weighted_overtime_hours' => 0.0,
                    'overtime_in_time' => '-',
                    'overtime_out_time' => '-',
                    'spl_approved' => false,
                    'is_approved' => false,
                    'reason' => 'Error memuat baris perhitungan. Cek log server untuk detail.',
                    'payable_rule' => null,
                    'ot_dynamic' => $otColumns->mapWithKeys(fn ($c) => [$c['key'] => 0.0])->all(),
                ];
            }
        }

        return [
            'rows' => $rows,
            'otColumns' => $otColumns->values()->all(),
            'pendingCount' => (int) $pendingCount,
        ];
    }

    // =========================================================================
    // calculationDetailPage() - Halaman detail kalkulasi
    // Dipanggil dari: GET /attendance-review/calculations/detail
    // Output: View (halaman Blade template)
    // =========================================================================
    public function calculationDetailPage(Request $request)
    {
        return view('attendancereview::calculation_detail', $this->buildCalculationDetailPayload($request->all()));
    }

    // =========================================================================
    // buildCalculationDetailPayload() - Membangun/membuat data payload
    // Dipanggil dari: Route/API endpoint
    // Output: Response (bervariasi)
    // =========================================================================
    public function buildCalculationDetailPayload(array $input): array
    {
        $validator = Validator::make($input, [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['required', 'integer', 'exists:master_karyawans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
        ]);
        if ($validator->fails()) {
            abort(422, $validator->errors()->first());
        }

        $profilId = (int) ($input['profil_bulan_id'] ?? 0);
        $karyawanId = (int) ($input['karyawan_id'] ?? 0);
        $profil = ProfilBulanModel::query()->findOrFail($profilId);
        $assignmentProfilId = (int) ($input['assignment_profil_bulan_id'] ?? 0);
        $assignmentProfilIds = $assignmentProfilId > 0
            ? [$assignmentProfilId]
            : $this->summaryProfileIds($profil, 'both');

        $periodStart = Carbon::parse($profil->start_date)->startOfDay();
        $periodEnd = Carbon::parse($profil->end_date)->startOfDay();
        $filterDateFrom = ! empty($input['date_from']) ? Carbon::parse((string) $input['date_from'])->startOfDay() : null;
        $filterDateTo = ! empty($input['date_to']) ? Carbon::parse((string) $input['date_to'])->startOfDay() : null;
        $effectiveStart = $filterDateFrom && $filterDateFrom->gt($periodStart) ? $filterDateFrom : $periodStart->copy();
        $effectiveEnd = $filterDateTo && $filterDateTo->lt($periodEnd) ? $filterDateTo : $periodEnd->copy();
        if ($effectiveStart->gt($effectiveEnd)) {
            abort(422, 'Rentang tanggal tidak valid.');
        }

        $assignment = ProfilBulanKaryawanModel::query()
            ->with([
                'karyawan:id,employee_code,full_name',
                'profilJamKerja:id,code,name,start_time,end_time,break_start_time,break_end_time,work_minutes_per_day',
                'profilJamKerjaAlt:id,code,name,start_time,end_time,break_start_time,break_end_time,work_minutes_per_day',
                'profilGaji:id,code,name,monthly_hour_base',
                'roundingRule:id,code,name,target_type,round_method,interval_minutes,discipline_mode',
            ])
            ->whereIn('profil_bulan_id', $assignmentProfilIds)
            ->where('karyawan_id', $karyawanId)
            ->where('is_active', true)
            ->orderByRaw('CASE WHEN profil_bulan_id = ? THEN 0 ELSE 1 END', [$profilId])
            ->orderByDesc('profil_bulan_id')
            ->firstOrFail();
        $payableRule = $this->resolveAssignmentPayableRule($assignment);
        $payrollBasis = $this->resolveCalculationPayrollBasis($profil, $assignment, $effectiveStart->copy(), $effectiveEnd->copy());
        $isDailySalaryOverride = $this->isDailySalaryOverride((int) $assignment->id, $effectiveEnd->copy());
        $hkHoursPerDay = (float) $payrollBasis['hours_per_day'];
        $hkMinutesPerDay = (int) round($hkHoursPerDay * 60);

        $rules = [];
        if ($assignment->profil_perkalian_jam_id) {
            $rules = ProfilPerkalianJamDetailModel::query()
                ->where('profil_perkalian_jam_id', (int) $assignment->profil_perkalian_jam_id)
                ->where('is_active', true)
                ->orderBy('sort_order')
                ->orderBy('hour_start')
                ->get()
                ->map(fn ($row) => [
                    'day_type' => (string) $row->day_type,
                    'overtime_segment' => (string) ($row->overtime_segment ?? ''),
                    'hour_start' => (float) ($row->hour_start ?? 0),
                    'hour_end' => (float) ($row->hour_end ?? 0),
                    'multiplier' => (float) ($row->multiplier ?? 1),
                    'is_break' => (bool) ($row->is_break ?? false),
                ])
                ->values()
                ->all();
        }
        $otColumns = collect($this->resolveOvertimeColumnsFromRules($rules));        $overtimeRuleMode = 'legacy';
        if ($assignment->profil_perkalian_jam_id) {
            $overtimeRuleMode = (string) (DB::table('master_profil_perkalian_jams')
                ->where('id', (int) $assignment->profil_perkalian_jam_id)
                ->value('overtime_rule_mode') ?? 'legacy');
        }
        $beforeRules = collect($rules)
            ->filter(fn (array $rule) => ($rule['overtime_segment'] ?? '') === 'before')
            ->values()->all();
        $legacyRules = collect($rules)
            ->filter(fn (array $rule) => ($rule['overtime_segment'] ?? '') !== 'before' && ($rule['overtime_segment'] ?? '') !== 'after')
            ->values()->all();

        $reviews = AttendanceDailyReviewModel::query()
            ->where('profil_bulan_id', $profilId)
            ->where('karyawan_id', $karyawanId)
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->orderBy('work_date')
            ->get()
            ->keyBy(fn ($row) => optional($row->work_date)->format('Y-m-d'));
        $pendingCount = $reviews->filter(fn ($row) => ! (bool) $row->is_approved)->count();
        $approvedUrgencyPolicyIds = AttendanceUrgencyPolicyModel::query()
            ->where('profil_bulan_id', $profilId)
            ->where('status', 'approved')
            ->pluck('id')->map(fn ($id) => (int) $id)->all();
        $urgencyFcAnyMap = ForgettingClockRequestModel::query()
            ->where('karyawan_id', $karyawanId)
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->where('status', 'approved')->where('is_active', true)
            ->where('source', 'attendance_urgency_auto')
            ->get(['id', 'work_date', 'requested_checkin_at', 'requested_checkout_at', 'urgency_policy_id'])
            ->groupBy(fn (ForgettingClockRequestModel $fc) => optional($fc->work_date)->format('Y-m-d'));
        $approvedFcMap = ForgettingClockRequestModel::query()
            ->where('karyawan_id', $karyawanId)
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->where('status', 'approved')->where('is_active', true)
            ->get(['id', 'work_date', 'requested_checkin_at', 'requested_checkout_at', 'source', 'urgency_policy_id'])
            ->groupBy(fn (ForgettingClockRequestModel $fc) => optional($fc->work_date)->format('Y-m-d'));

        $calendarMarks = $this->buildCalendarMarks($effectiveStart->copy(), $effectiveEnd->copy());
        $holidayMap = $calendarMarks['holiday_map'] ?? [];
        $workdayMap = $calendarMarks['workday_map'] ?? [];
        $holidaySpecialMap = $calendarMarks['holiday_special_map'] ?? [];
        $leaveApprovedMap = $this->buildLeaveApprovedMap(collect([$karyawanId]), $effectiveStart->copy(), $effectiveEnd->copy());
        $overtimeApprovedMap = $this->buildOvertimeApprovedMap(collect([$karyawanId]), $effectiveStart->copy(), $effectiveEnd->copy());
        $continuesNextDayMap = $this->buildContinuesNextDayBridgeMap(collect([$karyawanId]), $effectiveStart->copy(), $effectiveEnd->copy());
        $employeeLogs = AttendanceLogModel::query()
            ->where('karyawan_id', $karyawanId)
            ->where('log_at', '>=', $effectiveStart->copy()->subDay()->startOfDay())
            ->where('log_at', '<=', $effectiveEnd->copy()->addDay()->endOfDay())
            ->orderBy('log_at')
            ->get()
            ->map(function (AttendanceLogModel $row) {
                if ($row->log_at instanceof Carbon) {
                    return $row;
                }
                $row->log_at = $row->log_at ? Carbon::parse((string) $row->log_at) : null;

                return $row;
            })
            ->filter(fn (AttendanceLogModel $row) => $row->log_at instanceof Carbon)
            ->values();

        $hasAnyCustomSchedule = DB::table('master_shift_schedules')
            ->where('karyawan_id', $karyawanId)
            ->where('is_active', true)
            ->where(function ($q) use ($profil): void {
                $q->whereNull('profil_bulan_id')->orWhere('profil_bulan_id', (int) $profil->id);
            })
            ->exists();
        $customScheduleRows = DB::table('master_shift_schedules')
            ->where('karyawan_id', $karyawanId)
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->where('is_active', true)
            ->where(function ($q) use ($profil): void {
                $q->whereNull('profil_bulan_id')
                    ->orWhere('profil_bulan_id', (int) $profil->id);
            })
            ->orderByRaw(
                'CASE
                    WHEN profil_bulan_id = ? AND is_locked = 1 THEN 1
                    WHEN profil_bulan_id = ? AND is_locked = 0 THEN 2
                    WHEN profil_bulan_id IS NULL AND is_locked = 1 THEN 3
                    ELSE 4
                END ASC',
                [(int) $profil->id, (int) $profil->id]
            )
            ->orderByDesc('id')
            ->get(['work_date', 'profil_jam_kerja_id']);
        $customScheduleMap = [];
        $customScheduleEmployeeIds = [];
        $customShiftIds = [];
        foreach ($customScheduleRows as $row) {
            $mapDateKey = Carbon::parse((string) $row->work_date)->format('Y-m-d');
            if (isset($customScheduleMap[$mapDateKey])) {
                continue;
            }
            $shiftId = (int) ($row->profil_jam_kerja_id ?? 0);
            if ($shiftId <= 0) {
                continue;
            }
            $customScheduleMap[$mapDateKey] = $shiftId;
            $customShiftIds[$shiftId] = $shiftId;
        }
        $customShiftMap = collect();
        if (! empty($customShiftIds)) {
            $customShiftMap = ProfilJamKerjaModel::query()
                ->whereIn('id', array_values($customShiftIds))
                ->get(['id', 'code', 'name', 'start_time', 'end_time', 'break_start_time', 'break_end_time', 'work_minutes_per_day'])
                ->keyBy('id');
        }

        $plannedShiftProfileIds = $reviews
            ->pluck('planned_profil_jam_kerja_id')
            ->filter()
            ->map(fn ($id) => (int) $id)
            ->unique()
            ->values();
        $plannedShiftMetaMap = [];
        if ($plannedShiftProfileIds->isNotEmpty()) {
            $plannedShiftMetaMap = ProfilJamKerjaModel::query()
                ->whereIn('id', $plannedShiftProfileIds)
                ->get(['id', 'code', 'name', 'start_time', 'end_time', 'break_start_time', 'break_end_time', 'work_minutes_per_day'])
                ->mapWithKeys(fn ($row) => [
                    (int) $row->id => [
                        'code' => (string) ($row->code ?? ''),
                        'name' => (string) ($row->name ?? ''),
                        'start_time' => $row->start_time ? substr((string) $row->start_time, 0, 8) : null,
                        'end_time' => $row->end_time ? substr((string) $row->end_time, 0, 8) : null,
                        'break_start_time' => $row->break_start_time ? substr((string) $row->break_start_time, 0, 8) : null,
                        'break_end_time' => $row->break_end_time ? substr((string) $row->break_end_time, 0, 8) : null,
                        'work_minutes_per_day' => (int) ($row->work_minutes_per_day ?? 0),
                    ],
                ])
                ->all();
        }

        $rows = [];
        foreach (CarbonPeriod::create($effectiveStart->copy(), $effectiveEnd->copy()) as $date) {
            $dateKey = $date->format('Y-m-d');
            try {
                /** @var AttendanceDailyReviewModel|null $review */
                $review = $reviews->get($dateKey);
                $dayType = $this->resolveDayTypeForCalculation($dateKey, $holidayMap, $workdayMap, $holidaySpecialMap);
                $resolvedShift = $this->resolveAssignedShiftForDate($assignment, $date->copy());
                $resolvedShiftModel = $resolvedShift['shift'] ?? null;
                $customShiftId = (int) ($customScheduleMap[$dateKey] ?? 0);
                $customShiftModel = $customShiftId > 0 ? $customShiftMap->get($customShiftId) : null;
                $plannedShiftProfileId = $review?->planned_profil_jam_kerja_id ? (int) $review->planned_profil_jam_kerja_id : null;
                $plannedShiftMeta = $plannedShiftProfileId && isset($plannedShiftMetaMap[$plannedShiftProfileId])
                    ? $plannedShiftMetaMap[$plannedShiftProfileId]
                    : null;
                $effectiveShiftCode = (string) ($customShiftModel?->code ?? $plannedShiftMeta['code'] ?? $resolvedShiftModel?->code ?? $assignment->profilJamKerja?->code ?? '');
                $effectiveShiftName = (string) ($customShiftModel?->name ?? $plannedShiftMeta['name'] ?? $resolvedShiftModel?->name ?? $assignment->profilJamKerja?->name ?? '');
                $effectiveShiftStart = $customShiftModel?->start_time
                    ? substr((string) $customShiftModel->start_time, 0, 8)
                    : ($plannedShiftMeta['start_time'] ?? ($resolvedShiftModel?->start_time ? substr((string) $resolvedShiftModel->start_time, 0, 8) : null));
                $effectiveShiftEnd = $customShiftModel?->end_time
                    ? substr((string) $customShiftModel->end_time, 0, 8)
                    : ($plannedShiftMeta['end_time'] ?? ($resolvedShiftModel?->end_time ? substr((string) $resolvedShiftModel->end_time, 0, 8) : null));
                $effectiveBreakStart = $customShiftModel?->break_start_time
                    ? substr((string) $customShiftModel->break_start_time, 0, 8)
                    : ($plannedShiftMeta['break_start_time'] ?? ($resolvedShiftModel?->break_start_time ? substr((string) $resolvedShiftModel->break_start_time, 0, 8) : null));
                $effectiveBreakEnd = $customShiftModel?->break_end_time
                    ? substr((string) $customShiftModel->break_end_time, 0, 8)
                    : ($plannedShiftMeta['break_end_time'] ?? ($resolvedShiftModel?->break_end_time ? substr((string) $resolvedShiftModel->break_end_time, 0, 8) : null));
                $effectiveWorkMinutesPerDay = (int) ($customShiftModel?->work_minutes_per_day ?? $plannedShiftMeta['work_minutes_per_day'] ?? ($resolvedShiftModel?->work_minutes_per_day ?? $assignment->profilJamKerja?->work_minutes_per_day ?? 0));
                $shiftText = strtolower(trim(implode(' ', [
                    (string) ($effectiveShiftCode ?? ''),
                    (string) ($effectiveShiftName ?? ''),
                    (string) ($assignment->profilJamKerja?->code ?? ''),
                    (string) ($assignment->profilJamKerja?->name ?? ''),
                ])));
                $isNormalShiftProfile = $shiftText === ''
                    || str_contains($shiftText, 'normal')
                    || str_contains($shiftText, 'office')
                    || str_contains($shiftText, 'reguler')
                    || str_contains($shiftText, 'regular');
                $isFullPeriodShiftProfile = ! $isNormalShiftProfile
                    || ! in_array(strtolower(trim((string) ($assignment->shift_mode ?? 'fixed'))), ['fixed', 'normal', ''], true);
                $leaveTag = $leaveApprovedMap[$karyawanId.'|'.$dateKey] ?? null;
                $leaveTypeRaw = strtolower(trim((string) ($leaveTag['leave_type'] ?? '')));
                $isCutiLeave = $leaveTag && (
                    str_contains($leaveTypeRaw, 'cuti')
                    || str_contains($leaveTypeRaw, 'annual')
                    || str_contains($leaveTypeRaw, 'annual_leave')
                );
                $isIzinLeave = $leaveTag && (
                    str_contains($leaveTypeRaw, 'izin')
                    || str_contains($leaveTypeRaw, 'permission')
                    || str_contains($leaveTypeRaw, 'permit')
                );
                $isSakitLeave = $leaveTag && (
                    str_contains($leaveTypeRaw, 'sakit')
                    || str_contains($leaveTypeRaw, 'sick')
                    || str_contains($leaveTypeRaw, 'ill')
                    || $leaveTypeRaw === 'mc'
                );
                $isLeaveApproved = ! empty($leaveTag);
                $leaveLabel = null;
                if ($isCutiLeave) {
                    $leaveLabel = 'Cuti Approved';
                } elseif ($isIzinLeave) {
                    $leaveLabel = 'Izin Approved';
                } elseif ($isSakitLeave) {
                    $leaveLabel = 'Sakit Approved';
                } elseif ($isLeaveApproved) {
                    $leaveLabel = 'Leave Approved';
                }

                // "Leave Approved" can be payable (counts as HK) depending on profil settings.
                $countIzinAsHk = (bool) ($profil->count_izin_as_hk ?? true);
                $countSakitAsHk = (bool) ($profil->count_sakit_as_hk ?? true);
                $countCutiAsHk = (bool) ($profil->count_cuti_as_hk ?? true);
                $isPaidLeave = false;
                if ($isLeaveApproved) {
                    if ($isCutiLeave) {
                        $isPaidLeave = $countCutiAsHk;
                    } elseif (
                        str_contains($leaveTypeRaw, 'izin')
                        || str_contains($leaveTypeRaw, 'permission')
                        || str_contains($leaveTypeRaw, 'permit')
                    ) {
                        $isPaidLeave = $countIzinAsHk;
                    } elseif (
                        str_contains($leaveTypeRaw, 'sakit')
                        || str_contains($leaveTypeRaw, 'sick')
                        || str_contains($leaveTypeRaw, 'ill')
                        || $leaveTypeRaw === 'mc'
                    ) {
                        $isPaidLeave = $countSakitAsHk;
                    }
                    if (array_key_exists('is_payable', $leaveTag) && $leaveTag['is_payable'] === false) {
                        $isPaidLeave = false;
                    }
                }

                $rawCheckin = $review?->checkin_at ? Carbon::parse($review->checkin_at) : null;
                $rawCheckout = $review?->checkout_at ? Carbon::parse($review->checkout_at) : null;
                $approvedFcRows = $approvedFcMap->get($dateKey, collect());
                $urgencyFcAnyRows = $urgencyFcAnyMap->get($dateKey, collect());
                $approvedFcIn = $approvedFcRows->first(fn (ForgettingClockRequestModel $fc) => $fc->requested_checkin_at !== null);
                $approvedFcOut = $approvedFcRows->first(fn (ForgettingClockRequestModel $fc) => $fc->requested_checkout_at !== null);
                $fcUrgencyIn = $approvedFcIn && (string) $approvedFcIn->source === 'attendance_urgency_auto';
                $fcUrgencyOut = $approvedFcOut && (string) $approvedFcOut->source === 'attendance_urgency_auto';
                if (!$rawCheckin && $approvedFcIn?->requested_checkin_at) $rawCheckin = Carbon::parse($approvedFcIn->requested_checkin_at);
                if (!$rawCheckout && $approvedFcOut?->requested_checkout_at) $rawCheckout = Carbon::parse($approvedFcOut->requested_checkout_at);
                $checkin = $rawCheckin ? $rawCheckin->copy() : null;
                $checkout = $rawCheckout ? $rawCheckout->copy() : null;
                $previousReviewForManualCut = $reviews->get($date->copy()->subDay()->format('Y-m-d'));
                $isManualCutRemainderDay = $previousReviewForManualCut
                    && str_contains((string) ($previousReviewForManualCut->reason ?? ''), 'MANUAL_TIME_LOCK::')
                    && $previousReviewForManualCut->checkin_at
                    && $previousReviewForManualCut->checkout_at;
                $manualCutRoundedOut = null;
                $manualCutOutAt = null;
                if ($isManualCutRemainderDay) {
                    $lastLogForRemainder = $employeeLogs
                        ->filter(fn (AttendanceLogModel $log) => $log->log_at && $log->log_at->toDateString() === $dateKey)
                        ->sortByDesc('log_at')
                        ->first();
                    $manualCutOutAt = $lastLogForRemainder?->log_at?->copy() ?: $rawCheckout?->copy();
                    if ($manualCutOutAt instanceof Carbon) {
                        $manualCutRoundedOut = $manualCutOutAt->copy()->second(0)->microsecond(0);
                        if ((int) $manualCutRoundedOut->minute >= 30) {
                            $manualCutRoundedOut->addHour();
                        }
                        $manualCutRoundedOut->minute(0);
                    }
                }
                $effectiveRounding = $assignment->roundingRule;
                if ($effectiveRounding) {
                    if ($checkin && in_array((string) $effectiveRounding->target_type, ['checkin', 'both'], true)) {
                        $checkin = $this->applyRounding($checkin, $effectiveRounding, 'checkin');
                    }
                    if ($checkout && in_array((string) $effectiveRounding->target_type, ['checkout', 'both'], true)) {
                        $checkout = $this->applyRounding($checkout, $effectiveRounding, 'checkout');
                    }
                }

                $breakMinutes = 0;
                if ($effectiveBreakStart && $effectiveBreakEnd) {
                    $bs = Carbon::parse('2000-01-01 '.$effectiveBreakStart);
                    $be = Carbon::parse('2000-01-01 '.$effectiveBreakEnd);
                    if ($be->lte($bs)) {
                        $be->addDay();
                    }
                    $breakMinutes = max(0, $bs->diffInMinutes($be));
                }

                $plannedShiftStartAt = null;
                $plannedShiftEndAt = null;
                if ($review && $review->planned_shift_start && $review->planned_shift_end) {
                    $plannedShiftStartAt = Carbon::parse($review->planned_shift_start);
                    $plannedShiftEndAt = Carbon::parse($review->planned_shift_end);
                    if ($plannedShiftEndAt->lte($plannedShiftStartAt)) {
                        $plannedShiftEndAt->addDay();
                    }
                } elseif ($review && $review->planned_shift_end) {
                    $plannedShiftEndAt = Carbon::parse($review->planned_shift_end);
                    if ($checkin && $plannedShiftEndAt->lte($checkin)) {
                        $plannedShiftEndAt->addDay();
                    }
                } elseif ($effectiveShiftStart && $effectiveShiftEnd) {
                    $plannedShiftStartAt = $date->copy()->setTimeFromTimeString($effectiveShiftStart);
                    $plannedShiftEndAt = $date->copy()->setTimeFromTimeString($effectiveShiftEnd);
                    if ($plannedShiftEndAt->lte($plannedShiftStartAt)) {
                        $plannedShiftEndAt->addDay();
                    }
                }
                $isCrossDay = $plannedShiftStartAt instanceof Carbon
                    && $plannedShiftEndAt instanceof Carbon
                    && $plannedShiftEndAt->toDateString() !== $plannedShiftStartAt->toDateString();
                // Pasangkan OUT hanya dengan log bertipe OUT di window shift ini.
                // Mencegah IN shift berikutnya menjadi checkout shift malam.
                if ($plannedShiftStartAt && $plannedShiftEndAt) {
                    $shiftOutLogs = $employeeLogs
                        ->filter(function (AttendanceLogModel $log) use ($plannedShiftStartAt, $plannedShiftEndAt): bool {
                            if (! $log->log_at instanceof Carbon) {
                                return false;
                            }
                            $type = strtolower(trim((string) ($log->log_type ?? '')));
                            if (! in_array($type, ['out', 'check_out', 'checkout', '1'], true)) {
                                return false;
                            }

                            return $log->log_at->between(
                                $plannedShiftStartAt->copy()->subHours(6),
                                $plannedShiftEndAt->copy()->addHours(8),
                            );
                        })
                        ->sortBy('log_at')
                        ->values();
                    if ($shiftOutLogs->isNotEmpty()) {
                        // Pada shift lintas hari, OUT pertama adalah checkout shift malam.
                        // OUT berikutnya dapat menjadi IN/OUT shift berikutnya dan tidak boleh
                        // menggantikan checkout lintas hari yang sudah ditemukan.
                        $matchedOut = ($isCrossDay ? $shiftOutLogs->first() : $shiftOutLogs->last())->log_at->copy();
                        $rawCheckout = $matchedOut;
                        $checkout = $matchedOut->copy();
                        if ($effectiveRounding && in_array((string) $effectiveRounding->target_type, ['checkout', 'both'], true)) {
                            $checkout = $this->applyRounding($checkout, $effectiveRounding, 'checkout');
                        }
                    } elseif (! $approvedFcOut?->requested_checkout_at && $rawCheckout) {
                        $rawCheckout = null;
                        $checkout = null;
                    }
                }
                $splWindows = $overtimeApprovedMap[$karyawanId.'|'.$dateKey] ?? [];
                $continuesBridge = $continuesNextDayMap[$karyawanId.'|'.$dateKey] ?? null;
                $approvedSplWindow = $this->resolveApprovedOvertimeWindowForShift(
                    $splWindows,
                    $plannedShiftStartAt,
                    $plannedShiftEndAt
                );
                $splApproved = (bool) ($approvedSplWindow['has_any'] ?? false);
                $autoOvertimeWithoutSpl = $this->assignmentAllowsAutomaticOvertimeWithoutSpl($assignment);
                $autoOtWorkdayMode = $this->assignmentAutomaticOvertimeWorkdayMode($assignment);
                $skipOvertimeBreak = $this->hasApprovedOvertimeType(
                    $splWindows,
                    defined(SuratPerintahLemburModel::class.'::OVERTIME_TYPE_NO_REST_SKIP_BREAK')
                        ? SuratPerintahLemburModel::OVERTIME_TYPE_NO_REST_SKIP_BREAK
                        : 'no_rest_skip_break'
                );

                $plannedMinutes = $effectiveWorkMinutesPerDay;
                if ($plannedMinutes <= 0 && $review && $review->planned_shift_start && $review->planned_shift_end) {
                    $plannedStart = Carbon::parse($review->planned_shift_start);
                    $plannedEnd = Carbon::parse($review->planned_shift_end);
                    if ($plannedEnd->lte($plannedStart)) {
                        $plannedEnd->addDay();
                    }
                    if ($plannedEnd->gt($plannedStart)) {
                        $plannedMinutes = $plannedStart->diffInMinutes($plannedEnd);
                    }
                } elseif ($plannedMinutes <= 0 && $effectiveShiftStart && $effectiveShiftEnd) {
                    $plannedStart = Carbon::parse('2000-01-01 '.$effectiveShiftStart);
                    $plannedEnd = Carbon::parse('2000-01-01 '.$effectiveShiftEnd);
                    if ($plannedEnd->lte($plannedStart)) {
                        $plannedEnd->addDay();
                    }
                    if ($plannedEnd->gt($plannedStart)) {
                        $plannedMinutes = $plannedStart->diffInMinutes($plannedEnd);
                    }
                }
                if ($plannedMinutes <= 0) {
                    $plannedMinutes = 8 * 60;
                }
                $payrollPlannedMinutes = $hkMinutesPerDay;

                $inTimeActual = null;
                if ($dayType === 'workday' && $rawCheckin && $plannedShiftStartAt && $rawCheckin->lt($plannedShiftStartAt)) {
                    $inTimeActual = $rawCheckin->format('H:i:s');
                    if ($autoOvertimeWithoutSpl && $autoOtWorkdayMode === 'full_actual') {
                        // AUTO OT workday mode full actual: checkin tetap mengikuti log aktual.
                    } elseif (! $approvedSplWindow['allow_pre']) {
                        $checkin = $plannedShiftStartAt->copy();
                    } elseif ($approvedSplWindow['pre_start'] instanceof Carbon && $rawCheckin->lt($approvedSplWindow['pre_start'])) {
                        $checkin = $approvedSplWindow['pre_start']->copy();
                    }
                }

                if ($dayType === 'workday' && $rawCheckout && $plannedShiftEndAt && $rawCheckout->gt($plannedShiftEndAt)) {
                    if ($autoOvertimeWithoutSpl) {
                        // OT otomatis tanpa SPL: checkout workday tetap mengikuti log aktual.
                    } elseif (! $approvedSplWindow['allow_post']) {
                        $checkout = $plannedShiftEndAt->copy();
                    } elseif ($approvedSplWindow['post_end'] instanceof Carbon && $rawCheckout->gt($approvedSplWindow['post_end'])) {
                        $checkout = $approvedSplWindow['post_end']->copy();
                    }
                }

                // Fallback: jika jam efektif berubah dari log asli (IN/OUT), simpan actual time
                // supaya bisa ditampilkan sebagai "Real" di halaman detail.
                if ($inTimeActual === null && $rawCheckin && $checkin && $rawCheckin->format('H:i') !== $checkin->format('H:i')) {
                    $inTimeActual = $rawCheckin->format('H:i:s');
                }

                $actualMinutes = 0;
                if ($checkin && $checkout && $checkout->gt($checkin)) {
                    $actualMinutes = $checkin->diffInMinutes($checkout);
                }

                $breakDeducted = false;
                if ($effectiveWorkMinutesPerDay <= 0 && $breakMinutes > 0 && $plannedMinutes > $breakMinutes) {
                    $plannedMinutes -= $breakMinutes;
                    $breakDeducted = true;
                }

                $actualMinutesNet = $actualMinutes;
                $normalBreakOverlapMinutes = 0;
                if (
                    $breakMinutes > 0
                    && $checkin
                    && $checkout
                    && $effectiveBreakStart
                    && $effectiveBreakEnd
                ) {
                    $breakStartAt = $date->copy()->setTimeFromTimeString($effectiveBreakStart);
                    $breakEndAt = $date->copy()->setTimeFromTimeString($effectiveBreakEnd);
                    if ($breakEndAt->lte($breakStartAt)) {
                        $breakEndAt->addDay();
                    }
                    $overlapStart = $checkin->gt($breakStartAt) ? $checkin->copy() : $breakStartAt->copy();
                    $overlapEnd = $checkout->lt($breakEndAt) ? $checkout->copy() : $breakEndAt->copy();
                    if ($overlapEnd->gt($overlapStart)) {
                        $normalBreakOverlapMinutes = $overlapStart->diffInMinutes($overlapEnd);
                        if ($dayType === 'workday') {
                            $actualMinutesNet = max(0, $actualMinutesNet - $normalBreakOverlapMinutes);
                        }
                    }
                }

                $workedMinutesForOvertime = $actualMinutesNet;
                $isNonWorkdayCalculation = in_array($dayType, ['weekend', 'holiday', 'holiday_special'], true);
                $hasNonWorkdaySpl = $splApproved || is_array($continuesBridge);

                $dayNameLower = strtolower((string) $date->translatedFormat('D'));
                $isWeekendName = str_contains($dayNameLower, 'sab') || str_contains($dayNameLower, 'min') || str_contains($dayNameLower, 'sun') || str_contains($dayNameLower, 'sat');
                $holidayCountsAsHk = (bool) ($profil->holiday_counts_as_hk ?? true);
                $holidayWeekendCounts = (bool) ($profil->holiday_weekend_counts ?? false);

                if ($isPaidLeave) {
                    // Leave payable: dianggap hadir HK penuh (jam efektif = jam per hari), tanpa lembur.
                    $checkin = null;
                    $checkout = null;
                    $rawCheckin = null;
                    $rawCheckout = null;
                    $inTimeActual = null;
                    $actualMinutes = $hkMinutesPerDay;
                    $actualMinutesNet = $hkMinutesPerDay;
                    $plannedMinutes = $payrollPlannedMinutes;
                    $breakMinutes = 0;
                }

                $plannedIn = '-';
                $plannedOut = '-';
                $appliedShiftCode = '';
                $appliedShiftName = '';
                if ($review && $review->planned_shift_start && $review->planned_shift_end) {
                    $plannedIn = Carbon::parse($review->planned_shift_start)->format('H:i');
                    $plannedOut = Carbon::parse($review->planned_shift_end)->format('H:i');
                } elseif ($effectiveShiftStart && $effectiveShiftEnd) {
                    $plannedIn = substr($effectiveShiftStart, 0, 5);
                    $plannedOut = substr($effectiveShiftEnd, 0, 5);
                }
                $appliedShiftCode = $effectiveShiftCode;
                $appliedShiftName = $effectiveShiftName;
                $isOffShift = strtolower(trim($appliedShiftCode)) === 'off';
                if ($isOffShift) {
                    $rawCheckin = null;
                    $rawCheckout = null;
                    $checkin = null;
                    $checkout = null;
                    $inTimeActual = null;
                    $outTimeActual = null;
                    $actualMinutes = 0;
                    $actualMinutesNet = 0;
                    $workedMinutesForOvertime = 0;
                }
                $hasExplicitShiftSchedule = (bool) $customShiftModel;
                $hasReviewPlannedShift = $review && $review->planned_shift_start && $review->planned_shift_end;
                $waitingSchedule = !$hasExplicitShiftSchedule && !$hasReviewPlannedShift && $hasAnyCustomSchedule;
                $isCalendarNonWorkday = in_array($dayType, ['weekend', 'holiday', 'holiday_special'], true);
                $hasScheduledShift = ! $isOffShift && ($hasExplicitShiftSchedule
                    || $isFullPeriodShiftProfile
                    || $hasReviewPlannedShift
                    || (! $isCalendarNonWorkday && $appliedShiftCode !== '' && $plannedMinutes > 0));
                $scheduleBadgeType = 'normal';
                $scheduleBadgeLabel = 'Normal';
                if ($isOffShift) {
                    $scheduleBadgeType = 'off';
                    $scheduleBadgeLabel = 'OFF';
                } elseif (! $hasScheduledShift && $isCalendarNonWorkday) {
                    $scheduleBadgeType = 'off';
                    $scheduleBadgeLabel = 'OFF';
                } elseif ($hasExplicitShiftSchedule || $isFullPeriodShiftProfile) {
                    $scheduleBadgeType = 'shift';
                    $scheduleBadgeLabel = 'Shift';
                }
                $holidayPaid = $this->isHolidayLikeDayType($dayType)
                    && $holidayCountsAsHk
                    && (! $isWeekendName || $holidayWeekendCounts);
                $holidayPaidWithAuthorizedWork = $holidayPaid
                    && $workedMinutesForOvertime > 0
                    && $hasNonWorkdaySpl;
                if ($holidayPaid) {
                    $actualMinutes = $hkMinutesPerDay;
                    $actualMinutesNet = $hkMinutesPerDay;
                }
                if ($isOffShift && ! $isPaidLeave && ! $isLeaveApproved) {
                    $actualMinutes = 0;
                    $actualMinutesNet = 0;
                    $workedMinutesForOvertime = 0;
                }
                if (! $isPaidLeave && $isNonWorkdayCalculation && ! $hasNonWorkdaySpl && ! $hasScheduledShift) {
                    // Raw attendance remains visible, but actual work/overtime is not credited without SPL.
                    // Paid weekday holiday credit is applied separately through $normalMinutes below.
                    $actualMinutes = 0;
                    $actualMinutesNet = 0;
                    $workedMinutesForOvertime = 0;
                }
                $isScheduledNonWorkdayShift = $hasScheduledShift
                    && in_array($dayType, ['weekend', 'holiday', 'holiday_special'], true)
                    && $workedMinutesForOvertime > 0;
                $isAutoOtScheduledNonWorkday = $isScheduledNonWorkdayShift
                    && $autoOvertimeWithoutSpl;

                $dayTypeDescription = '-';
                if ($this->isHolidayLikeDayType($dayType)) {
                    $dayTypeDescription = (string) (($holidaySpecialMap[$dateKey] ?? $holidayMap[$dateKey] ?? ($dayType === 'holiday_special' ? 'Holiday Special' : 'Holiday')));
                } elseif ($dayType === 'weekend') {
                    $dayTypeDescription = 'Weekend';
                } elseif ($dayType === 'workday' && isset($workdayMap[$dateKey])) {
                    $dayTypeDescription = (string) $workdayMap[$dateKey];
                }

                if ($holidayPaid) {
                    // Holiday berbayar tetap memberi kredit HK penuh. SPL hanya membuka hak lembur.
                    $normalMinutes = $hkMinutesPerDay;
                    $overtimeMinutes = $holidayPaidWithAuthorizedWork ? $workedMinutesForOvertime : 0;
                } elseif ($isScheduledNonWorkdayShift) {
                    $normalMinutes = $isAutoOtScheduledNonWorkday
                        ? 0
                        : min($actualMinutesNet, $hkMinutesPerDay);
                    $overtimeMinutes = $isAutoOtScheduledNonWorkday
                        ? $actualMinutesNet
                        : ($hasNonWorkdaySpl ? max(0, $actualMinutesNet - $plannedMinutes) : 0);
                } elseif ($hasScheduledShift) {
                    $normalMinutes = min($actualMinutesNet, $payrollPlannedMinutes);
                    $overtimeMinutes = max(0, $actualMinutesNet - $plannedMinutes);
                } else {
                    $normalMinutes = $dayType === 'workday' ? min($actualMinutesNet, $payrollPlannedMinutes) : 0;
                    $overtimeMinutes = $dayType === 'workday'
                        ? max(0, $actualMinutesNet - $plannedMinutes)
                        : ($splApproved ? $actualMinutes : 0);
                }
                if ($isPaidLeave) {
                    $normalMinutes = $hkMinutesPerDay;
                    $overtimeMinutes = 0;
                }
                $payableRuleApplied = null;
                if ($this->payableRuleApplies($payableRule, $date, $normalMinutes)) {
                    $creditMinutes = max(0, (int) ($payableRule['credit_minutes'] ?? 0));
                    if ($creditMinutes > $normalMinutes) {
                        $normalMinutes = $creditMinutes;
                        $payableRuleApplied = $payableRule;
                    }
                }
                $overtimeHoursGross = $overtimeMinutes / 60;
                $normalBreakOvertimeHours = $dayType !== 'workday'
                    ? round($normalBreakOverlapMinutes / 60, 4)
                    : 0.0;
                $overtimeHoursCalcBase = max(0.0, round($overtimeHoursGross - $normalBreakOvertimeHours, 4));

                // Segmented AUTO OT uses one interval: Before gets its own multiplier.
                if ($overtimeRuleMode === 'segmented' && $beforeMinutes <= 0 && !empty($beforeRules)
                    && $isAutoOtScheduledNonWorkday
                    && $rawCheckin && $plannedShiftStartAt && $rawCheckin->lt($plannedShiftStartAt)
                    && $rawCheckout && $rawCheckout->gt($rawCheckin)) {
                    $beforeMinutes = min(
                        $rawCheckin->diffInMinutes($plannedShiftStartAt),
                        $rawCheckin->diffInMinutes($rawCheckout)
                    );
                    if ($beforeMinutes > 0) {
                        $beforeWeightedHours = $this->applyOvertimeMultiplierInternal(
                            $beforeMinutes / 60,
                            $dayType,
                            $beforeRules,
                            false
                        );
                        $overtimeHoursCalcBase = max(0.0, round($overtimeHoursCalcBase - ($beforeMinutes / 60), 4));
                    }
                }
                $overtimeBreakHours = $this->calculateOvertimeBreakDeductionHoursInternal($overtimeHoursCalcBase, $dayType, $legacyRules, $skipOvertimeBreak);
                $overtimeHours = max(0.0, round($overtimeHoursCalcBase - $overtimeBreakHours, 4));
                $weightedHours = $this->applyOvertimeMultiplierInternal($overtimeHoursCalcBase, $dayType, $legacyRules, $skipOvertimeBreak);
                $otBreakdown = $this->calculateOvertimeBreakdownDynamicInternal($overtimeHoursCalcBase, $dayType, $legacyRules, $skipOvertimeBreak);

                // Approved SPL Before is handled here for workday/SPL flows.
                if ($overtimeRuleMode === 'segmented' && $beforeMinutes <= 0 && !empty($beforeRules)
                    && $rawCheckin && $plannedShiftStartAt && $rawCheckin->lt($plannedShiftStartAt)
                    && ($approvedSplWindow['allow_pre'] ?? false)) {
                    $beforeStart = $rawCheckin->copy();
                    if ($approvedSplWindow['pre_start'] instanceof Carbon && $beforeStart->lt($approvedSplWindow['pre_start'])) {
                        $beforeStart = $approvedSplWindow['pre_start']->copy();
                    }
                    if ($beforeStart->lt($plannedShiftStartAt)) {
                        $beforeMinutes = $beforeStart->diffInMinutes($plannedShiftStartAt);
                        $beforeWeightedHours = $this->applyOvertimeMultiplierInternal(
                            $beforeMinutes / 60,
                            $dayType,
                            $beforeRules,
                            false
                        );
                    }
                }
                $overtimeHours += round($beforeMinutes / 60, 4);
                $weightedHours += $beforeWeightedHours;
                if ($beforeMinutes > 0) {
                    $otBreakdown[] = [
                        'segment' => 'before',
                        'hour_start' => 1,
                        'hour_end' => round($beforeMinutes / 60, 4),
                        'hours' => round($beforeMinutes / 60, 4),
                        'weighted_hours' => round($beforeWeightedHours, 4),
                    ];
                }
                if ($isPaidLeave) {
                    $overtimeHoursGross = 0.0;
                    $overtimeBreakHours = 0.0;
                    $overtimeHours = 0.0;
                    $weightedHours = 0.0;
                    $otBreakdown = [];
                }

                $otIn = null;
                $otOut = null;
                $outTimeActual = null;
                if ($rawCheckout && $checkout && $rawCheckout->format('H:i') !== $checkout->format('H:i')) {
                    $outTimeActual = $rawCheckout->format('H:i:s');
                }
                if ($overtimeMinutes > 0 && $checkin && $checkout) {
                    if ($dayType === 'workday') {
                        $normalEnd = $plannedShiftEndAt ? $plannedShiftEndAt->copy() : $checkin->copy()->addMinutes($plannedMinutes);
                        if ($normalEnd->lt($checkout)) {
                            $otIn = $normalEnd->format('H:i');
                            $otOut = $checkout->format('H:i');
                        }
                    } else {
                        $otIn = $checkin->format('H:i');
                        $otOut = $checkout->format('H:i');
                    }
                }

                if ($plannedShiftStartAt && $plannedShiftEndAt) {
                    $rawWindowStart = $plannedShiftStartAt->copy()->subHours(6);
                    $rawWindowEnd = $plannedShiftEndAt->copy()->addHours(8);
                    $rawWindowLogs = $employeeLogs
                        ->filter(fn (AttendanceLogModel $log) => $log->log_at && $log->log_at->between($rawWindowStart, $rawWindowEnd))
                        ->values();
                    $rawFirstLog = $rawWindowLogs->first();
                    $rawLastLog = $rawWindowLogs->last();
                    $rawTypedIn = $rawWindowLogs->filter(function (AttendanceLogModel $log): bool {
                        $type = strtolower(trim((string) ($log->log_type ?? '')));

                        return in_array($type, ['in', 'check_in', 'checkin', '0'], true);
                    });
                    $rawTypedOut = $rawWindowLogs->filter(function (AttendanceLogModel $log): bool {
                        $type = strtolower(trim((string) ($log->log_type ?? '')));

                        return in_array($type, ['out', 'check_out', 'checkout', '1'], true);
                    });
                    if ($rawTypedIn->isNotEmpty()) {
                        $rawFirstLog = $rawTypedIn->first();
                    }
                    if ($rawTypedOut->isNotEmpty()) {
                        $rawLastLog = $isCrossDay ? $rawTypedOut->first() : $rawTypedOut->last();
                    }

                    if ($inTimeActual === null && $rawFirstLog && $rawFirstLog->log_at instanceof Carbon) {
                        $inTimeActual = $rawFirstLog->log_at->format('H:i:s');
                    }

                    if ($rawLastLog && $rawLastLog->log_at instanceof Carbon) {
                        $rawLastOut = $rawLastLog->log_at->copy();
                        if ($rawLastOut->format('H:i') !== ($checkout?->format('H:i') ?: '')) {
                            $outTimeActual = $rawLastOut->format('H:i:s');
                        }
                    }
                }

                $actualOutFromLogsSameDate = null;
                $sameDateLastLog = $employeeLogs
                    ->filter(fn (AttendanceLogModel $log) => $log->log_at instanceof Carbon && $log->log_at->format('Y-m-d') === $dateKey)
                    ->last();
                if ($sameDateLastLog && $sameDateLastLog->log_at instanceof Carbon) {
                    $actualOutFromLogsSameDate = $sameDateLastLog->log_at->format('H:i');
                }

                $reasonText = $isOffShift ? '-' : (string) ($review?->reason ?: '-');
                if (
                    ! $isOffShift
                    && $isCrossDay
                    && $rawCheckin instanceof Carbon
                    && $rawCheckout instanceof Carbon
                    && $plannedShiftStartAt instanceof Carbon
                    && $plannedShiftEndAt instanceof Carbon
                    && $rawCheckin->lte($plannedShiftStartAt->copy()->addHours(4))
                    && $rawCheckout->gte($plannedShiftEndAt->copy()->subHours(3))
                    && $rawCheckout->lte($plannedShiftEndAt->copy()->addMinutes(10))
                ) {
                    // Reason lama dapat berasal dari deteksi sebelum pasangan cross-day diperbaiki.
                    // Jangan tampilkan transisi/checkout dibatasi jika OUT aktual sudah cocok.
                    $reasonText = 'Normal';
                }
                if ($isAutoOtScheduledNonWorkday) {
                    $reasonText = 'AUTO OT terjadwal weekend/holiday.';
                }
                if (is_array($continuesBridge)) {
                    $reasonText = $this->buildContinuesNextDayReason($continuesBridge);
                }
                if ($isLeaveApproved) {
                    $leaveNotes = trim((string) ($leaveTag['notes'] ?? ''));
                    if ($isCutiLeave) {
                        $reasonText = 'Cuti approved (paid).';
                    } else {
                        $reasonText = 'Leave approved.';
                    }
                    if ($leaveNotes !== '') {
                        $reasonText .= "\n".$leaveNotes;
                    }
                }
                if (
                    ! $isLeaveApproved
                    && $isNonWorkdayCalculation
                    && ! $hasNonWorkdaySpl
                    && ! $hasScheduledShift
                    && ($rawCheckin || $rawCheckout || $sameDateLastLog)
                ) {
                    $nonWorkdayLabel = $dayTypeDescription !== '-'
                        ? $dayTypeDescription
                        : ($dayType === 'holiday_special'
                            ? 'Holiday Special'
                            : ($dayType === 'holiday' ? 'Holiday' : 'Weekend'));
                    $reasonText = $holidayPaid
                        ? 'Menunggu SPL: '.$nonWorkdayLabel.' tetap dikreditkan sebagai HK reguler, kehadiran belum dihitung lembur.'
                        : 'Butuh SPL: '.$nonWorkdayLabel.' tanpa SPL approved. Jam tidak diakui.';
                }
                if ($splApproved && ! str_contains($reasonText, 'SPL Approved')) {
                $splWindows = $overtimeApprovedMap[$karyawanId.'|'.$dateKey] ?? [];
                    $docNos = collect($splWindows)->pluck('document_no')->filter()->unique()->values()->all();
                    $jobCodes = collect($splWindows)->pluck('job_code')->filter()->unique()->values()->all();
                    $splLine = 'SPL Approved: '.(! empty($docNos) ? implode(', ', $docNos) : '-');
                    if (! empty($jobCodes)) {
                        $splLine .= ' | No Job: '.implode(', ', $jobCodes);
                    }
                    $reasonText = trim(($reasonText !== '-' ? $reasonText."\n" : '').$splLine);
                }
                if ($payableRuleApplied && ! str_contains($reasonText, 'Payable Rule')) {
                    $ruleLine = 'Payable Rule: '.($payableRuleApplied['code'] ?? '-')
                        .' - '.($payableRuleApplied['name'] ?? '-')
                        .' (diakui '.round(((int) ($payableRuleApplied['credit_minutes'] ?? 0)) / 60, 2).' jam / '
                        .number_format((float) ($payableRuleApplied['credit_hk'] ?? 1), 2, '.', '').' HK).';
                    $reasonText = trim(($reasonText !== '-' ? $reasonText."\n" : '').$ruleLine);
                }
                if ($reasonText !== '-') {
                    $reasonText = str_replace([
                        'Log IN/OUT terdeteksi normal.',
                        'Log tidak match dengan pola shift yang direncanakan.',
                        'Checkout dibatasi jam pulang karena SPL lembur akhir belum approved.',
                        'Checkin awal dibatasi jam masuk karena SPL awal belum approved.',
                        'Tidak ada log dalam window shift.',
                        'Log tidak match dengan pola shift.',
                        'Log tidak match dengan pola shift yang direncanakan.',
                        'Kemungkinan transisi shift, jam IN jauh dari rencana.',
                        'Kemungkinan transisi shift, jam OUT jauh dari rencana.',
                        'Terdeteksi IN tanpa OUT.',
                        'Terdeteksi OUT tanpa IN.',
                        'Log IN/OUT terdeteksi normal.',
                        'Tidak dihitung lembur.',
                    ], [
                        'Normal',
                        'Tidak match shift',
                        'Checkout dibatasi (SPL belum approved)',
                        'Checkin dibatasi (SPL belum approved)',
                        'Tidak ada log (window shift)',
                        'Tidak match shift',
                        'Tidak match shift',
                        'Transisi shift (IN jauh)',
                        'Transisi shift (OUT jauh)',
                        'Missing OUT',
                        'Missing IN',
                        'Normal',
                        'No OT',
                    ], $reasonText);
                }

                $displayInTime = $checkin?->format('H:i') ?: '-';
                $displayInTimeReal = $isOffShift ? '-' : ($rawCheckin?->format('H:i:s') ?: '-');
                $displayInShadow = $isOffShift ? null : $inTimeActual;
                $displayOutTime = $checkout?->format('H:i') ?: '-';
                $displayOutTimeReal = $isOffShift ? '-' : ($rawCheckout?->format('H:i:s') ?: '-');
                $displayOutShadow = $isOffShift ? null : $outTimeActual;
                $displayActualMinutes = $dayType === 'workday' && $actualMinutes > 0
                    ? min($actualMinutes, $payrollPlannedMinutes + $breakMinutes)
                    : $actualMinutes;
                $displayActualHours = round($displayActualMinutes / 60, 2);
                $displayPlannedHours = $isOffShift ? 0.0 : round($payrollPlannedMinutes / 60, 2);
                $displayBreakHours = round($breakMinutes / 60, 2);
                $displayNormalHours = round($normalMinutes / 60, 2);
                $displayOvertimeHours = round($overtimeHours, 2);
                $displayOvertimeHoursGross = round($overtimeHoursGross, 2);
                $displayOvertimeBreakHours = round($overtimeBreakHours, 2);
                $displayOvertimeSegments = $this->buildOvertimeDetailSegmentsInternal($overtimeHoursGross, $dayType, $rules, $skipOvertimeBreak);
                $displayWeightedHours = round($weightedHours, 2);
                $displayOtIn = $otIn ?: '-';
                $displayOtOut = $otOut ?: '-';
                $displaySplApproved = $splApproved;
                $displayOtDynamic = $otColumns->mapWithKeys(fn ($c) => [$c['key'] => round((float) ($otBreakdown[$c['key']] ?? 0), 2)])->all();
                $specialOvertimeLabel = null;
                $specialOvertimeMode = null;
                $specialOvertimeCode = null;
                $specialOvertimePayload = null;

                if (is_array($continuesBridge)) {
                    $displaySplApproved = true;
                    $specialOvertimeLabel = 'Special Overtime';
                    $specialOvertimeMode = ($continuesBridge['mode'] ?? '') === 'carry'
                        ? 'Continues Carry'
                        : 'ContinuesNextDay';
                    $specialOvertimeCode = 'continues_work_day';
                    $specialOvertimePayload = is_array($continuesBridge['rule_payload'] ?? null)
                        ? $continuesBridge['rule_payload']
                        : [];
                    $continuesTargetCoverageHours = round((float) ($specialOvertimePayload['continues_target_coverage_hours'] ?? 0), 2);
                    $continuesNextDayWorkHours = round((float) ($specialOvertimePayload['continues_next_day_work_hours'] ?? 0), 2);
                    $continuesShortageHours = round((float) ($specialOvertimePayload['continues_shortage_hours'] ?? 0), 2);
                    if (($continuesBridge['mode'] ?? '') === 'carry') {
                        $carryBonusCutoff = '16:00';
                        $carryActualOut = $actualOutFromLogsSameDate ?: $outTimeActual;
                        if (! $carryActualOut) {
                            $carryActualOut = $rawCheckout?->format('H:i');
                        }
                        if (! $carryActualOut) {
                            $carryActualOut = $rawCheckout?->copy()->format('H:i');
                        }
                        if (! $carryActualOut) {
                            $carryActualOut = substr((string) ($continuesBridge['end_time'] ?? ''), 0, 5) ?: null;
                        }
                        $effectiveContinuesShortageHours = $continuesShortageHours;
                        if ($carryActualOut) {
                            try {
                                $carryActualOutAt = Carbon::createFromFormat('H:i', $carryActualOut);
                                $carryBonusCutoffAt = Carbon::createFromFormat('H:i', $carryBonusCutoff);
                                if ($carryActualOutAt->lte($carryBonusCutoffAt)) {
                                    $effectiveContinuesShortageHours = 0.0;
                                }
                            } catch (\Throwable $e) {
                                // Ignore invalid carry time formats and keep configured shortage hours.
                            }
                        }
                        $specialOvertimePayload['continues_original_shortage_hours'] = $continuesShortageHours;
                        $specialOvertimePayload['continues_effective_shortage_hours'] = $effectiveContinuesShortageHours;
                        $specialOvertimePayload['continues_bonus_awarded'] = $effectiveContinuesShortageHours > 0;
                        $specialOvertimePayload['continues_bonus_cutoff_time'] = $carryBonusCutoff;
                        $specialOvertimePayload['continues_carry_actual_out'] = $carryActualOut;
                        $displayInTime = '-';
                        $displayInTimeReal = '-';
                        $displayInShadow = null;
                        $displayOutTime = $carryActualOut ?: (substr((string) ($continuesBridge['end_time'] ?? ''), 0, 5) ?: ($displayOutTime ?: '-'));
                        $displayOutTimeReal = $carryActualOut ?: $displayOutTime;
                        $displayOutShadow = $displayOutTimeReal !== $displayOutTime ? $outTimeActual : null;
                        $displayActualHours = round(max(0.0, $continuesNextDayWorkHours + $effectiveContinuesShortageHours), 2);
                        $displayPlannedHours = 0.0;
                        $displayBreakHours = 0.0;
                        $displayNormalHours = $displayActualHours;
                        $displayOvertimeHours = 0.0;
                        $displayOvertimeHoursGross = 0.0;
                        $displayOvertimeBreakHours = 0.0;
                        $displayOvertimeSegments = [];
                        $displayWeightedHours = 0.0;
                        $displayOtIn = '-';
                        $displayOtOut = '-';
                        $displayOtDynamic = $otColumns->mapWithKeys(fn ($c) => [$c['key'] => 0.0])->all();
                    } else {
                        $bridgeWindow = $this->resolveContinuesBridgeWindow($continuesBridge);
                        if (is_array($bridgeWindow)) {
                            /** @var Carbon $bridgeStartAt */
                            $bridgeStartAt = $bridgeWindow['start_at'];
                            /** @var Carbon $bridgeEndAt */
                            $bridgeEndAt = $bridgeWindow['end_at'];
                            $bridgeOvertimeHoursGross = max(0.0, round($bridgeStartAt->diffInMinutes($bridgeEndAt) / 60, 4));
                            $bridgeOvertimeCalcBase = $bridgeOvertimeHoursGross;
                            $bridgeOvertimeBreakHours = $this->calculateOvertimeBreakDeductionHoursInternal($bridgeOvertimeCalcBase, $dayType, $rules, $skipOvertimeBreak);
                            $bridgeOvertimeHours = max(0.0, round($bridgeOvertimeCalcBase - $bridgeOvertimeBreakHours, 4));
                            $bridgeWeightedHours = $this->applyOvertimeMultiplierInternal($bridgeOvertimeCalcBase, $dayType, $rules, $skipOvertimeBreak);
                            $bridgeOtBreakdown = $this->calculateOvertimeBreakdownDynamicInternal($bridgeOvertimeCalcBase, $dayType, $rules, $skipOvertimeBreak);

                            $displayOvertimeHoursGross = round($bridgeOvertimeHoursGross, 2);
                            $displayOvertimeBreakHours = round($bridgeOvertimeBreakHours, 2);
                            $displayOvertimeHours = round($bridgeOvertimeHours, 2);
                            $displayWeightedHours = round($bridgeWeightedHours, 2);
                            $displayOtIn = $bridgeStartAt->format('H:i');
                            $displayOtOut = $bridgeEndAt->isSameDay($bridgeStartAt)
                                ? $bridgeEndAt->format('H:i')
                                : ($bridgeEndAt->format('H:i').' (+1)');
                            $displayOtDynamic = $otColumns->mapWithKeys(fn ($c) => [$c['key'] => round((float) ($bridgeOtBreakdown[$c['key']] ?? 0), 2)])->all();
                            $displayOvertimeSegments = $this->buildOvertimeDetailSegmentsInternal($bridgeOvertimeCalcBase, $dayType, $rules, $skipOvertimeBreak);
                        }

                        if ($displayActualHours <= 0 && $displayPlannedHours > 0) {
                            $displayActualHours = $displayPlannedHours;
                        }
                        if ($displayNormalHours <= 0 && $displayPlannedHours > 0) {
                            $displayNormalHours = $displayPlannedHours;
                        }
                        if ($displayOutTime === '-') {
                            $bridgeOut = substr((string) ($continuesBridge['end_time'] ?? ''), 0, 5);
                            if ($bridgeOut !== '') {
                                $displayOutTime = $bridgeOut.' (+1)';
                            }
                        }
                    }
                }

                $isManualCutAnchorDay = $review
                    && str_contains((string) ($review->reason ?? ''), 'MANUAL_TIME_LOCK::')
                    && $review->checkin_at
                    && $review->checkout_at
                    && Carbon::parse((string) $review->checkout_at)->toDateString() > $dateKey;
                if ($isManualCutAnchorDay) {
                    $cutStart = Carbon::parse((string) $review->checkin_at);
                    if ($effectiveRounding && in_array((string) $effectiveRounding->target_type, ['checkin', 'both'], true)) {
                        $cutStart = $this->applyRounding($cutStart, $effectiveRounding, 'checkin');
                    }
                    $cutEnd = $cutStart->copy()->addDay();
                    $displayInTime = $cutStart->format('H:i');
                    $displayOutTime = $cutEnd->format('H:i').' (+1)';
                    $displayActualHours = 24.0;
                    $displayNormalHours = 0.0;
                    $displayOvertimeHoursGross = 24.0;
                    $displayOvertimeBreakHours = round($breakMinutes / 60, 2);
                    $displayOvertimeHours = max(0.0, round(24.0 - $displayOvertimeBreakHours, 2));
                    $displayWeightedHours = round($displayOvertimeHours * 2, 2);
                    $displayOtIn = $cutStart->format('H:i');
                    $displayOtOut = $cutEnd->format('H:i').' (+1)';
                    $reasonText = 'Cut 1 Day: 24 jam setelah pembulatan profil. Sisa waktu dihitung pada tanggal berikutnya.';
                }
                if ($isManualCutRemainderDay && $manualCutRoundedOut instanceof Carbon) {
                    $previousCutStart = Carbon::parse((string) $previousReviewForManualCut->checkin_at);
                    if ($effectiveRounding && in_array((string) $effectiveRounding->target_type, ['checkin', 'both'], true)) {
                        $previousCutStart = $this->applyRounding($previousCutStart, $effectiveRounding, 'checkin');
                    }
                    $previousCutLimit = $previousCutStart->copy()->addDay();
                    $displayInTime = 'Sisa Cut 1 Day';
                    $displayOutTime = $manualCutRoundedOut->format('H:i');
                    $displayInTimeReal = '-';
                    $displayOutTimeReal = $manualCutOutAt?->format('H:i:s') ?: '-';
                    $displayInShadow = null;
                    $displayOutShadow = null;
                    $remainderMinutes = max(0, $previousCutLimit->diffInMinutes($manualCutRoundedOut, false));
                    $displayActualHours = round($remainderMinutes / 60, 2);
                    $displayNormalHours = 0.0;
                    $displayOvertimeHoursGross = round($remainderMinutes / 60, 2);
                    $displayOvertimeBreakHours = 0.0;
                    $displayOvertimeHours = round($remainderMinutes / 60, 2);
                    $displayWeightedHours = round($remainderMinutes / 60, 2);
                    $displayOtIn = $previousCutLimit->format('H:i');
                    $displayOtOut = $manualCutRoundedOut->format('H:i');
                    $displayOtDynamic = $otColumns->mapWithKeys(fn ($c) => [$c['key'] => 0.0])->all();
                    $reasonText = 'Sisa setelah Cut 1 Day tanggal '.$date->copy()->subDay()->format('d/m/Y').' sampai pulang '.$manualCutRoundedOut->format('H:i').'.';
                }
                if ($waitingSchedule) {
                    $scheduleBadgeType = 'off';
                    $scheduleBadgeLabel = 'Belum Ada Shift';
                    $reasonText = 'Belum ada shift / bisa jadi libur. Menunggu jadwal.';
                    $displayInTime = '-';
                    $displayOutTime = '-';
                    $displayInTimeReal = '-';
                    $displayOutTimeReal = '-';
                    $displayInShadow = null;
                    $displayOutShadow = null;
                    $displayActualHours = 0.0;
                    $displayPlannedHours = 0.0;
                    $displayNormalHours = 0.0;
                    $displayOvertimeHours = 0.0;
                    $displayOvertimeHoursGross = 0.0;
                    $displayOvertimeBreakHours = 0.0;
                    $displayWeightedHours = 0.0;
                    $displayBreakHours = 0.0;
                    $displayOtIn = '-';
                    $displayOtOut = '-';
                    $displayOtDynamic = $otColumns->mapWithKeys(fn ($c) => [$c['key'] => 0.0])->all();
                    $appliedShiftCode = '';
                    $appliedShiftName = '';
                    $plannedIn = '-';
                    $plannedOut = '-';
                    $hasScheduledShift = false;
                }
                $rows[] = [
                    'work_date' => $dateKey,
                    'day_name' => $date->locale('id')->translatedFormat('D'),
                    'day_type' => $dayType,
                    'day_type_description' => $dayTypeDescription,
                    'schedule_badge_type' => $scheduleBadgeType,
                    'schedule_badge_label' => $scheduleBadgeLabel,
                    'is_off_day' => $scheduleBadgeType === 'off',
                    'leave_tag_label' => $leaveLabel,
                    'special_overtime_label' => $specialOvertimeLabel,
                    'special_overtime_mode' => $specialOvertimeMode,
                    'special_overtime_code' => $specialOvertimeCode,
                    'special_overtime_payload' => $specialOvertimePayload,
                    'leave_tag_notes' => $leaveTag['notes'] ?? null,
                    'in_time' => $displayInTime,
                    'in_time_real' => $displayInTimeReal,
                    'in_time_shadow' => $displayInShadow,
                    'out_time' => $displayOutTime,
                    'out_time_real' => $displayOutTimeReal,
                    'out_time_shadow' => $displayOutShadow,
                    'fc_personal_in' => (bool) ($approvedFcIn && !$fcUrgencyIn),
                    'fc_personal_out' => (bool) ($approvedFcOut && !$fcUrgencyOut),
                    'fc_urgency_in' => (bool) $fcUrgencyIn,
                    'fc_urgency_out' => (bool) $fcUrgencyOut,
                    'actual_hours' => $displayActualHours,
                    'planned_hours' => $displayPlannedHours,
                    'planned_in_time' => $plannedIn,
                    'planned_out_time' => $plannedOut,
                    'has_scheduled_shift' => $hasScheduledShift,
                    'auto_ot_scheduled_nonworkday' => $isAutoOtScheduledNonWorkday,
                    'applied_shift_code' => $appliedShiftCode,
                    'applied_shift_name' => $appliedShiftName,
                    'break_hours' => $displayBreakHours,
                    'break_deducted' => $breakDeducted,
                    'normal_hours' => $displayNormalHours,
                    'overtime_hours' => $displayOvertimeHours,
                    'overtime_hours_gross' => $displayOvertimeHoursGross,
                    'overtime_break_hours' => $displayOvertimeBreakHours,
                    'overtime_detail_segments' => $displayOvertimeSegments,
                    'weighted_overtime_hours' => $displayWeightedHours,
                    'overtime_in_time' => $displayOtIn,
                    'overtime_out_time' => $displayOtOut,
                    'spl_approved' => $displaySplApproved,
                    'is_approved' => (bool) ($review?->is_approved),
                    'reason' => $reasonText.($fcUrgencyIn || $fcUrgencyOut ? ' | FC URGENCY Approved' : '').($skipOvertimeBreak ? ' | NOREST-2' : ''),
                    'payable_rule' => $payableRuleApplied,
                    'ot_dynamic' => $displayOtDynamic,
                ];
            } catch (\Throwable $e) {
                \Log::error('Attendance review detail row build failed', [
                    'profil_bulan_id' => $profilId,
                    'karyawan_id' => $karyawanId,
                    'work_date' => $dateKey,
                    'message' => $e->getMessage(),
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                ]);

                $rows[] = [
                    'work_date' => $dateKey,
                    'day_name' => $date->locale('id')->translatedFormat('D'),
                    'day_type' => $this->resolveDayTypeForCalculation($dateKey, $holidayMap, $workdayMap, $holidaySpecialMap),
                    'day_type_description' => '-',
                    'schedule_badge_type' => 'normal',
                    'schedule_badge_label' => 'Normal',
                    'is_off_day' => false,
                    'leave_tag_label' => null,
                    'special_overtime_label' => null,
                    'special_overtime_mode' => null,
                    'special_overtime_code' => null,
                    'special_overtime_payload' => null,
                    'leave_tag_notes' => null,
                    'in_time' => '-',
                    'in_time_real' => '-',
                    'in_time_shadow' => null,
                    'out_time' => '-',
                    'out_time_real' => '-',
                    'out_time_shadow' => null,
                    'actual_hours' => 0.0,
                    'planned_hours' => 0.0,
                    'planned_in_time' => '-',
                    'planned_out_time' => '-',
                    'has_scheduled_shift' => false,
                    'applied_shift_code' => '',
                    'applied_shift_name' => '',
                    'break_hours' => 0.0,
                    'break_deducted' => false,
                    'normal_hours' => 0.0,
                    'overtime_hours' => 0.0,
                    'overtime_hours_gross' => 0.0,
                    'overtime_break_hours' => 0.0,
                    'overtime_detail_segments' => [],
                    'weighted_overtime_hours' => 0.0,
                    'overtime_in_time' => '-',
                    'overtime_out_time' => '-',
                    'spl_approved' => false,
                    'is_approved' => false,
                    'reason' => 'Error memuat baris perhitungan. Cek log server untuk detail.',
                    'payable_rule' => null,
                    'ot_dynamic' => $otColumns->mapWithKeys(fn ($c) => [$c['key'] => 0.0])->all(),
                ];
            }
        }

        $rows = $this->attachFaceImageMetadataToDetailRows($rows, $employeeLogs);

        return [
            'profil' => $profil,
            'profilId' => $profilId,
            'assignment' => $assignment,
            'karyawanId' => $karyawanId,
            'rows' => $rows,
            'otColumns' => $otColumns->values()->all(),
            'payrollBasis' => $payrollBasis,
            'isDailySalaryOverride' => $isDailySalaryOverride,
            'dateFrom' => $effectiveStart->format('Y-m-d'),
            'dateTo' => $effectiveEnd->format('Y-m-d'),
            'pendingCount' => (int) $pendingCount,
            'publicView' => filter_var($input['public_view'] ?? false, FILTER_VALIDATE_BOOLEAN),
            'publicBackUrl' => (string) ($input['public_back_url'] ?? ''),
        ];
    }

    // =========================================================================
    // resolveCalculationPayrollBasis() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function isDailySalaryOverride(int $assignmentId, Carbon $effectiveDate): bool
    {
        if ($assignmentId <= 0 || !Schema::hasTable('payroll_karyawan_component_overrides') || !Schema::hasTable('master_komponen_pendapatans')) {
            return false;
        }

        $date = $effectiveDate->format('Y-m-d');
        $row = DB::table('payroll_karyawan_component_overrides as o')
            ->leftJoin('master_komponen_pendapatans as kp', 'kp.id', '=', 'o.komponen_pendapatan_id')
            ->where('o.profil_bulan_karyawan_id', $assignmentId)
            ->where('o.component_group', 'pendapatan')
            ->where('o.calc_type', 'fixed')
            ->where('o.is_active', true)
            ->where(fn ($q) => $q->whereNull('o.effective_start')->orWhereDate('o.effective_start', '<=', $date))
            ->where(fn ($q) => $q->whereNull('o.effective_end')->orWhereDate('o.effective_end', '>=', $date))
            ->where(function ($q) {
                foreach (['gapok', 'gaji pokok', 'upah pokok', 'basic salary'] as $idx => $kw) {
                    $method = $idx === 0 ? 'whereRaw' : 'orWhereRaw';
                    $q->{$method}('LOWER(COALESCE(kp.code, "")) like ?', ["%{$kw}%"])
                        ->orWhereRaw('LOWER(COALESCE(kp.name, "")) like ?', ["%{$kw}%"]);
                }
            })
            ->orderByDesc('o.id')
            ->first([
                'o.amount',
                DB::raw('LOWER(COALESCE(kp.code, "")) as code_lc'),
                DB::raw('LOWER(COALESCE(kp.name, "")) as name_lc'),
            ]);

        if (!$row || !is_numeric($row->amount)) {
            return false;
        }

        $code = (string) ($row->code_lc ?? '');
        $name = (string) ($row->name_lc ?? '');
        $amount = (float) $row->amount;

        return str_contains($code, 'harian')
            || str_contains($name, 'harian')
            || str_contains($code, 'daily')
            || str_contains($name, 'daily')
            || ((str_contains($code, 'bulanan') || str_contains($name, 'bulanan') || str_contains($code, 'monthly') || str_contains($name, 'monthly')) && $amount > 0 && $amount < self::LEGACY_MONTHLY_TO_DAILY_THRESHOLD);
    }

    private function resolveCalculationPayrollBasis(ProfilBulanModel $profil, ProfilBulanKaryawanModel $assignment, ?Carbon $dateFrom = null, ?Carbon $dateTo = null): array
    {
        $monthlyHourBase = (int) ($assignment->profilGaji?->monthly_hour_base ?? 0);
        $hoursPerDay = match ($monthlyHourBase) {
            173 => 7.0,
            168 => 8.0,
            default => 0.0,
        };
        if ($hoursPerDay <= 0) {
            $shiftMinutes = (int) ($assignment->profilJamKerja?->work_minutes_per_day ?? 0);
            $hoursPerDay = $shiftMinutes > 0
                ? round($shiftMinutes / 60, 4)
                : (float) ($profil->jam_per_hari ?? 8);
        }
        $hoursPerDay = max(1.0, $hoursPerDay);

        if ($monthlyHourBase <= 0) {
            $monthlyHourBase = (int) round(max(1, (int) ($profil->hk_basis ?? 21)) * $hoursPerDay);
        }
        $monthlyHourBase = max(1, $monthlyHourBase);
        if (strtolower(trim((string) ($assignment->payroll_hk_basis_mode ?? ''))) === 'daily' && $dateFrom && $dateTo) {
            $calendarMarks = $this->buildCalendarMarks($dateFrom->copy(), $dateTo->copy());
            $holidayMap = $calendarMarks['holiday_map'] ?? [];
            $workdayMap = $calendarMarks['workday_map'] ?? [];
            $workdays = 0;
            foreach (CarbonPeriod::create($dateFrom->copy(), $dateTo->copy()) as $date) {
                $dateKey = $date->format('Y-m-d');
                if (isset($workdayMap[$dateKey]) || !isset($holidayMap[$dateKey])) {
                    $workdays++;
                }
            }
            $monthlyHourBase = max(1, (int) round(max(1, $workdays) * $hoursPerDay));
        }

        return [
            'monthly_hour_base' => $monthlyHourBase,
            'hours_per_day' => $hoursPerDay,
            'hk_basis' => round($monthlyHourBase / $hoursPerDay, 4),
            'profil_gaji_code' => (string) ($assignment->profilGaji?->code ?? ''),
            'profil_gaji_name' => (string) ($assignment->profilGaji?->name ?? ''),
        ];
    }

    // =========================================================================
    // normalizeFaceImagePath() - Menormalisasi format data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function normalizeFaceImagePath(?string $rawPath): ?string
    {
        $raw = trim((string) $rawPath);
        if ($raw === '') {
            return null;
        }

        $raw = str_replace('\\', '/', $raw);
        if (str_starts_with($raw, '/storage/')) {
            $raw = ltrim(substr($raw, 8), '/');
        }

        $raw = ltrim($raw, '/');

        return str_starts_with($raw, 'attendance-face/') ? $raw : null;
    }

    // =========================================================================
    // resolveFaceImageUrl() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveFaceImageUrl(?string $rawPath): ?string
    {
        $relative = $this->normalizeFaceImagePath($rawPath);
        if (! $relative) {
            return null;
        }

        if (Storage::disk('public')->exists($relative) || is_file(public_path('storage/'.$relative))) {
            return route('attendance_review.face_file', ['path' => $relative], false);
        }

        return null;
    }

    // =========================================================================
    // faceFile() - Serve file foto wajah
    // Dipanggil dari: GET /attendance-review/face-file
    // Output: Response (bervariasi)
    // =========================================================================
    public function faceFile(Request $request)
    {
        $relative = $this->normalizeFaceImagePath((string) $request->query('path', ''));
        if (! $relative) {
            abort(404);
        }

        if (Storage::disk('public')->exists($relative)) {
            return response()->file(Storage::disk('public')->path($relative));
        }

        $publicStoragePath = public_path('storage/'.$relative);
        if (is_file($publicStoragePath)) {
            return response()->file($publicStoragePath);
        }

        abort(404);
    }

    // =========================================================================
    // attachFaceImageMetadataToDetailRows() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function attachFaceImageMetadataToDetailRows(array $rows, Collection $employeeLogs): array
    {
        if (empty($rows) || $employeeLogs->isEmpty()) {
            return array_map(static function (array $row): array {
                $row['face_images'] = [];
                $row['has_face_image'] = false;
                $row['face_image_count'] = 0;

                return $row;
            }, $rows);
        }

        $photosByDate = [];
        foreach ($employeeLogs as $log) {
            $capturedAt = $log->log_at instanceof Carbon ? $log->log_at : null;
            $url = $this->resolveFaceImageUrl($log->face_image_path ?? null);
            if (! $capturedAt || ! $url) {
                continue;
            }

            $dateKey = $capturedAt->format('Y-m-d');
            $logType = strtoupper(trim((string) ($log->log_type ?? '')));
            $label = match ($logType) {
                'IN' => 'Foto IN',
                'OUT' => 'Foto OUT',
                default => 'Foto Presensi',
            };

            $photosByDate[$dateKey][] = [
                'label' => $label,
                'captured_at' => $capturedAt->format('Y-m-d H:i:s'),
                'captured_at_label' => $capturedAt->copy()->locale('id')->translatedFormat('d M Y H:i'),
                'source' => trim((string) ($log->source ?? '')) !== '' ? (string) $log->source : '-',
                'url' => $url,
            ];
        }

        return array_map(function (array $row) use ($photosByDate): array {
            $dateKey = (string) ($row['work_date'] ?? '');
            $photos = $photosByDate[$dateKey] ?? [];
            $row['face_images'] = array_values($photos);
            $row['has_face_image'] = ! empty($photos);
            $row['face_image_count'] = count($photos);

            return $row;
        }, $rows);
    }

    // =========================================================================
    // resolveAssignmentPayableRule() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveAssignmentPayableRule(?ProfilBulanKaryawanModel $assignment): ?array
    {
        if (! $assignment || ! Schema::hasTable('payroll_payable_rules')) {
            return null;
        }
        if (! Schema::hasColumn('master_profil_bulan_karyawans', 'payable_rule_id')) {
            return null;
        }

        $ruleId = (int) ($assignment->payable_rule_id ?? 0);
        if ($ruleId <= 0) {
            return null;
        }

        $row = DB::table('payroll_payable_rules')
            ->where('id', $ruleId)
            ->where('is_active', true)
            ->first(['id', 'code', 'name', 'min_effective_minutes', 'credit_minutes', 'credit_hk', 'days_of_week']);
        if (! $row) {
            return null;
        }

        $days = json_decode((string) ($row->days_of_week ?? '[]'), true);
        $days = is_array($days) ? array_values(array_filter(array_map('intval', $days))) : [];

        return [
            'id' => (int) $row->id,
            'code' => (string) $row->code,
            'name' => (string) $row->name,
            'min_effective_minutes' => (int) ($row->min_effective_minutes ?? 0),
            'credit_minutes' => (int) ($row->credit_minutes ?? 0),
            'credit_hk' => (float) ($row->credit_hk ?? 1),
            'days_of_week' => $days,
        ];
    }

    // =========================================================================
    // payableRuleApplies() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function payableRuleApplies(?array $rule, Carbon $date, int $effectiveMinutes): bool
    {
        if (! $rule) {
            return false;
        }
        $days = (array) ($rule['days_of_week'] ?? []);
        if (! empty($days) && ! in_array((int) $date->dayOfWeekIso, $days, true)) {
            return false;
        }

        return $effectiveMinutes >= max(0, (int) ($rule['min_effective_minutes'] ?? 0));
    }

    // =========================================================================
    // approveCalculationDetailAll() - Approve semua detail kalkulasi
    // Dipanggil dari: POST /attendance-review/calculations/detail/approve-all
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function approveCalculationDetailAll(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['required', 'integer', 'exists:master_karyawans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profilId = (int) $request->input('profil_bulan_id');
        $karyawanId = (int) $request->input('karyawan_id');
        $profil = ProfilBulanModel::query()->findOrFail($profilId);
        if ($guard = $this->guardProfilBulanOpenForAttendance($profil)) {
            return $guard;
        }

        $periodStart = Carbon::parse($profil->start_date)->startOfDay();
        $periodEnd = Carbon::parse($profil->end_date)->startOfDay();
        $filterDateFrom = $request->filled('date_from') ? Carbon::parse($request->input('date_from'))->startOfDay() : null;
        $filterDateTo = $request->filled('date_to') ? Carbon::parse($request->input('date_to'))->startOfDay() : null;
        $effectiveStart = $filterDateFrom && $filterDateFrom->gt($periodStart) ? $filterDateFrom : $periodStart->copy();
        $effectiveEnd = $filterDateTo && $filterDateTo->lt($periodEnd) ? $filterDateTo : $periodEnd->copy();
        if ($effectiveStart->gt($effectiveEnd)) {
            return response()->json(['message' => 'Rentang tanggal tidak valid.'], 422);
        }

        $rows = AttendanceDailyReviewModel::query()
            ->where('profil_bulan_id', $profilId)
            ->where('karyawan_id', $karyawanId)
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->orderBy('work_date')
            ->get();

        if ($rows->isEmpty()) {
            return response()->json(['message' => 'Tidak ada data review pada rentang tanggal ini.'], 422);
        }

        $approvedCount = 0;
        $skippedCount = 0;
        DB::transaction(function () use ($rows, &$approvedCount, &$skippedCount): void {
            foreach ($rows as $row) {
                if ((bool) $row->is_approved) {
                    $skippedCount++;

                    continue;
                }
                $changed = $this->applyApproveToReview($row, 'Bulk approve dari halaman Detail Perhitungan Jam.');
                if ($changed) {
                    $approvedCount++;
                } else {
                    $skippedCount++;
                }
            }
        });

        return response()->json([
            'message' => "Approve detail selesai. Approved: {$approvedCount}, Skip: {$skippedCount}.",
            'data' => [
                'approved' => $approvedCount,
                'skipped' => $skippedCount,
                'profil_bulan_id' => $profilId,
                'karyawan_id' => $karyawanId,
                'date_from' => $effectiveStart->format('Y-m-d'),
                'date_to' => $effectiveEnd->format('Y-m-d'),
            ],
        ]);
    }

    // =========================================================================
    // exportCalculationDetailPdf() - Export detail kalkulasi ke PDF
    // Dipanggil dari: GET /attendance-review/calculations/detail/export-pdf
    // Output: Response (bervariasi)
    // =========================================================================
    public function exportCalculationDetailPdf(Request $request)
    {
        $data = $this->buildCalculationDetailPayload($request->all());
        $profil = $data['profil'] ?? null;
        $assignment = $data['assignment'] ?? null;
        $dateFrom = (string) ($data['dateFrom'] ?? now()->format('Y-m-d'));
        $dateTo = (string) ($data['dateTo'] ?? now()->format('Y-m-d'));

        $pdf = Pdf::loadView('attendancereview::exports.calculation_detail_pdf', $data)->setPaper('a3', 'landscape');
        $filename = 'calc-detail-'
            .($profil?->code ?: 'profil')
            .'-'.($assignment?->karyawan?->employee_code ?: 'karyawan')
            .'-'.str_replace('-', '', $dateFrom)
            .'-'.str_replace('-', '', $dateTo)
            .'.pdf';

        return $pdf->download($filename);
    }

    // =========================================================================
    // sendCalculationDetail() - Kirim detail kalkulasi via email
    // Dipanggil dari: POST /attendance-review/calculations/detail/send
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function sendCalculationDetail(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['required', 'integer', 'exists:master_karyawans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
            'channel' => ['required', 'in:email,wa'],
            'recipient' => ['required', 'string', 'max:500'],
            'subject' => ['nullable', 'string', 'max:200'],
            'message' => ['nullable', 'string', 'max:5000'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $data = $this->buildCalculationDetailPayload($request->all());
        $profil = $data['profil'] ?? null;
        $assignment = $data['assignment'] ?? null;
        $dateFrom = (string) ($data['dateFrom'] ?? now()->format('Y-m-d'));
        $dateTo = (string) ($data['dateTo'] ?? now()->format('Y-m-d'));
        $rows = (array) ($data['rows'] ?? []);

        $filename = 'calc-detail-'
            .($profil?->code ?: 'profil')
            .'-'.($assignment?->karyawan?->employee_code ?: 'karyawan')
            .'-'.str_replace('-', '', $dateFrom)
            .'-'.str_replace('-', '', $dateTo)
            .'.pdf';
        $pdfBinary = Pdf::loadView('attendancereview::exports.calculation_detail_pdf', $data)
            ->setPaper('a3', 'landscape')
            ->output();

        $channel = (string) $request->input('channel');
        if ($channel === 'email') {
            $recipients = collect(explode(',', (string) $request->input('recipient')))
                ->map(fn ($email) => strtolower(trim((string) $email)))
                ->filter(fn ($email) => $email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL))
                ->unique()
                ->values()
                ->all();
            if (count($recipients) === 0) {
                return response()->json(['message' => 'Email tujuan tidak valid.'], 422);
            }

            $subject = trim((string) $request->input('subject', ''));
            if ($subject === '') {
                $subject = '[AHSP] Detail Perhitungan Jam '.($assignment?->karyawan?->employee_code ?: '');
            }
            $body = trim((string) $request->input('message', ''));
            if ($body === '') {
                $body = 'Terlampir PDF Detail Perhitungan Jam untuk '
                    .($assignment?->karyawan?->employee_code ?: '-')
                    .' periode '.$dateFrom.' s/d '.$dateTo.'.';
            }

            Mail::raw($body, function ($message) use ($recipients, $subject, $pdfBinary, $filename): void {
                $message->to($recipients)
                    ->subject($subject)
                    ->attachData($pdfBinary, $filename, ['mime' => 'application/pdf']);
            });

            return response()->json([
                'message' => 'Detail PDF berhasil dikirim ke email.',
                'data' => ['channel' => 'email', 'recipients' => $recipients, 'filename' => $filename],
            ]);
        }

        $waBaseUrl = trim((string) (AppSetting::query()->where('key', 'login.wa_base_url')->value('value') ?: ''));
        $waApiKey = trim((string) (AppSetting::query()->where('key', 'login.wa_api_key')->value('value') ?: ''));
        $waSender = trim((string) (AppSetting::query()->where('key', 'login.wa_sender')->value('value') ?: ''));
        $waDeviceId = trim((string) (AppSetting::query()->where('key', 'login.wa_device_id')->value('value') ?: ''));
        $waDelay = (int) (AppSetting::query()->where('key', 'login.wa_delay_seconds')->value('value') ?: 0);
        $waRetry = (int) (AppSetting::query()->where('key', 'login.wa_retry_count')->value('value') ?: 0);
        $waRetryDelay = (int) (AppSetting::query()->where('key', 'login.wa_retry_delay_seconds')->value('value') ?: 5);
        if ($waBaseUrl === '' || $waApiKey === '') {
            return response()->json(['message' => 'WA Gateway belum dikonfigurasi.'], 422);
        }

        $waTarget = trim((string) $request->input('recipient', ''));
        if ($waTarget === '') {
            return response()->json(['message' => 'Nomor WhatsApp tujuan wajib diisi.'], 422);
        }

        $messageText = trim((string) $request->input('message', ''));
        if ($messageText === '') {
            $messageText = "Detail Perhitungan Jam\n"
                .'Karyawan: '.($assignment?->karyawan?->employee_code ?: '-').' - '.($assignment?->karyawan?->full_name ?: '-')."\n"
                .'Periode: '.$dateFrom.' s/d '.$dateTo."\n"
                .'Jumlah hari: '.count($rows)."\n"
                .'PDF detail tersedia di dashboard AHSP.';
        }

        $payload = [
            'target' => $waTarget,
            'message' => $messageText,
            'sender' => $waSender,
            'device_id' => $waDeviceId,
            'delay' => $waDelay,
            'retry' => $waRetry,
            'retry_delay' => $waRetryDelay,
        ];

        $waResp = Http::withToken($waApiKey)->acceptJson()->post(rtrim($waBaseUrl, '/').'/send', $payload);
        if (! $waResp->successful()) {
            return response()->json([
                'message' => 'Gagal kirim WhatsApp ke gateway.',
                'data' => ['status' => $waResp->status(), 'response' => $waResp->json() ?: $waResp->body()],
            ], 422);
        }

        return response()->json([
            'message' => 'Notifikasi WhatsApp detail berhasil dikirim.',
            'data' => ['channel' => 'wa', 'recipient' => $waTarget],
        ]);
    }

    // =========================================================================
    // exportCalculationSheet() - Export sheet kalkulasi ke Excel
    // Dipanggil dari: GET /attendance-review/calculation-sheet
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function exportCalculationSheet(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['required_without:karyawan_id', 'array', 'min:1', 'max:50'],
            'karyawan_ids.*' => ['integer', 'distinct', 'exists:master_karyawans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profilId = (int) $request->input('profil_bulan_id');
        $profil = ProfilBulanModel::query()->findOrFail($profilId);

        $periodStart = Carbon::parse($profil->start_date)->startOfDay();
        $periodEnd = Carbon::parse($profil->end_date)->startOfDay();
        $filterDateFrom = $request->filled('date_from') ? Carbon::parse($request->input('date_from'))->startOfDay() : null;
        $filterDateTo = $request->filled('date_to') ? Carbon::parse($request->input('date_to'))->startOfDay() : null;
        $effectiveStart = $filterDateFrom && $filterDateFrom->gt($periodStart) ? $filterDateFrom : $periodStart->copy();
        $effectiveEnd = $filterDateTo && $filterDateTo->lt($periodEnd) ? $filterDateTo : $periodEnd->copy();

        if ($effectiveStart->gt($effectiveEnd)) {
            return response()->json(['message' => 'Rentang tanggal tidak valid.'], 422);
        }

        $assignmentsQuery = ProfilBulanKaryawanModel::query()
            ->with(['karyawan:id,employee_code,full_name,jabatan_id', 'karyawan.jabatan:id,name', 'profilJamKerja:id,name,start_time,end_time,break_start_time,break_end_time,work_minutes_per_day', 'profilGaji:id,code,name,monthly_hour_base'])
            ->where('profil_bulan_id', $profilId)
            ->where('is_active', true);
        if ($request->filled('karyawan_id')) {
            $assignmentsQuery->where('karyawan_id', (int) $request->input('karyawan_id'));
        }

        $assignments = $assignmentsQuery->get();
        if ($assignments->isEmpty()) {
            return response()->json(['message' => 'Tidak ada data karyawan pada profil bulan ini.'], 422);
        }

        $employeeIds = $assignments->pluck('karyawan_id')->filter()->map(fn ($id) => (int) $id)->unique()->values();
        $assignmentByEmployee = $assignments->keyBy(fn ($row) => (int) $row->karyawan_id);

        $reviewRows = AttendanceDailyReviewModel::query()
            ->where('profil_bulan_id', $profilId)
            ->whereIn('karyawan_id', $employeeIds)
            ->whereDate('work_date', '>=', $effectiveStart->format('Y-m-d'))
            ->whereDate('work_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->get()
            ->keyBy(fn (AttendanceDailyReviewModel $row) => ((int) $row->karyawan_id).'|'.optional($row->work_date)->format('Y-m-d'));

        $calendarMarks = $this->buildCalendarMarks($effectiveStart->copy(), $effectiveEnd->copy());
        $holidayMap = $calendarMarks['holiday_map'] ?? [];
        $workdayMap = $calendarMarks['workday_map'] ?? [];
        $holidaySpecialMap = $calendarMarks['holiday_special_map'] ?? [];
        $overtimeTags = $this->buildOvertimeTagMap($employeeIds, $effectiveStart->copy(), $effectiveEnd->copy());
        $overtimeApprovedMap = $this->buildOvertimeApprovedMap($employeeIds, $effectiveStart->copy(), $effectiveEnd->copy());

        $leaveRows = LeaveRequestModel::query()
            ->where('status', 'approved')
            ->whereIn('karyawan_id', $employeeIds)
            ->whereDate('start_date', '<=', $effectiveEnd->format('Y-m-d'))
            ->whereDate('end_date', '>=', $effectiveStart->format('Y-m-d'))
            ->get(['karyawan_id', 'leave_type', 'is_payable', 'start_date', 'end_date']);

        // Map leave approved per karyawan per tanggal (for payable HK credit)
        $leaveApprovedMap = [];
        foreach ($leaveRows as $leave) {
            $from = Carbon::parse($leave->start_date)->startOfDay();
            $to = Carbon::parse($leave->end_date)->startOfDay();
            if ($to->lt($from)) {
                $to = $from->copy();
            }
            if ($from->lt($effectiveStart)) {
                $from = $effectiveStart->copy();
            }
            if ($to->gt($effectiveEnd)) {
                $to = $effectiveEnd->copy();
            }
            foreach (CarbonPeriod::create($from, $to) as $date) {
                $key = ((int) $leave->karyawan_id).'|'.$date->format('Y-m-d');
                $leaveApprovedMap[$key] = [
                    'leave_type' => strtolower(trim((string) ($leave->leave_type ?: ''))),
                    'is_payable' => (bool) ($leave->is_payable ?? false),
                ];
            }
        }

        $leaveCountDateMap = [];
        foreach ($leaveRows as $leave) {
            $from = Carbon::parse($leave->start_date)->startOfDay();
            $to = Carbon::parse($leave->end_date)->startOfDay();
            if ($to->lt($from)) {
                $to = $from->copy();
            }
            if ($from->lt($effectiveStart)) {
                $from = $effectiveStart->copy();
            }
            if ($to->gt($effectiveEnd)) {
                $to = $effectiveEnd->copy();
            }
            foreach (CarbonPeriod::create($from, $to) as $date) {
                $empKey = (int) $leave->karyawan_id;
                $typeKey = $this->classifyCalculationSheetLeaveCounterKey((string) ($leave->leave_type ?: ''));
                if ($typeKey === null) {
                    continue;
                }
                $dateKey = $date->format('Y-m-d');
                $leaveCountDateMap[$empKey][$typeKey][$dateKey] = true;
            }
        }
        $leaveCountMap = [];
        foreach ($leaveCountDateMap as $empKey => $types) {
            foreach ($types as $typeKey => $dateFlags) {
                $leaveCountMap[(int) $empKey][$typeKey] = count($dateFlags);
            }
        }

        $collectiveLeaveDays = 0;
        foreach (CarbonPeriod::create($effectiveStart->copy(), $effectiveEnd->copy()) as $date) {
            $dateKey = $date->format('Y-m-d');
            $holidayName = strtolower(trim((string) ($holidayMap[$dateKey] ?? '')));
            if ($holidayName === '' || $holidayName === 'weekend') {
                continue;
            }
            if (str_contains($holidayName, 'cuti bersama') || str_contains($holidayName, 'collective')) {
                $collectiveLeaveDays++;
            }
        }

        $profileIds = $assignments->pluck('profil_perkalian_jam_id')->filter()->map(fn ($id) => (int) $id)->unique()->values();
        $rulesByProfile = [];
        if ($profileIds->isNotEmpty()) {
            $rulesByProfile = ProfilPerkalianJamDetailModel::query()
                ->whereIn('profil_perkalian_jam_id', $profileIds)
                ->where('is_active', true)
                ->orderBy('sort_order')
                ->orderBy('hour_start')
                ->get()
                ->groupBy('profil_perkalian_jam_id')
                ->map(function ($rows) {
                    return $rows->map(fn ($row) => [
                        'day_type' => (string) $row->day_type,
                        'hour_start' => (float) ($row->hour_start ?? 0),
                        'hour_end' => (float) ($row->hour_end ?? 0),
                        'multiplier' => (float) ($row->multiplier ?? 1),
                        'is_break' => (bool) ($row->is_break ?? false),
                    ])->values()->all();
                })
                ->all();
        }

        $periodDates = collect(CarbonPeriod::create($effectiveStart->copy(), $effectiveEnd->copy()))
            ->map(fn (Carbon $date) => $date->copy())
            ->values();

        $sheets = [];
        $hkBasis = max(1, (int) ($profil->hk_basis ?? 21));
        $hkHoursPerDay = max(1.0, (float) ($profil->jam_per_hari ?? 8));
        $hkBaseHours = $hkBasis * $hkHoursPerDay;
        $holidayCountsAsHk = (bool) ($profil->holiday_counts_as_hk ?? true);
        $holidayWeekendCounts = (bool) ($profil->holiday_weekend_counts ?? false);
        $countIzinAsHk = (bool) ($profil->count_izin_as_hk ?? true);
        $countSakitAsHk = (bool) ($profil->count_sakit_as_hk ?? true);
        $countCutiAsHk = (bool) ($profil->count_cuti_as_hk ?? true);
        foreach ($employeeIds as $karyawanId) {
            $assignment = $assignmentByEmployee->get((int) $karyawanId);
            if (! $assignment) {
                continue;
            }
            $detailPayloadForSheet = $this->buildCalculationDetailPayload([
                'profil_bulan_id' => $profilId,
                'assignment_profil_bulan_id' => (int) $assignment->profil_bulan_id,
                'karyawan_id' => (int) $karyawanId,
                'date_from' => $effectiveStart->format('Y-m-d'),
                'date_to' => $effectiveEnd->format('Y-m-d'),
            ]);
            $detailRowsByDateForSheet = collect($detailPayloadForSheet['rows'] ?? [])
                ->keyBy(fn ($row) => (string) ($row['work_date'] ?? ''));
            $payrollBasisForSheet = is_array($detailPayloadForSheet['payrollBasis'] ?? null)
                ? (array) $detailPayloadForSheet['payrollBasis']
                : $this->resolveCalculationPayrollBasis($profil, $assignment, $effectiveStart->copy(), $effectiveEnd->copy());
            $hkHoursPerDay = max(1.0, (float) ($payrollBasisForSheet['hours_per_day'] ?? $hkHoursPerDay));
            $sheetHkBaseHours = max(1.0, (float) ($payrollBasisForSheet['monthly_hour_base'] ?? $hkBaseHours));
            $isDailySalaryOverride = $this->isDailySalaryOverride((int) $assignment->id, $effectiveEnd->copy());
            if ($isDailySalaryOverride) {
                $workdays = 0;
                foreach ($periodDates as $date) {
                    $dateKey = $date->format('Y-m-d');
                    if (isset($workdayMap[$dateKey]) || ! isset($holidayMap[$dateKey])) {
                        $workdays++;
                    }
                }
                $sheetHkBaseHours = max(1.0, $workdays * $hkHoursPerDay);
            }

            $rules = $assignment->profil_perkalian_jam_id
                ? ($rulesByProfile[(int) $assignment->profil_perkalian_jam_id] ?? [])
                : [];
            $rows = [];
            $otColumns = is_array($detailPayloadForSheet['otColumns'] ?? null)
                ? array_values($detailPayloadForSheet['otColumns'])
                : $this->resolveOvertimeColumnsFromRules($rules);
            $otSums = collect($otColumns)->mapWithKeys(fn ($column) => [(string) ($column['key'] ?? '') => 0.0])->all();
            $sum = [
                'total_jam_masuk' => 0.0,
                'std_jam_normal' => 0.0,
                'jam_normal' => 0.0,
                'jam_kurang' => 0.0,
            ];

            foreach ($periodDates as $date) {
                $dateKey = $date->format('Y-m-d');
                $detailRow = (array) ($detailRowsByDateForSheet->get($dateKey) ?? []);
                $isOffShift = ! empty($detailRow['is_off_day'])
                    || strtolower(trim((string) ($detailRow['applied_shift_code'] ?? ''))) === 'off';
                $actualHours = $isOffShift ? 0.0 : round((float) ($detailRow['actual_hours'] ?? 0), 1);
                $plannedHours = $isOffShift ? 0.0 : round((float) ($detailRow['planned_hours'] ?? 0), 1);
                $normalHours = $isOffShift ? 0.0 : round((float) ($detailRow['normal_hours'] ?? 0), 1);
                $otDynamic = collect($otColumns)->mapWithKeys(fn ($column) => [
                    (string) ($column['key'] ?? '') => $isOffShift ? 0.0 : round((float) (($detailRow['ot_dynamic'] ?? [])[$column['key'] ?? ''] ?? 0), 1),
                ])->all();
                $dayCredit = AttendanceDayCreditResolver::resolve($detailRow, $profil, $hkHoursPerDay);
                $dailyDeficitHours = $isOffShift ? 0.0 : max(0.0, (float) ($dayCredit['deficit_hours'] ?? 0));
                $rows[] = [
                    'date' => $date->copy(),
                    'day_label' => $date->translatedFormat('D'),
                    'is_holiday' => isset($holidayMap[$dateKey]),
                    'is_off_shift' => $isOffShift,
                    'masuk' => $isOffShift ? '-' : ((string) ($detailRow['in_time'] ?? '-')),
                    'keluar' => $isOffShift ? '-' : ((string) ($detailRow['out_time'] ?? '-')),
                    'total_jam_masuk' => $actualHours > 0 ? $actualHours : null,
                    'std_jam_normal' => $plannedHours,
                    'jam_normal' => $normalHours,
                    'ot_dynamic' => $otDynamic,
                    'remark' => $isOffShift ? ((string) ($detailRow['schedule_badge_label'] ?? '') === 'Belum Ada Shift' ? 'Belum ada shift / bisa jadi libur.' : 'LIBUR (OFF shift).') : trim(((string) ($detailRow['reason'] ?? 'Normal')) . ' | ' . (((string) ($detailRow['applied_shift_code'] ?? '')) ?: ((string) ($detailRow['applied_shift_name'] ?? '')))),
                ];
                $sum['total_jam_masuk'] += $actualHours;
                $sum['std_jam_normal'] += $plannedHours;
                $sum['jam_normal'] += $normalHours;
                $sum['jam_kurang'] += $dailyDeficitHours;
                foreach ($otDynamic as $key => $value) {
                    $otSums[$key] = ($otSums[$key] ?? 0.0) + (float) $value;
                }
            }

            $hakCuti = $assignment->annual_leave_eligible ? 12 : 0;
            $empLeave = $leaveCountMap[(int) $karyawanId] ?? [];
            $cutiPribadi = (int) ($empLeave['annual'] ?? 0);
            $cutiBersama = (int) ($empLeave['collective'] ?? 0) + $collectiveLeaveDays;
            $sisaCuti = max(0, $hakCuti - $cutiBersama - $cutiPribadi);
            $otWeightedSums = collect($otColumns)
                ->mapWithKeys(function (array $otCol) use ($otSums) {
                    $key = (string) ($otCol['key'] ?? '');
                    $multiplier = (float) ($otCol['multiplier'] ?? 1);

                    return [$key => round(((float) ($otSums[$key] ?? 0)) * $multiplier, 1)];
                })
                ->all();

            $sheets[] = [
                'employee_code' => $assignment->karyawan?->employee_code ?: '-',
                'employee_name' => $assignment->karyawan?->full_name ?: '-',
                'jabatan' => $assignment->karyawan?->jabatan?->name ?: '-',
                'finger_no' => preg_replace('/\D+/', '', (string) ($assignment->karyawan?->employee_code ?: '')) ?: '-',
                'bulan_label' => Carbon::parse($effectiveStart)->translatedFormat('F Y'),
                'rows' => $rows,
                'ot_columns' => $otColumns,
                'is_daily_salary_override' => $isDailySalaryOverride,
                'sum' => [
                    'total_jam_masuk' => round($sum['total_jam_masuk'], 1),
                    'std_jam_normal' => round($sum['std_jam_normal'], 1),
                    'jam_normal' => round($sum['jam_normal'], 1),
                    'ot_dynamic' => collect($otSums)->map(fn ($v) => round((float) $v, 1))->all(),
                    'ot_weighted_dynamic' => $otWeightedSums,
                    'total_lembur_weighted' => round(array_sum($otWeightedSums), 1),
                    'basis_jam_profil' => round($sheetHkBaseHours, 1),
                    'hk_masuk' => round($hkHoursPerDay > 0 ? ((max(0.0, $sheetHkBaseHours - $sum['jam_kurang'])) / $hkHoursPerDay) : 0.0, 1),
                    'jam_tidak_masuk' => round(max(0.0, $sum['jam_kurang']), 1),
                    'jam_masuk_normal' => round(max(0.0, $sheetHkBaseHours - $sum['jam_kurang']), 1),
                    'jam_masuk_aktual' => round($sum['total_jam_masuk'], 1),
                ],
                'leave' => [
                    'hak_cuti' => $hakCuti,
                    'cuti_bersama' => $cutiBersama,
                    'cuti_pribadi' => $cutiPribadi,
                    'sisa_cuti' => $sisaCuti,
                    'note' => $hakCuti > 0 ? '' : 'Belum eligible cuti tahunan',
                ],
            ];
        }

        return view('attendancereview::exports.calculation_sheet', [
            'company_name' => 'PT. Hikari Teknologi Indonesia',
            'profil' => $profil,
            'date_from' => $effectiveStart->format('Y-m-d'),
            'date_to' => $effectiveEnd->format('Y-m-d'),
            'sheets' => $sheets,
            'generated_at' => now()->format('Y-m-d H:i:s'),
        ]);
    }

    // =========================================================================
    // requestCalculationZip() - Request pembuatan ZIP kalkulasi
    // Dipanggil dari: POST /attendance-review/calculations/zip/request
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function requestCalculationZip(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'karyawan_id' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['required_without:karyawan_id', 'array', 'min:1', 'max:50'],
            'karyawan_ids.*' => ['integer', 'distinct', 'exists:master_karyawans,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $selectedKaryawanIds = collect($request->input('karyawan_ids', []))
            ->map(fn ($id) => (int) $id)
            ->filter()
            ->unique()
            ->values()
            ->all();
        if ($selectedKaryawanIds === [] && $request->filled('karyawan_id')) {
            $selectedKaryawanIds = [(int) $request->input('karyawan_id')];
        }

        $exportJob = AttendanceExportJobModel::query()->create([
            'request_no' => 'ARZ-'.now()->format('YmdHis').'-'.Str::upper(Str::random(4)),
            'user_id' => auth()->id(),
            'profil_bulan_id' => (int) $request->input('profil_bulan_id'),
            'filters' => [
                'karyawan_ids' => $selectedKaryawanIds,
                'date_from' => $request->input('date_from') ?: null,
                'date_to' => $request->input('date_to') ?: null,
            ],
            'status' => 'pending',
            'total_users' => 0,
            'processed_users' => 0,
        ]);

        GenerateCalculationZipJob::dispatch((int) $exportJob->id)->onQueue(self::QUEUE_NAME);

        return response()->json([
            'message' => 'Proses generate ZIP dimulai di background.',
            'data' => [
                'job_id' => (int) $exportJob->id,
                'request_no' => $exportJob->request_no,
            ],
        ]);
    }

    // =========================================================================
    // calculationZipStatus() - Cek status pembuatan ZIP kalkulasi
    // Dipanggil dari: GET /attendance-review/calculations/zip/{id}/status
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function calculationZipStatus(string $id): JsonResponse
    {
        $row = AttendanceExportJobModel::query()->findOrFail((int) $id);
        $downloadUrl = null;
        if ($row->status === 'done' && ! empty($row->zip_path) && Storage::disk('public')->exists($row->zip_path)) {
            $downloadUrl = route('attendance_review_v2.calculations.zip.download', ['id' => (int) $row->id]);
        }

        return response()->json([
            'data' => [
                'id' => (int) $row->id,
                'request_no' => $row->request_no,
                'status' => $row->status,
                'total_users' => (int) ($row->total_users ?? 0),
                'processed_users' => (int) ($row->processed_users ?? 0),
                'progress_percent' => (int) (((int) ($row->total_users ?? 0) > 0)
                    ? floor((((int) $row->processed_users) / max(1, (int) $row->total_users)) * 100)
                    : 0),
                'error_message' => $row->error_message,
                'download_url' => $downloadUrl,
                'started_at' => optional($row->started_at)->format('Y-m-d H:i:s'),
                'finished_at' => optional($row->finished_at)->format('Y-m-d H:i:s'),
            ],
        ]);
    }

    // =========================================================================
    // downloadCalculationZip() - Download file ZIP kalkulasi
    // Dipanggil dari: GET /attendance-review/calculations/zip/{id}/download
    // Output: View (halaman Blade template)
    // =========================================================================
    public function downloadCalculationZip(string $id)
    {
        $row = AttendanceExportJobModel::query()->findOrFail((int) $id);
        if ($row->status !== 'done' || empty($row->zip_path) || ! Storage::disk('public')->exists($row->zip_path)) {
            abort(404, 'File ZIP belum tersedia.');
        }
        $absPath = storage_path('app/public/'.$row->zip_path);
        $filename = basename($row->zip_path);

        return response()->download($absPath, $filename);
    }

    // =========================================================================
    // approveReview() - Approve satu review attendance
    // Dipanggil dari: POST /attendance-review/reviews/{id}/approve
    // Output: View (halaman Blade template)
    // =========================================================================

    public function createAttendanceQuestion(string $id, Request $request): JsonResponse
    {
        $review = AttendanceDailyReviewModel::query()->with('karyawan')->findOrFail((int) $id);
        $status = strtolower(trim((string) ($review->status ?? '')));
        if (!in_array($status, ['missing_in', 'missing_out', 'unpaired', 'shift_transition', 'no_log'], true)) {
            return response()->json(['message' => 'Question hanya dapat dibuat untuk presensi yang bermasalah.'], 422);
        }
        if (Schema::hasTable('attendance_questions')) {
            $existing = AttendanceQuestionModel::query()
                ->where('attendance_daily_review_id', (int) $review->id)
                ->whereIn('status', ['pending_answer', 'answered', 'converted_to_fc'])
                ->latest('id')
                ->first();
            if ($existing) {
                return response()->json(['message' => 'Question untuk tanggal ini sudah ada.', 'question_id' => (int) $existing->id], 422);
            }
        }

        $missingType = match ($status) {
            'missing_in' => 'missing_in',
            'missing_out' => 'missing_out',
            default => ($review->checkin_at && !$review->checkout_at) ? 'missing_out' : (($review->checkout_at && !$review->checkin_at) ? 'missing_in' : 'missing_both'),
        };
        $question = AttendanceQuestionModel::query()->create([
            'karyawan_id' => (int) $review->karyawan_id,
            'attendance_daily_review_id' => (int) $review->id,
            'work_date' => $review->work_date,
            'missing_type' => $missingType,
            'question_type' => 'attendance_clarification',
            'question_text' => 'Mohon klarifikasi presensi tanggal ' . optional($review->work_date)->format('d-m-Y') . ': ' . str_replace('_', ' ', $missingType) . '.',
            'status' => 'pending_answer',
            'created_by' => auth()->id(),
        ]);

        return response()->json(['message' => 'Question terkirim ke mobile karyawan.', 'question_id' => (int) $question->id]);
    }
    public function bulkCreateAttendanceQuestions(Request $request): JsonResponse
    {
        $ids = collect($request->input('karyawan_ids', []))->filter()->map(fn ($id) => (int) $id)->unique()->values();
        $dateFrom = trim((string) $request->input('date_from', ''));
        $dateTo = trim((string) $request->input('date_to', ''));
        if ($ids->isEmpty() || $dateFrom === '' || $dateTo === '') {
            return response()->json(['message' => 'Pilih user dan periode terlebih dahulu.'], 422);
        }
        $reviews = AttendanceDailyReviewModel::query()
            ->whereIn('karyawan_id', $ids->all())
            ->whereBetween('work_date', [$dateFrom, $dateTo])
            ->whereIn('status', ['missing_in', 'missing_out', 'unpaired', 'shift_transition', 'no_log'])
            ->orderBy('work_date')->get();
        $created = 0;
        $skipped = 0;
        foreach ($reviews as $review) {
            $response = $this->createAttendanceQuestion((string) $review->id, $request);
            $response->getStatusCode() === 200 ? $created++ : $skipped++;
        }
        return response()->json(['message' => "Bulk Question FC selesai. Dibuat: {$created}, dilewati: {$skipped}.", 'created' => $created, 'skipped' => $skipped, 'eligible' => $reviews->count()]);
    }
    public function approveReview(string $id): JsonResponse
    {
        $row = AttendanceDailyReviewModel::query()->findOrFail($id);
        if ($guard = $this->guardProfilBulanOpenForAttendance(ProfilBulanModel::query()->find((int) $row->profil_bulan_id))) {
            return $guard;
        }
        $this->applyApproveToReview($row, 'Review di-approve dari halaman Attendance Review.');

        return response()->json(['message' => 'Review attendance approved']);
    }

    // =========================================================================
    // manualUpdateReviewTime() - Update manual waktu review
    // Dipanggil dari: POST /attendance-review/reviews/{id}/manual-time
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function manualUpdateReviewTime(Request $request, string $id): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'checkin_time' => ['nullable', 'string', 'max:19'],
            'checkout_time' => ['nullable', 'string', 'max:19'],
            'notes' => ['nullable', 'string', 'max:255'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $review = AttendanceDailyReviewModel::query()->with('karyawan:id,employee_code,full_name')->findOrFail((int) $id);
        if ($request->boolean('reset_prediction')) {
            $reviewDate = Carbon::parse((string) $review->work_date)->startOfDay();
            $partnerDate = null;
            if ($review->checkout_at) {
                $checkoutDate = Carbon::parse((string) $review->checkout_at)->startOfDay();
                if ($checkoutDate->ne($reviewDate)) {
                    $partnerDate = $checkoutDate;
                }
            }
            if (! $partnerDate) {
                $previousPartner = AttendanceDailyReviewModel::query()
                    ->where('profil_bulan_id', (int) $review->profil_bulan_id)
                    ->where('karyawan_id', (int) $review->karyawan_id)
                    ->whereDate('checkout_at', $reviewDate->format('Y-m-d'))
                    ->where('checkout_at', '>', DB::raw('planned_shift_end'))
                    ->latest('id')
                    ->first();
                $partnerDate = $previousPartner?->work_date ? Carbon::parse((string) $previousPartner->work_date)->startOfDay() : null;
            }
            $resetDates = [$reviewDate->format('Y-m-d')];
            if ($partnerDate && ! in_array($partnerDate->format('Y-m-d'), $resetDates, true)) {
                $resetDates[] = $partnerDate->format('Y-m-d');
            }
            DB::transaction(function () use ($review, $resetDates): void {
                $targets = AttendanceDailyReviewModel::query()
                    ->where('profil_bulan_id', (int) $review->profil_bulan_id)
                    ->where('karyawan_id', (int) $review->karyawan_id)
                    ->whereIn('work_date', $resetDates)
                    ->get();
                $targetIds = $targets->pluck('id')->filter()->map(fn ($id) => (int) $id)->values()->all();
                if ($targetIds) {
                    DB::table('attendance_daily_review_histories')
                        ->whereIn('attendance_daily_review_id', $targetIds)
                        ->whereIn('action', ['manual_time_set', 'reset_prediction'])
                        ->delete();
                }
                foreach ($targets as $target) {
                    $before = $this->snapshotReview($target);
                    $target->checkin_at = null;
                    $target->checkout_at = null;
                    $target->suggested_checkin_at = null;
                    $target->suggested_checkout_at = null;
                    $target->status = 'no_log';
                    $target->confidence_score = 0;
                    $target->is_approved = false;
                    $target->approved_by = null;
                    $target->approved_at = null;
                    $target->reason = 'RESET_PREDICTION::Raw log tetap tersimpan; hasil pairing dihapus.';
                    $target->save();
                    $this->saveHistory($target, 'reset_prediction', $before, $this->snapshotReview($target), $target->reason);
                }
            });
            $result = $this->processDetectionJob((int) $review->profil_bulan_id, null, (int) $review->karyawan_id, null);
            return response()->json([
                'message' => 'Pasangan prediksi direset dan deteksi ulang 1 user selesai.',
                'reset_dates' => $resetDates,
                'affected' => (int) ($result['affected'] ?? 0),
            ]);
        }
        if ($guard = $this->guardProfilBulanOpenForAttendance(ProfilBulanModel::query()->find((int) $review->profil_bulan_id))) {
            return $guard;
        }
        $workDate = optional($review->work_date)->format('Y-m-d');
        if (! $workDate) {
            return response()->json(['message' => 'Work date tidak valid.'], 422);
        }

        $parseTime = static function (?string $t) use ($workDate): ?Carbon {
            $raw = trim((string) ($t ?? ''));
            if ($raw === '' || $raw === '-' || strtolower($raw) === 'null') {
                return null;
            }

            $formats = preg_match('/^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}(:\d{2})?$/', $raw)
                ? ['Y-m-d H:i', 'Y-m-d H:i:s']
                : ['H:i', 'H:i:s'];

            foreach ($formats as $format) {
                try {
                    $value = str_starts_with($format, 'Y-m-d') ? $raw : ($workDate.' '.$raw);
                    $fullFormat = str_starts_with($format, 'Y-m-d') ? $format : ('Y-m-d '.$format);
                    $parsed = Carbon::createFromFormat('!'.$fullFormat, $value);
                    if ($parsed && $parsed->format($fullFormat) === $value) {
                        return $parsed;
                    }
                } catch (\Throwable) {
                    // Try the next supported format before returning a validation error.
                }
            }

            return null;
        };

        $newIn = $parseTime($request->input('checkin_time'));
        $newOut = $parseTime($request->input('checkout_time'));
        if (($request->filled('checkin_time') && ! $newIn) || ($request->filled('checkout_time') && ! $newOut)) {
            return response()->json(['message' => 'Format jam tidak valid. Gunakan HH:MM atau YYYY-MM-DD HH:MM.'], 422);
        }

        // If only one side is provided, keep the other side as-is.
        $oldIn = $review->checkin_at ? Carbon::parse((string) $review->checkin_at) : null;
        $oldOut = $review->checkout_at ? Carbon::parse((string) $review->checkout_at) : null;
        $effectiveIn = $newIn ?: $oldIn;
        $effectiveOut = $newOut ?: $oldOut;

        // Support cross-day: if OUT time is earlier than IN time, assume next day.
        if ($effectiveIn && $effectiveOut && $effectiveOut->lte($effectiveIn)) {
            $effectiveOut = $effectiveOut->copy()->addDay();
        }

        if ($effectiveIn && $effectiveOut && $effectiveOut->lte($effectiveIn)) {
            return response()->json(['message' => 'Jam OUT harus lebih besar dari jam IN.'], 422);
        }

        $before = $this->snapshotReview($review);
        DB::transaction(function () use ($review, $effectiveIn, $effectiveOut, $before, $request, $workDate): void {
            $review->checkin_at = $effectiveIn?->format('Y-m-d H:i:s');
            $review->checkout_at = $effectiveOut?->format('Y-m-d H:i:s');

            // Normalize status so UI doesn't show "No Log" when times exist.
            if ($review->checkin_at && $review->checkout_at) {
                $review->status = 'normal';
            } elseif ($review->checkin_at && ! $review->checkout_at) {
                $review->status = 'missing_out';
            } elseif (! $review->checkin_at && $review->checkout_at) {
                $review->status = 'missing_in';
            } else {
                $review->status = 'no_log';
            }

            // Manual changes should require re-approval.
            $review->is_approved = false;
            $review->approved_by = null;
            $review->approved_at = null;
            $review->confidence_score = 100.0;
            $review->reason = trim((string) ($review->reason ?? ''));
            $note = trim((string) $request->input('notes', 'Manual koreksi jam.'));
            if (! str_contains($review->reason, 'MANUAL_TIME_LOCK::')) {
                $review->reason = trim(($review->reason ? $review->reason."\n" : '').'MANUAL_TIME_LOCK::Jam dikunci dari koreksi manual.');
            }
            if ($note !== '') {
                $review->reason = $review->reason === '' ? $note : ($review->reason."\n".$note);
            }

            $review->save();

            if ($effectiveOut && $effectiveOut->toDateString() !== $workDate) {
                $nextReview = AttendanceDailyReviewModel::query()
                    ->where('profil_bulan_id', (int) $review->profil_bulan_id)
                    ->where('karyawan_id', (int) $review->karyawan_id)
                    ->whereDate('work_date', $effectiveOut->toDateString())
                    ->first();

                if ($nextReview && empty($nextReview->checkout_at)) {
                    $outKey = $effectiveOut->format('Y-m-d H:i');
                    $nextInKey = $nextReview->checkin_at ? Carbon::parse((string) $nextReview->checkin_at)->format('Y-m-d H:i') : '';
                    $nextSuggestedInKey = $nextReview->suggested_checkin_at ? Carbon::parse((string) $nextReview->suggested_checkin_at)->format('Y-m-d H:i') : '';
                    $nextRawKeys = AttendanceLogModel::query()
                        ->where('karyawan_id', (int) $review->karyawan_id)
                        ->whereDate('log_at', $effectiveOut->toDateString())
                        ->get(['log_at'])
                        ->map(fn ($row) => Carbon::parse((string) $row->log_at)->format('Y-m-d H:i'))
                        ->unique()
                        ->values();
                    $hasOnlyConsumedRawLog = $nextRawKeys->count() === 1 && $nextRawKeys->first() === $outKey;

                    if ($outKey === $nextInKey || $outKey === $nextSuggestedInKey || $hasOnlyConsumedRawLog) {
                        $nextBefore = $this->snapshotReview($nextReview);
                        $nextReview->checkin_at = null;
                        $nextReview->suggested_checkin_at = null;
                        $nextReview->status = 'no_log';
                        $nextReview->is_approved = false;
                        $nextReview->approved_by = null;
                        $nextReview->approved_at = null;
                        $nextReview->reason = trim((string) ($nextReview->reason ?? ''));
                        $consumeNote = 'Log '.$outKey.' dipakai sebagai OUT lintas hari tanggal '.$workDate.'.';
                        $nextReview->reason = $nextReview->reason === '' ? $consumeNote : ($nextReview->reason."\n".$consumeNote);
                        $nextReview->save();
                        $this->saveHistory(
                            $nextReview,
                            'manual_time_cross_day_consume',
                            $nextBefore,
                            $this->snapshotReview($nextReview),
                            $consumeNote
                        );
                    }
                }
            }

            $this->saveHistory(
                $review,
                'manual_time_set',
                $before,
                $this->snapshotReview($review),
                'Koreksi jam manual dari Attendance Review.'
            );
        });

        return response()->json([
            'message' => 'Jam berhasil dikoreksi.',
            'data' => [
                'id' => (int) $review->id,
                'work_date' => $workDate,
                'employee_code' => $review->karyawan?->employee_code,
                'employee_name' => $review->karyawan?->full_name,
                'checkin_at' => optional($review->checkin_at)->format('Y-m-d H:i:s'),
                'checkout_at' => optional($review->checkout_at)->format('Y-m-d H:i:s'),
                'status' => $review->status,
                'is_approved' => (bool) $review->is_approved,
            ],
        ]);
    }

    // =========================================================================
    // approveOfflineLogs() - Approve log offline
    // Dipanggil dari: POST /attendance-review/reviews/{id}/offline-approve
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function approveOfflineLogs(string $id): JsonResponse
    {
        $review = AttendanceDailyReviewModel::query()->findOrFail((int) $id);
        if ($guard = $this->guardProfilBulanOpenForAttendance(ProfilBulanModel::query()->find((int) $review->profil_bulan_id))) {
            return $guard;
        }
        $workDate = optional($review->work_date)->format('Y-m-d');
        if (! $workDate || ! $review->karyawan_id) {
            return response()->json(['message' => 'Data review tidak valid.'], 422);
        }

        $logs = AttendanceLogModel::query()
            ->where('karyawan_id', (int) $review->karyawan_id)
            ->whereDate('log_at', $workDate)
            ->where('notes', 'like', '%OFFLINE_PENDING_APPROVAL%')
            ->get();
        if ($logs->isEmpty()) {
            return response()->json(['message' => 'Tidak ada log offline yang menunggu approval.'], 422);
        }

        $approvedCount = 0;
        DB::transaction(function () use ($logs, $review, &$approvedCount): void {
            foreach ($logs as $log) {
                $notes = $this->rewriteOfflineMarker((string) ($log->notes ?? ''), 'OFFLINE_APPROVED');
                $log->notes = $notes;
                $log->validation_status = 'passed';
                $log->validation_reason = null;
                $log->is_active = true;
                $log->save();
                $approvedCount++;
            }

            $before = $this->snapshotReview($review);
            $review->reason = trim((string) ($review->reason ?? ''));
            if ($review->reason !== '') {
                $review->reason .= "\n";
            }
            $review->reason .= 'Offline log approved: '.$approvedCount.' item(s).';
            $review->save();
            $this->saveHistory(
                $review,
                'offline_logs_approved',
                $before,
                $this->snapshotReview($review),
                'Approve offline logs dari Attendance Review.'
            );
        });

        return response()->json(['message' => "Offline log approved: {$approvedCount} item."]);
    }

    // =========================================================================
    // rejectOfflineLogs() - Reject log offline
    // Dipanggil dari: POST /attendance-review/reviews/{id}/offline-reject
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function rejectOfflineLogs(string $id): JsonResponse
    {
        $review = AttendanceDailyReviewModel::query()->findOrFail((int) $id);
        if ($guard = $this->guardProfilBulanOpenForAttendance(ProfilBulanModel::query()->find((int) $review->profil_bulan_id))) {
            return $guard;
        }
        $workDate = optional($review->work_date)->format('Y-m-d');
        if (! $workDate || ! $review->karyawan_id) {
            return response()->json(['message' => 'Data review tidak valid.'], 422);
        }

        $logs = AttendanceLogModel::query()
            ->where('karyawan_id', (int) $review->karyawan_id)
            ->whereDate('log_at', $workDate)
            ->where('notes', 'like', '%OFFLINE_PENDING_APPROVAL%')
            ->get();
        if ($logs->isEmpty()) {
            return response()->json(['message' => 'Tidak ada log offline yang menunggu approval.'], 422);
        }

        $rejectedCount = 0;
        DB::transaction(function () use ($logs, $review, &$rejectedCount): void {
            foreach ($logs as $log) {
                $notes = $this->rewriteOfflineMarker((string) ($log->notes ?? ''), 'OFFLINE_REJECTED');
                $log->notes = $notes;
                $log->validation_status = 'rejected';
                $log->validation_reason = 'Offline log ditolak reviewer pada '.now()->format('Y-m-d H:i:s');
                $log->is_active = false;
                $log->save();
                $rejectedCount++;
            }

            $before = $this->snapshotReview($review);
            $review->checkin_at = null;
            $review->checkout_at = null;
            $review->suggested_checkin_at = null;
            $review->suggested_checkout_at = null;
            $review->status = 'no_log';
            $review->is_approved = false;
            $review->approved_by = null;
            $review->approved_at = null;
            $review->reason = 'Offline log rejected: '.$rejectedCount.' item(s). Jalankan detect ulang jika diperlukan.';
            $review->save();
            $this->saveHistory(
                $review,
                'offline_logs_rejected',
                $before,
                $this->snapshotReview($review),
                'Reject offline logs dari Attendance Review.'
            );
        });

        return response()->json(['message' => "Offline log rejected: {$rejectedCount} item."]);
    }

    // =========================================================================
    // approveReviewsByDate() - Approve review berdasarkan tanggal
    // Dipanggil dari: POST /attendance-review/reviews/approve-by-date
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function approveReviewsByDate(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'work_date' => ['required', 'date'],
            'karyawan_id' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['required_without:karyawan_id', 'array', 'min:1', 'max:50'],
            'karyawan_ids.*' => ['integer', 'distinct', 'exists:master_karyawans,id'],
            'karyawan_ids' => ['nullable', 'array'],
            'karyawan_ids.*' => ['nullable', 'integer', 'exists:master_karyawans,id'],
            'review_ids' => ['nullable', 'array'],
            'review_ids.*' => ['integer', 'exists:attendance_daily_reviews,id'],
            'safe_only' => ['nullable', 'boolean'],
            'attendance_profile_scope' => ['nullable', 'string', 'in:selected,main,sub,all,both'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profilId = (int) $request->input('profil_bulan_id');
        $profil = ProfilBulanModel::query()->find($profilId);
        if ($guard = $this->guardProfilBulanOpenForAttendance($profil)) {
            return $guard;
        }
        $scope = (string) $request->input('attendance_profile_scope', 'selected');
        $scope = $scope === 'all' ? 'both' : $scope;
        $profileIds = $scope === 'selected'
            ? [$profilId]
            : ($profil ? $this->summaryProfileIds($profil, $scope) : [$profilId]);
        $workDate = Carbon::parse($request->input('work_date'))->format('Y-m-d');
        $safeOnly = $request->boolean('safe_only');
        $filterKaryawanIds = $this->resolveAttendanceReviewKaryawanIds($request);
        $reviewIds = collect($request->input('review_ids', []))
            ->map(fn ($id) => (int) $id)
            ->filter(fn ($id) => $id > 0)
            ->unique()
            ->values();

        $query = AttendanceDailyReviewModel::query()
            ->whereIn('profil_bulan_id', $profileIds)
            ->whereDate('work_date', $workDate);
        if (Schema::hasColumn('attendance_daily_reviews', 'attendance_tag')) {
            $query->where(function ($tagQuery): void {
                $tagQuery->whereNull('attendance_tag')
                    ->orWhere('attendance_tag', '<>', 'leave_approved');
            });
        }
        if (! empty($filterKaryawanIds)) {
            $query->whereIn('karyawan_id', $filterKaryawanIds);
        }
        if ($reviewIds->isNotEmpty()) {
            $query->whereIn('id', $reviewIds);
        }

        $rows = $query->get();
        if ($rows->isEmpty()) {
            if ($reviewIds->isEmpty()) {
                return response()->json([
                    'message' => 'Tidak ada data review pada tanggal ini.',
                    'data' => [
                        'approved' => 0,
                        'skipped' => 0,
                        'work_date' => $workDate,
                    ],
                ]);
            }

            return response()->json(['message' => 'Tidak ada data review yang bisa di-approve pada tanggal ini.'], 422);
        }

        $approvedCount = 0;
        $skippedCount = 0;
        $safeContext = $safeOnly
            ? $this->buildBulkApprovalSafetyContext($rows, $workDate, $profilId)
            : [];
        DB::transaction(function () use ($rows, $safeOnly, $safeContext, &$approvedCount, &$skippedCount): void {
            foreach ($rows as $row) {
                if ((bool) $row->is_approved) {
                    $skippedCount++;

                    continue;
                }
                if ($safeOnly && ! $this->isSafeForBulkCheckApproval($row, $safeContext)) {
                    $skippedCount++;

                    continue;
                }
                $changed = $this->applyApproveToReview(
                    $row,
                    $safeOnly
                        ? 'Approve All (Cek) aman dari matrix Attendance Review.'
                        : 'Bulk approve per tanggal dari matrix Attendance Review.'
                );
                if ($changed) {
                    $approvedCount++;
                } else {
                    $skippedCount++;
                }
            }
        });

        $messagePrefix = $safeOnly ? 'Approve cek aman selesai' : 'Approve tanggal selesai';

        return response()->json([
            'message' => "{$messagePrefix}. Approved: {$approvedCount}, Skip: {$skippedCount}.",
            'data' => [
                'approved' => $approvedCount,
                'skipped' => $skippedCount,
                'safe_only' => $safeOnly,
                'work_date' => $workDate,
            ],
        ]);
    }

    // =========================================================================
    // unapproveReviewsByDate() - Unapprove review berdasarkan tanggal
    // Dipanggil dari: POST /attendance-review/reviews/unapprove-by-date
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function unapproveReviewsByDate(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'work_date' => ['required', 'date'],
            'review_ids' => ['nullable', 'array'],
            'review_ids.*' => ['integer', 'exists:attendance_daily_reviews,id'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profilId = (int) $request->input('profil_bulan_id');
        if ($guard = $this->guardProfilBulanOpenForAttendance(ProfilBulanModel::query()->find($profilId))) {
            return $guard;
        }
        $workDate = Carbon::parse($request->input('work_date'))->format('Y-m-d');
        $reviewIds = collect($request->input('review_ids', []))
            ->map(fn ($id) => (int) $id)
            ->filter(fn ($id) => $id > 0)
            ->unique()
            ->values();

        $query = AttendanceDailyReviewModel::query()
            ->where('profil_bulan_id', $profilId)
            ->whereDate('work_date', $workDate);
        if ($reviewIds->isNotEmpty()) {
            $query->whereIn('id', $reviewIds);
        }

        $rows = $query->get();
        if ($rows->isEmpty()) {
            return response()->json(['message' => 'Tidak ada data review yang bisa di-unapprove pada tanggal ini.'], 422);
        }

        $unapprovedCount = 0;
        $skippedCount = 0;
        DB::transaction(function () use ($rows, &$unapprovedCount, &$skippedCount): void {
            foreach ($rows as $row) {
                if (! (bool) $row->is_approved) {
                    $skippedCount++;

                    continue;
                }
                $before = $this->snapshotReview($row);
                $row->is_approved = false;
                $row->approved_by = null;
                $row->approved_at = null;
                $row->save();

                $this->saveHistory(
                    $row,
                    'unapproved',
                    $before,
                    $this->snapshotReview($row),
                    'Bulk unapprove per tanggal dari matrix Attendance Review.'
                );
                $unapprovedCount++;
            }
        });

        return response()->json([
            'message' => "Unapprove tanggal selesai. Unapproved: {$unapprovedCount}, Skip: {$skippedCount}.",
            'data' => [
                'unapproved' => $unapprovedCount,
                'skipped' => $skippedCount,
                'work_date' => $workDate,
            ],
        ]);
    }

    // =========================================================================
    // rejectHolidayHours() - Reject jam hari libur
    // Dipanggil dari: POST /attendance-review/reviews/{id}/reject-hours
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function rejectHolidayHours(string $id): JsonResponse
    {
        $row = AttendanceDailyReviewModel::query()->findOrFail($id);
        if ($guard = $this->guardProfilBulanOpenForAttendance(ProfilBulanModel::query()->find((int) $row->profil_bulan_id))) {
            return $guard;
        }
        $workDate = optional($row->work_date)->format('Y-m-d');
        if (! $workDate) {
            return response()->json(['message' => 'Work date tidak valid.'], 422);
        }

        $calendarMarks = $this->buildCalendarMarks(
            Carbon::parse($workDate)->startOfDay(),
            Carbon::parse($workDate)->startOfDay()
        );
        $isHoliday = isset($calendarMarks['holiday_map'][$workDate]);
        if (! $isHoliday) {
            return response()->json(['message' => 'Tolak jam hanya berlaku pada hari libur.'], 422);
        }

        $overtimeTags = $this->buildOvertimeTagMap(
            collect([(int) $row->karyawan_id]),
            Carbon::parse($workDate)->startOfDay(),
            Carbon::parse($workDate)->startOfDay()
        );
        $tagKey = $overtimeTags[((int) $row->karyawan_id).'|'.$workDate]['tag_key'] ?? null;
        if (str_starts_with((string) $tagKey, 'overtime_')) {
            return response()->json(['message' => 'Ada data SPL pada tanggal ini. Jam tidak bisa ditolak.'], 422);
        }

        if (! $row->checkin_at && ! $row->checkout_at) {
            return response()->json(['message' => 'Tidak ada jam untuk ditolak.'], 422);
        }

        $before = $this->snapshotReview($row);
        $row->checkin_at = null;
        $row->checkout_at = null;
        $row->suggested_checkin_at = null;
        $row->suggested_checkout_at = null;
        $row->status = 'no_log';
        $row->is_approved = false;
        $row->approved_by = null;
        $row->approved_at = null;
        $row->reason = trim(($row->reason ? $row->reason.' ' : '').'Jam ditolak karena hari libur tanpa SPL.');
        $row->save();

        $this->saveHistory(
            $row,
            'rejected_hours_holiday',
            $before,
            $this->snapshotReview($row),
            'Tolak jam libur tanpa SPL dari halaman Attendance Review.'
        );

        return response()->json(['message' => 'Jam berhasil ditolak untuk hari libur tanpa SPL.']);
    }

    // =========================================================================
    // restoreHolidayHours() - Restore jam hari libur yang di-reject
    // Dipanggil dari: POST /attendance-review/reviews/{id}/restore-hours
    // Output: View (halaman Blade template)
    // =========================================================================
    public function restoreHolidayHours(string $id): JsonResponse
    {
        $row = AttendanceDailyReviewModel::query()->findOrFail($id);
        if ($guard = $this->guardProfilBulanOpenForAttendance(ProfilBulanModel::query()->find((int) $row->profil_bulan_id))) {
            return $guard;
        }
        $history = AttendanceDailyReviewHistoryModel::query()
            ->where('attendance_daily_review_id', (int) $row->id)
            ->where('action', 'rejected_hours_holiday')
            ->orderByDesc('id')
            ->first();

        if (! $history || ! is_array($history->before_data) || empty($history->before_data)) {
            return response()->json(['message' => 'Data restore tidak ditemukan.'], 422);
        }

        $before = $this->snapshotReview($row);
        $prev = $history->before_data;

        $row->checkin_at = $prev['checkin_at'] ?? null;
        $row->checkout_at = $prev['checkout_at'] ?? null;
        $row->suggested_checkin_at = $prev['suggested_checkin_at'] ?? null;
        $row->suggested_checkout_at = $prev['suggested_checkout_at'] ?? null;
        $row->status = $prev['status'] ?? $row->status;
        $row->confidence_score = $prev['confidence_score'] ?? $row->confidence_score;
        $row->reason = $prev['reason'] ?? $row->reason;
        $row->is_approved = (bool) ($prev['is_approved'] ?? false);
        $row->approved_by = $prev['approved_by'] ?? null;
        $row->approved_at = $prev['approved_at'] ?? null;
        $row->save();

        $this->saveHistory(
            $row,
            'restored_hours_holiday',
            $before,
            $this->snapshotReview($row),
            'Restore jam setelah sebelumnya ditolak pada hari libur.'
        );

        return response()->json(['message' => 'Jam berhasil direstore.']);
    }

    public function deleteReview(string $id): JsonResponse
    {
        $row = AttendanceDailyReviewModel::query()->findOrFail($id);
        if ($guard = $this->guardProfilBulanOpenForAttendance(ProfilBulanModel::query()->find((int) $row->profil_bulan_id))) {
            return $guard;
        }

        $before = $this->snapshotReview($row);

        AttendanceDailyReviewHistoryModel::query()
            ->where('attendance_daily_review_id', (int) $row->id)
            ->delete();

        $row->delete();

        return response()->json(['message' => 'Review berhasil dihapus.']);
    }

    public function cancelForgettingClock(string $id): JsonResponse
    {
        if (! class_exists(ForgettingClockRequestModel::class)) {
            return response()->json(['message' => 'Model Forgetting Clock tidak ditemukan.'], 422);
        }

        $row = ForgettingClockRequestModel::query()->with('approvalRequest')->findOrFail((int) $id);

        if (in_array((string) ($row->status ?? ''), ['cancelled', 'rejected'], true)) {
            return response()->json(['message' => 'FC sudah dibatalkan/ditolak.'], 422);
        }

        try {
            $this->cancelMobileSelfServiceDocument($row, $row->approvalRequest);
        } catch (\RuntimeException $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }

        return response()->json(['message' => 'Forgetting Clock berhasil dibatalkan.', 'id' => (int) $row->id]);
    }

    // =========================================================================
    // reviewHistories() - Riwayat perubahan review
    // Dipanggil dari: GET /attendance-review/reviews/{id}/histories
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function reviewHistories(string $id): JsonResponse
    {
        $review = AttendanceDailyReviewModel::query()
            ->with('karyawan:id,employee_code,full_name')
            ->findOrFail($id);

        $rows = AttendanceDailyReviewHistoryModel::query()
            ->with('changedBy:id,name')
            ->where('attendance_daily_review_id', (int) $review->id)
            ->orderByDesc('changed_at')
            ->orderByDesc('id')
            ->get()
            ->map(fn (AttendanceDailyReviewHistoryModel $row) => [
                'id' => (int) $row->id,
                'action' => $row->action,
                'changed_at' => optional($row->changed_at)->format('Y-m-d H:i:s'),
                'changed_by' => $row->changedBy?->name ?: 'System',
                'notes' => $row->notes,
                'before_data' => $row->before_data,
                'after_data' => $row->after_data,
            ])
            ->values();

        $approvedByIds = $rows
            ->flatMap(function ($row) {
                $ids = [];
                $before = (array) ($row['before_data'] ?? []);
                $after = (array) ($row['after_data'] ?? []);
                if (! empty($before['approved_by'])) {
                    $ids[] = (int) $before['approved_by'];
                }
                if (! empty($after['approved_by'])) {
                    $ids[] = (int) $after['approved_by'];
                }

                return $ids;
            })
            ->filter(fn ($v) => $v > 0)
            ->unique()
            ->values();

        $shiftIds = $rows
            ->flatMap(function ($row) {
                $ids = [];
                $before = (array) ($row['before_data'] ?? []);
                $after = (array) ($row['after_data'] ?? []);
                if (! empty($before['planned_profil_jam_kerja_id'])) {
                    $ids[] = (int) $before['planned_profil_jam_kerja_id'];
                }
                if (! empty($after['planned_profil_jam_kerja_id'])) {
                    $ids[] = (int) $after['planned_profil_jam_kerja_id'];
                }

                return $ids;
            })
            ->filter(fn ($v) => $v > 0)
            ->unique()
            ->values();

        $approvedByMap = [];
        if ($approvedByIds->isNotEmpty()) {
            $approvedByMap = UserModels::query()
                ->whereIn('id', $approvedByIds)
                ->pluck('name', 'id')
                ->map(fn ($name) => (string) $name)
                ->all();
        }

        $shiftMap = [];
        if ($shiftIds->isNotEmpty()) {
            $shiftMap = ProfilJamKerjaModel::query()
                ->whereIn('id', $shiftIds)
                ->get(['id', 'code', 'name', 'start_time', 'end_time'])
                ->mapWithKeys(function (ProfilJamKerjaModel $shift) {
                    $label = trim((string) ($shift->code ?: '')).' - '.trim((string) ($shift->name ?: ''));
                    $time = trim(substr((string) ($shift->start_time ?: ''), 0, 5)).'-'.trim(substr((string) ($shift->end_time ?: ''), 0, 5));

                    return [(int) $shift->id => trim($label.' '.$time)];
                })
                ->all();
        }

        $profilLabel = '';
        if (! empty($review->profil_bulan_id)) {
            $profilRow = ProfilBulanModel::query()->find((int) $review->profil_bulan_id, ['id', 'code', 'name']);
            if ($profilRow) {
                $profilLabel = trim((string) ($profilRow->code ?: '').' - '.(string) ($profilRow->name ?: ''));
            }
        }

        return response()->json([
            'data' => $rows,
            'meta' => [
                'review_id' => (int) $review->id,
                'employee_code' => $review->karyawan?->employee_code,
                'employee_name' => $review->karyawan?->full_name,
                'work_date' => optional($review->work_date)->format('Y-m-d'),
                'lookups' => [
                    'approved_by' => $approvedByMap,
                    'shift' => $shiftMap,
                    'profil_bulan' => [
                        (int) ($review->profil_bulan_id ?? 0) => $profilLabel,
                    ],
                    'karyawan' => [
                        (int) ($review->karyawan_id ?? 0) => trim(($review->karyawan?->employee_code ?? '').' - '.($review->karyawan?->full_name ?? '')),
                    ],
                ],
            ],
        ]);
    }

    // =========================================================================
    // reviewLogOptions() - Opsi log untuk review tertentu
    // Dipanggil dari: GET /attendance-review/reviews/{id}/log-options
    // Output: JSON response (untuk AJAX/API)
    // =========================================================================
    public function scanEmergencyCases(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'profil_bulan_id' => ['required', 'integer', 'exists:master_profil_bulans,id'],
            'work_date' => ['required', 'date'],
        ]);
        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first()], 422);
        }

        $profilId = (int) $request->input('profil_bulan_id');
        $workDate = Carbon::parse((string) $request->input('work_date'))->startOfDay();
        $nextDate = $workDate->copy()->addDay();
        $employeeIds = ProfilBulanKaryawanModel::query()
            ->where('profil_bulan_id', $profilId)
            ->pluck('karyawan_id')
            ->filter()
            ->map(fn ($id) => (int) $id)
            ->unique()
            ->values();

        $employees = KaryawanModel::query()
            ->whereIn('id', $employeeIds)
            ->get(['id', 'employee_code', 'full_name'])
            ->keyBy('id');
        $reviews = AttendanceDailyReviewModel::query()
            ->where('profil_bulan_id', $profilId)
            ->whereIn('karyawan_id', $employeeIds)
            ->whereDate('work_date', '>=', $workDate->format('Y-m-d'))
            ->whereDate('work_date', '<=', $nextDate->format('Y-m-d'))
            ->get()
            ->groupBy('karyawan_id');
        $logs = AttendanceLogModel::query()
            ->whereIn('karyawan_id', $employeeIds)
            ->whereBetween('log_at', [$workDate->copy()->setTime(12, 0)->format('Y-m-d H:i:s'), $nextDate->copy()->setTime(12, 0)->format('Y-m-d H:i:s')])
            ->orderBy('log_at')
            ->get(['karyawan_id', 'log_at', 'log_type', 'source', 'device_code'])
            ->groupBy('karyawan_id');
        $leaveMap = LeaveRequestModel::query()
            ->where('status', 'approved')
            ->whereIn('karyawan_id', $employeeIds)
            ->whereDate('start_date', '<=', $nextDate->format('Y-m-d'))
            ->whereDate('end_date', '>=', $workDate->format('Y-m-d'))
            ->get(['id', 'karyawan_id', 'leave_type', 'start_date', 'end_date'])
            ->groupBy('karyawan_id');

        $isInLog = static fn ($row): bool => in_array(strtolower(trim((string) ($row->log_type ?? ''))), ['in', 'check_in', 'checkin', '0'], true);
        $isOutLog = static fn ($row): bool => in_array(strtolower(trim((string) ($row->log_type ?? ''))), ['out', 'check_out', 'checkout', '1'], true);
        $items = [];
        foreach ($employeeIds as $employeeId) {
            $empLogs = ($logs->get($employeeId) ?: collect())->values();
            $nightIn = $empLogs->first(fn ($row) => $isInLog($row) && Carbon::parse((string) $row->log_at)->toDateString() === $workDate->format('Y-m-d') && Carbon::parse((string) $row->log_at)->hour >= 16);
            $nextOut = $empLogs->first(fn ($row) => $isOutLog($row) && Carbon::parse((string) $row->log_at)->toDateString() === $nextDate->format('Y-m-d') && Carbon::parse((string) $row->log_at)->hour <= 12);
            if (! $nightIn && ! $nextOut) {
                continue;
            }
            $empReviews = $reviews->get($employeeId) ?: collect();
            $reviewX = $empReviews->first(fn ($row) => Carbon::parse((string) $row->work_date)->toDateString() === $workDate->format('Y-m-d'));
            $reviewNext = $empReviews->first(fn ($row) => Carbon::parse((string) $row->work_date)->toDateString() === $nextDate->format('Y-m-d'));
            $leaves = $leaveMap->get($employeeId) ?: collect();
            $conflicts = [];
            if ($leaves->isNotEmpty()) $conflicts[] = 'Leave Approved';
            if ($reviewNext && (string) $reviewNext->status !== 'no_log') $conflicts[] = 'Review X+1 aktif';
            if ($reviewX && !($reviewX->planned_shift_start && $reviewX->planned_shift_end)) $conflicts[] = 'Shift belum lengkap';
            $confidence = 0;
            if ($nightIn) $confidence += 40;
            if ($nextOut) $confidence += 40;
            if ($leaves->isNotEmpty()) $confidence += 10;
            if ($reviewX && $reviewX->planned_shift_start && $reviewX->planned_shift_end && Carbon::parse((string) $reviewX->planned_shift_end)->lt(Carbon::parse((string) $reviewX->planned_shift_start))) $confidence += 10;
            $employee = $employees->get($employeeId);
            $items[] = [
                'karyawan_id' => $employeeId,
                'employee_code' => $employee?->employee_code,
                'employee_name' => $employee?->full_name,
                'work_date' => $workDate->format('Y-m-d'),
                'next_date' => $nextDate->format('Y-m-d'),
                'raw_in' => $nightIn ? Carbon::parse((string) $nightIn->log_at)->format('Y-m-d H:i:s') : null,
                'raw_out' => $nextOut ? Carbon::parse((string) $nextOut->log_at)->format('Y-m-d H:i:s') : null,
                'source' => trim(collect([$nightIn?->source, $nextOut?->source])->filter()->unique()->join(' / ')),
                'device' => trim(collect([$nightIn?->device_code, $nextOut?->device_code])->filter()->unique()->join(' / ')),
                'review_id' => $reviewX?->id ? (int) $reviewX->id : null,
                'next_review_id' => $reviewNext?->id ? (int) $reviewNext->id : null,
                'status' => $reviewX?->status,
                'next_status' => $reviewNext?->status,
                'conflict' => $conflicts ? implode(', ', array_unique($conflicts)) : 'Perlu cek pairing',
                'suggestion' => $nightIn && $nextOut ? 'Emergency Shift Malam' : 'Possible Forget Clock / Unpaired',
                'confidence' => min(100, $confidence),
            ];
        }

        return response()->json(['data' => $items]);
    }

    public function cancelEmergencyLeave(Request $request, string $id): JsonResponse
    {
        $review = AttendanceDailyReviewModel::query()->findOrFail((int) $id);
        $reason = trim((string) $request->input('reason', 'Emergency masuk; leave dibatalkan dari Attendance Review.'));
        if ($reason === '') {
            return response()->json(['message' => 'Alasan wajib diisi.'], 422);
        }

        $leave = LeaveRequestModel::query()
            ->where('karyawan_id', (int) $review->karyawan_id)
            ->where('status', 'approved')
            ->whereDate('start_date', '<=', $review->work_date)
            ->whereDate('end_date', '>=', $review->work_date)
            ->first();
        if (! $leave) {
            return response()->json(['message' => 'Leave approved pada tanggal ini tidak ditemukan.'], 404);
        }

        DB::transaction(function () use ($leave, $review, $reason): void {
            if ($leave->approval_request_id) {
                DB::table('approval_request_steps')->where('approval_request_id', (int) $leave->approval_request_id)->delete();
                DB::table('approval_requests')->where('id', (int) $leave->approval_request_id)->delete();
            }
            $leave->approval_request_id = null;
            $leave->status = 'draft';
            $leave->reason = trim((string) ($leave->reason ?? ''))."
EMERGENCY_CANCEL::".$reason;
            $leave->save();

            AttendanceDailyReviewModel::query()
                ->where('karyawan_id', (int) $review->karyawan_id)
                ->whereDate('work_date', $review->work_date)
                ->where('reason', 'like', '%Leave%')
                ->update(['is_approved' => false, 'approved_by' => null, 'approved_at' => null]);
        });

        return response()->json(['message' => 'Leave emergency dibatalkan. Jalankan Run Deteksi untuk memproses shift.']);
    }

    public function reviewLogOptions(Request $request, string $id): JsonResponse
    {
        $review = AttendanceDailyReviewModel::query()
            ->with('karyawan:id,employee_code,full_name')
            ->findOrFail($id);

        if (empty($review->karyawan_id) || empty($review->work_date)) {
            return response()->json(['message' => 'Review tidak valid.'], 422);
        }

        $workDate = Carbon::parse((string) $review->work_date)->startOfDay();
        $includeNextDay = $request->boolean('include_next_day', false);
        $allowUsedNextDay = $request->boolean('allow_used_next_day', false);
        $plannedStart = $review->planned_shift_start ? Carbon::parse((string) $review->planned_shift_start) : $workDate->copy()->startOfDay();
        $plannedEnd = $review->planned_shift_end ? Carbon::parse((string) $review->planned_shift_end) : $workDate->copy()->endOfDay();
        $from = $workDate->copy()->subDay()->startOfDay();
        $to = $workDate->copy()->addDay()->endOfDay();

        $employeeCode = trim((string) ($review->karyawan?->employee_code ?? ''));
        $fingerId = trim((string) ($review->karyawan?->finger_id ?? ''));
        $logs = AttendanceLogModel::query()
            ->where(function ($query) use ($review, $employeeCode, $fingerId) {
                $query->where('karyawan_id', (int) $review->karyawan_id);
                if ($employeeCode !== '') {
                    $query->orWhere('employee_code', $employeeCode);
                }
                if ($fingerId !== '') {
                    $query->orWhere('finger_id', $fingerId);
                }
            })
            ->whereBetween('log_at', [$from->format('Y-m-d H:i:s'), $to->format('Y-m-d H:i:s')])
            ->orderBy('log_at')
            ->get(['id', 'karyawan_id', 'employee_code', 'finger_id', 'log_at', 'source', 'device_code', 'log_type']);

        $isInLog = static function ($row): bool {
            $type = strtolower(trim((string) ($row->log_type ?? '')));

            return in_array($type, ['in', 'check_in', 'checkin', '0'], true);
        };
        $isOutLog = static function ($row): bool {
            $type = strtolower(trim((string) ($row->log_type ?? '')));

            return in_array($type, ['out', 'check_out', 'checkout', '1'], true);
        };
        $toOption = static function ($row): array {
            $dt = Carbon::parse((string) $row->log_at);

            return [
                'id' => (int) $row->id,
                'date' => $dt->format('Y-m-d'),
                'time' => $dt->format('H:i'),
                'datetime' => $dt->format('Y-m-d H:i'),
                'source' => (string) ($row->source ?? ''),
                'device_code' => (string) ($row->device_code ?? ''),
                'log_type' => (string) ($row->log_type ?? ''),
            ];
        };

        $inWindowStart = $workDate->copy()->subDay()->startOfDay();
        $inWindowEnd = $workDate->copy()->endOfDay();
        $outWindowStart = $workDate->copy()->startOfDay();
        $outWindowEnd = $workDate->copy()->addDay()->endOfDay();
        $usedOtherReviewTimes = AttendanceDailyReviewModel::query()
            ->where('profil_bulan_id', (int) $review->profil_bulan_id)
            ->where('karyawan_id', (int) $review->karyawan_id)
            ->where('id', '<>', (int) $review->id)
            ->whereDate('work_date', '>=', $workDate->copy()->addDay()->format('Y-m-d'))
            ->whereDate('work_date', '<=', $workDate->copy()->addDay()->format('Y-m-d'))
            ->get(['checkin_at', 'checkout_at', 'suggested_checkin_at', 'suggested_checkout_at'])
            ->flatMap(function ($row) {
                return [
                    $row->checkin_at,
                    $row->checkout_at,
                    $row->suggested_checkin_at,
                    $row->suggested_checkout_at,
                ];
            })
            ->filter()
            ->map(fn ($value) => Carbon::parse((string) $value)->format('Y-m-d H:i'))
            ->flip();

        $checkinLogs = $logs
            ->filter(function ($row) use ($isInLog, $inWindowStart, $inWindowEnd) {
                if (empty($row->log_at) || ! $isInLog($row)) {
                    return false;
                }

                $dt = Carbon::parse((string) $row->log_at);

                return $dt->between($inWindowStart, $inWindowEnd, true);
            })
            ->values();
        $checkoutLogs = $logs
            ->filter(function ($row) use ($isOutLog, $outWindowStart, $outWindowEnd, $plannedEnd, $workDate, $includeNextDay, $allowUsedNextDay, $usedOtherReviewTimes, $review) {
                if (empty($row->log_at)) {
                    return false;
                }

                $dt = Carbon::parse((string) $row->log_at);
                $dtKey = $dt->format('Y-m-d H:i');
                $currentOut = $review->checkout_at ? Carbon::parse((string) $review->checkout_at)->format('Y-m-d H:i') : '';
                $isCurrentOut = $currentOut !== '' && $dtKey === $currentOut;
                if (
                    ! $allowUsedNextDay
                    && ! $isCurrentOut
                    && $dt->toDateString() !== $workDate->toDateString()
                    && isset($usedOtherReviewTimes[$dtKey])
                ) {
                    return false;
                }

                return $dt->between($outWindowStart, $outWindowEnd, true)
                    && $isOutLog($row);
            })
            ->values();

        $checkinLogs = $logs
            ->filter(fn ($row) => ! empty($row->log_at) && Carbon::parse((string) $row->log_at)->between($inWindowStart, $inWindowEnd, true))
            ->values();
        $checkoutLogs = $logs
            ->filter(fn ($row) => ! empty($row->log_at) && Carbon::parse((string) $row->log_at)->between($outWindowStart, $outWindowEnd, true))
            ->values();

        $currentInKey = $review->checkin_at ? Carbon::parse((string) $review->checkin_at)->format('Y-m-d H:i') : null;
        $currentOutKey = $review->checkout_at ? Carbon::parse((string) $review->checkout_at)->format('Y-m-d H:i') : null;
        if ($currentInKey) {
            $currentInLog = $logs->first(fn ($row) => ! empty($row->log_at) && Carbon::parse((string) $row->log_at)->format('Y-m-d H:i') === $currentInKey);
            if ($currentInLog && ! $checkinLogs->contains('id', $currentInLog->id)) {
                $checkinLogs->prepend($currentInLog);
            }
        }
        if ($currentOutKey) {
            $currentOutLog = $logs->first(fn ($row) => ! empty($row->log_at) && Carbon::parse((string) $row->log_at)->format('Y-m-d H:i') === $currentOutKey);
            if ($currentOutLog && ! $checkoutLogs->contains('id', $currentOutLog->id)) {
                $checkoutLogs->push($currentOutLog);
            }
        }

        $checkinOptions = $checkinLogs->map($toOption)->values();
        $checkoutOptions = $checkoutLogs->map($toOption)->values();

        $options = $logs
            ->filter(fn ($row) => ! empty($row->log_at))
            ->map($toOption)
            ->values();

        return response()->json([
            'data' => $options,
            'checkin_options' => $checkinOptions,
            'checkout_options' => $checkoutOptions,
            'meta' => [
                'review_id' => (int) $review->id,
                'work_date' => $workDate->format('Y-m-d'),
                'employee_code' => $review->karyawan?->employee_code,
                'employee_name' => $review->karyawan?->full_name,
                'current_in' => optional($review->checkin_at)->format('H:i'),
                'current_out' => optional($review->checkout_at)->format('H:i'),
                'current_in_datetime' => optional($review->checkin_at)->format('Y-m-d H:i'),
                'current_out_datetime' => optional($review->checkout_at)->format('Y-m-d H:i'),
                'recommended_in_datetime' => $currentInKey ?: (optional($checkinLogs->first())->log_at ? Carbon::parse((string) $checkinLogs->first()->log_at)->format('Y-m-d H:i') : null),
                'recommended_out_datetime' => $currentOutKey ?: (optional($checkoutLogs->last())->log_at ? Carbon::parse((string) $checkoutLogs->last()->log_at)->format('Y-m-d H:i') : null),
                'checkout_requires_explicit_out_log' => true,
            ],
        ]);
    }

    // =========================================================================
    // applyRounding() - Menerapkan perubahan pada data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function applyRounding(Carbon $dateTime, PembulatanJamModel $rule, string $target = 'checkin'): Carbon
    {
        $interval = max(1, (int) ($rule->interval_minutes ?? 5));
        $method = (string) ($rule->round_method ?? 'nearest');
        if ((bool) ($rule->discipline_mode ?? false)) {
            $method = $target === 'checkout' ? 'floor' : 'ceil';
        }

        $minute = (int) $dateTime->minute;
        $hour = (int) $dateTime->hour;
        $total = ($hour * 60) + $minute;

        if ($method === 'floor') {
            $rounded = (int) (floor($total / $interval) * $interval);
        } elseif ($method === 'ceil') {
            $rounded = (int) (ceil($total / $interval) * $interval);
        } else {
            $rounded = (int) (round($total / $interval) * $interval);
        }

        $rounded = max(0, min(1439, $rounded));
        $newHour = (int) floor($rounded / 60);
        $newMinute = $rounded % 60;

        return $dateTime->copy()->setTime($newHour, $newMinute, 0);
    }

    // =========================================================================
    // snapshotReview() - Membuat snapshot data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function snapshotReview(AttendanceDailyReviewModel $review): array
    {
        return collect(self::REVIEW_TRACKED_FIELDS)
            ->mapWithKeys(fn (string $field) => [$field => $review->getAttribute($field)])
            ->toArray();
    }

    // =========================================================================
    // saveHistory() - Menyimpan data ke database
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function saveHistory(
        AttendanceDailyReviewModel $review,
        string $action,
        ?array $beforeData,
        ?array $afterData,
        ?string $notes = null
    ): void {
        AttendanceDailyReviewHistoryModel::query()->create([
            'attendance_daily_review_id' => (int) $review->id,
            'action' => $action,
            'before_data' => $beforeData,
            'after_data' => $afterData,
            'notes' => $notes,
            'changed_by' => auth()->id(),
            'changed_at' => now()->format('Y-m-d H:i:s'),
        ]);
    }

    // =========================================================================
    // rewriteOfflineMarker() - Menulis ulang data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function rewriteOfflineMarker(string $notes, string $status): string
    {
        $clean = preg_replace('/\\[OFFLINE_PENDING_APPROVAL\\]/i', '', $notes) ?? $notes;
        $clean = preg_replace('/\\s+\\|\\s+$/', '', trim($clean)) ?? trim($clean);
        $stamp = '['.strtoupper($status).' by '.(auth()->user()->name ?? 'System').' at '.now()->format('Y-m-d H:i:s').']';
        if ($clean === '') {
            return $stamp;
        }

        return $clean.' | '.$stamp;
    }

    // =========================================================================
    // buildBulkApprovalSafetyContext() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildBulkApprovalSafetyContext(Collection $rows, string $workDate, int $profilId): array
    {
        $employeeIds = $rows->pluck('karyawan_id')
            ->map(fn ($id) => (int) $id)
            ->filter(fn ($id) => $id > 0)
            ->unique()
            ->values();

        $date = Carbon::parse($workDate);
        $rawLogsByEmployee = collect();
        if ($employeeIds->isNotEmpty()) {
            try {
                $rawLogsByEmployee = AttendanceLogModel::query()
                    ->whereIn('karyawan_id', $employeeIds->all())
                    ->whereBetween('log_at', [
                        $date->copy()->subDay()->startOfDay(),
                        $date->copy()->addDay()->endOfDay(),
                    ])
                    ->orderBy('log_at')
                    ->get(['karyawan_id', 'log_at', 'log_type'])
                    ->map(function (AttendanceLogModel $row) {
                        if (! ($row->log_at instanceof Carbon) && ! empty($row->log_at)) {
                            $row->log_at = Carbon::parse((string) $row->log_at);
                        }

                        return $row;
                    })
                    ->filter(fn (AttendanceLogModel $row) => $row->log_at instanceof Carbon)
                    ->groupBy(fn (AttendanceLogModel $row) => (int) $row->karyawan_id);
            } catch (\Throwable $e) {
                $rawLogsByEmployee = collect();
            }
        }

        $assignments = $employeeIds->isNotEmpty()
            ? ProfilBulanKaryawanModel::query()
                ->where('profil_bulan_id', $profilId)
                ->whereIn('karyawan_id', $employeeIds->all())
                ->get()
                ->keyBy(fn (ProfilBulanKaryawanModel $row) => (int) $row->karyawan_id)
            : collect();

        return [
            'raw_logs_by_employee' => $rawLogsByEmployee,
            'overtime_tags' => $this->buildOvertimeTagMap($employeeIds, $date->copy(), $date->copy()),
            'overtime_approved' => $this->buildOvertimeApprovedMap($employeeIds, $date->copy(), $date->copy()),
            'assignments' => $assignments,
        ];
    }

    // =========================================================================
    // isSafeForBulkCheckApproval() - Cek kondisi tertentu, return bool
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function isSafeForBulkCheckApproval(AttendanceDailyReviewModel $row, array $context): bool
    {
        $status = strtolower(trim((string) ($row->status ?? '')));
        if (in_array($status, ['missing_in', 'missing_out', 'unpaired', 'shift_transition'], true)) {
            return false;
        }

        $reason = strtolower(trim((string) ($row->reason ?? '')));
        foreach ([
            'butuh spl',
            'spl belum approved',
            'butuh extend spl',
            'extend spl',
            'tidak match shift',
            'perlu review',
            'kontrak selesai',
            'kontrak belum mulai',
            'offline pending',
        ] as $marker) {
            if ($reason !== '' && str_contains($reason, $marker)) {
                return false;
            }
        }

        if ($this->reviewHasUnsafeOvertimeForBulkCheck($row, $context)) {
            return false;
        }

        return true;
    }

    // =========================================================================
    // reviewHasUnsafeOvertimeForBulkCheck() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function reviewHasUnsafeOvertimeForBulkCheck(AttendanceDailyReviewModel $row, array $context): bool
    {
        try {
            if (empty($row->planned_shift_end)) {
                return false;
            }

            $karyawanId = (int) $row->karyawan_id;
            $dateKey = $row->work_date instanceof Carbon
                ? $row->work_date->copy()->format('Y-m-d')
                : Carbon::parse((string) $row->work_date)->format('Y-m-d');
            $splKey = $karyawanId.'|'.$dateKey;
            $assignments = $context['assignments'] ?? collect();
            $assignment = $assignments instanceof Collection ? $assignments->get($karyawanId) : null;
            if ($this->assignmentAllowsAutomaticOvertimeWithoutSpl($assignment)) {
                return false;
            }

            $plannedEnd = Carbon::parse((string) $row->planned_shift_end);
            $rawWindow = $this->resolveRawLogWindowForBulkCheck(
                $row,
                $context['raw_logs_by_employee'] ?? collect()
            );
            $rawOutAt = ! empty($rawWindow['max_at'])
                ? Carbon::parse((string) $rawWindow['max_at'])
                : null;
            if (! $rawOutAt || ! $rawOutAt->gt($plannedEnd)) {
                return false;
            }

            $overtimeTags = $context['overtime_tags'] ?? [];
            if (empty($overtimeTags[$splKey])) {
                $threshold = (int) env('ATTENDANCE_MISSING_SPL_THRESHOLD_MINUTES', 30);

                return $plannedEnd->diffInMinutes($rawOutAt) >= max(1, $threshold);
            }

            $overtimeApproved = $context['overtime_approved'] ?? [];
            $approvedWindow = $this->resolveApprovedOvertimeWindowForShift(
                $overtimeApproved[$splKey] ?? [],
                ! empty($row->planned_shift_start) ? Carbon::parse((string) $row->planned_shift_start) : null,
                $plannedEnd
            );
            if (($approvedWindow['post_end'] ?? null) instanceof Carbon && $rawOutAt->gt($approvedWindow['post_end'])) {
                $threshold = (int) env('ATTENDANCE_EXTEND_SPL_THRESHOLD_MINUTES', 1);

                return $approvedWindow['post_end']->diffInMinutes($rawOutAt) >= max(1, $threshold);
            }

            return false;
        } catch (\Throwable $e) {
            return true;
        }
    }

    // =========================================================================
    // resolveRawLogWindowForBulkCheck() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveRawLogWindowForBulkCheck(AttendanceDailyReviewModel $review, $rawLogsByEmployee): array
    {
        $fallback = [
            'min_at' => $review->suggested_checkin_at ?: $review->checkin_at,
            'max_at' => $review->suggested_checkout_at ?: $review->checkout_at,
        ];

        if (
            empty($review->planned_shift_start)
            || empty($review->planned_shift_end)
            || ! ($rawLogsByEmployee instanceof Collection)
            || $rawLogsByEmployee->isEmpty()
        ) {
            return $fallback;
        }

        try {
            $plannedStart = Carbon::parse((string) $review->planned_shift_start);
            $plannedEnd = Carbon::parse((string) $review->planned_shift_end);
            $windowStart = $plannedStart->copy()->subHours(6);
            $windowEnd = $plannedEnd->copy()->addHours(8)->endOfMinute();
            $inWindowEnd = $plannedStart->copy()->addHours(6);
            if ($inWindowEnd->gt($plannedEnd)) {
                $inWindowEnd = $plannedEnd->copy();
            }
            $outWindowStart = $plannedEnd->copy()->subHours(6);

            $logs = ($rawLogsByEmployee->get((int) $review->karyawan_id) ?: collect())
                ->filter(function (AttendanceLogModel $row) use ($windowStart, $windowEnd) {
                    return $row->log_at instanceof Carbon
                        && $row->log_at->between($windowStart, $windowEnd, true);
                })
                ->sortBy('log_at')
                ->values();
            if ($logs->isEmpty()) {
                return $fallback;
            }

            $isInLog = static function (AttendanceLogModel $row): bool {
                $type = strtolower(trim((string) ($row->log_type ?? '')));

                return in_array($type, ['in', 'check_in', 'checkin', '0'], true);
            };
            $isOutLog = static function (AttendanceLogModel $row): bool {
                $type = strtolower(trim((string) ($row->log_type ?? '')));

                return in_array($type, ['out', 'check_out', 'checkout', '1'], true);
            };

            $inLogs = $logs
                ->filter(fn (AttendanceLogModel $row) => $isInLog($row) && $row->log_at->between($windowStart, $inWindowEnd, true))
                ->values();
            $outLogs = $logs
                ->filter(fn (AttendanceLogModel $row) => $isOutLog($row) && $row->log_at->between($outWindowStart, $windowEnd, true))
                ->values();

            return [
                'min_at' => ($inLogs->first() ?: $logs->first())->log_at->format('Y-m-d H:i:s'),
                'max_at' => ($outLogs->last() ?: $logs->last())->log_at->format('Y-m-d H:i:s'),
            ];
        } catch (\Throwable $e) {
            return $fallback;
        }
    }

    // =========================================================================
    // applyApproveToReview() - Menerapkan perubahan pada data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function applyApproveToReview(AttendanceDailyReviewModel $row, string $notes): bool
    {
        $before = $this->snapshotReview($row);

        if (! $row->checkin_at && $row->suggested_checkin_at) {
            $row->checkin_at = $row->suggested_checkin_at;
        }
        if (! $row->checkout_at && $row->suggested_checkout_at) {
            $row->checkout_at = $row->suggested_checkout_at;
        }
        $row->is_approved = true;
        $row->approved_by = auth()->id();
        $row->approved_at = now();
        $row->save();

        if (! $row->wasChanged()) {
            return false;
        }

        $this->saveHistory(
            $row,
            'approved',
            $before,
            $this->snapshotReview($row),
            $notes
        );

        return true;
    }

    // =========================================================================
    // isDetectionCoreUnchanged() - Cek kondisi tertentu, return bool
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function isDetectionCoreUnchanged(AttendanceDailyReviewModel $review, array $payload): bool
    {
        $toDateTime = static function ($value): ?string {
            if ($value === null || $value === '') {
                return null;
            }

            return Carbon::parse((string) $value)->format('Y-m-d H:i:s');
        };

        $oldStatus = (string) ($review->status ?? '');
        $newStatus = (string) ($payload['status'] ?? '');
        if ($oldStatus !== $newStatus) {
            return false;
        }

        // Bandingkan "effective in/out":
        // untuk missing_in / missing_out, nilai suggested yang di-approve dianggap ekuivalen
        // dengan nilai actual yang diisikan saat approve.
        $oldCheckin = $toDateTime($review->checkin_at);
        $oldCheckout = $toDateTime($review->checkout_at);
        $oldSuggestedIn = $toDateTime($review->suggested_checkin_at);
        $oldSuggestedOut = $toDateTime($review->suggested_checkout_at);
        $newCheckin = $toDateTime($payload['checkin_at'] ?? null);
        $newCheckout = $toDateTime($payload['checkout_at'] ?? null);
        $newSuggestedIn = $toDateTime($payload['suggested_checkin_at'] ?? null);
        $newSuggestedOut = $toDateTime($payload['suggested_checkout_at'] ?? null);

        $oldEffectiveIn = $oldCheckin ?: (($oldStatus === 'missing_in') ? $oldSuggestedIn : null);
        $oldEffectiveOut = $oldCheckout ?: (($oldStatus === 'missing_out') ? $oldSuggestedOut : null);
        $newEffectiveIn = $newCheckin ?: (($newStatus === 'missing_in') ? $newSuggestedIn : null);
        $newEffectiveOut = $newCheckout ?: (($newStatus === 'missing_out') ? $newSuggestedOut : null);

        if ((string) ($oldEffectiveIn ?? '') !== (string) ($newEffectiveIn ?? '')) {
            return false;
        }
        if ((string) ($oldEffectiveOut ?? '') !== (string) ($newEffectiveOut ?? '')) {
            return false;
        }

        $compareKeys = [
            'planned_profil_jam_kerja_id',
            'planned_shift_start',
            'planned_shift_end',
            'is_cross_day',
            'suggested_checkin_at',
            'suggested_checkout_at',
        ];

        foreach ($compareKeys as $key) {
            $oldVal = $review->getAttribute($key);
            $newVal = $payload[$key] ?? null;

            if (in_array($key, ['planned_shift_start', 'planned_shift_end', 'checkin_at', 'checkout_at', 'suggested_checkin_at', 'suggested_checkout_at'], true)) {
                $oldVal = $oldVal ? Carbon::parse((string) $oldVal)->format('Y-m-d H:i:s') : null;
                $newVal = $newVal ? Carbon::parse((string) $newVal)->format('Y-m-d H:i:s') : null;
            }

            if ($key === 'is_cross_day') {
                $oldVal = (bool) $oldVal;
                $newVal = (bool) $newVal;
            }

            if ((string) ($oldVal ?? '') !== (string) ($newVal ?? '')) {
                return false;
            }
        }

        return true;
    }

    // =========================================================================
    // isReviewPlanningUnchanged() - Cek kondisi tertentu, return bool
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function isReviewPlanningUnchanged(AttendanceDailyReviewModel $review, array $payload): bool
    {
        $compareKeys = [
            'planned_profil_jam_kerja_id',
            'planned_shift_start',
            'planned_shift_end',
            'is_cross_day',
        ];

        foreach ($compareKeys as $key) {
            $oldVal = $review->getAttribute($key);
            $newVal = $payload[$key] ?? null;

            if (in_array($key, ['planned_shift_start', 'planned_shift_end'], true)) {
                $oldVal = $oldVal ? Carbon::parse((string) $oldVal)->format('Y-m-d H:i:s') : null;
                $newVal = $newVal ? Carbon::parse((string) $newVal)->format('Y-m-d H:i:s') : null;
            }

            if ($key === 'is_cross_day') {
                $oldVal = (bool) $oldVal;
                $newVal = (bool) $newVal;
            }

            if ((string) ($oldVal ?? '') !== (string) ($newVal ?? '')) {
                return false;
            }
        }

        return true;
    }

    // =========================================================================
    // buildCalendarMarks() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildCalendarMarks(Carbon $startDate, Carbon $endDate): array
    {
        $holidayMap = [];
        $workdayMap = [];
        $holidaySpecialMap = [];
        $period = collect(CarbonPeriod::create($startDate, $endDate))
            ->map(fn (Carbon $d) => $d->copy())
            ->values();

        foreach ($period as $date) {
            if (in_array((int) $date->dayOfWeekIso, [6, 7], true)) {
                $holidayMap[$date->format('Y-m-d')] = 'Weekend';
            }
        }

        if (! class_exists(KalenderModel::class)) {
            return [
                'holiday_map' => $holidayMap,
                'workday_map' => $workdayMap,
            ];
        }

        $events = KalenderModel::query()
            ->where('is_active', true)
            ->whereDate('start_date', '<=', $endDate->format('Y-m-d'))
            ->whereDate('end_date', '>=', $startDate->format('Y-m-d'))
            ->orderBy('start_date')
            ->get(array_filter([
                'name',
                'event_type',
                Schema::hasColumn('master_kalenders', 'is_holiday_special') ? 'is_holiday_special' : null,
                'start_date',
                'end_date',
            ]));

        foreach ($events as $event) {
            $from = Carbon::parse($event->start_date)->startOfDay();
            $to = Carbon::parse($event->end_date ?: $event->start_date)->startOfDay();
            if ($to->lt($from)) {
                $to = $from->copy();
            }

            $from = $from->lt($startDate) ? $startDate->copy() : $from;
            $to = $to->gt($endDate) ? $endDate->copy() : $to;

            foreach (CarbonPeriod::create($from, $to) as $date) {
                $dateKey = $date->format('Y-m-d');
                if ($event->event_type === 'workday') {
                    unset($holidayMap[$dateKey]);
                    unset($holidaySpecialMap[$dateKey]);
                    $workdayMap[$dateKey] = $event->name ?: 'Workday';

                    continue;
                }
                unset($workdayMap[$dateKey]);
                $holidayMap[$dateKey] = $event->name ?: 'Holiday';
                if ((bool) ($event->is_holiday_special ?? false)) {
                    $holidaySpecialMap[$dateKey] = $event->name ?: 'Holiday Special';
                } else {
                    unset($holidaySpecialMap[$dateKey]);
                }
            }
        }

        ksort($holidayMap);
        ksort($workdayMap);
        ksort($holidaySpecialMap);

        return [
            'holiday_map' => $holidayMap,
            'workday_map' => $workdayMap,
            'holiday_special_map' => $holidaySpecialMap,
        ];
    }

    // =========================================================================
    // buildLeaveApprovedMap() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildLeaveApprovedMap($employeeIds, Carbon $startDate, Carbon $endDate): array
    {
        $map = [];
        if ($employeeIds->isEmpty() || ! class_exists(LeaveRequestModel::class)) {
            return $map;
        }

        $rows = LeaveRequestModel::query()
            ->where('status', 'approved')
            ->whereIn('karyawan_id', $employeeIds)
            ->whereDate('start_date', '<=', $endDate->format('Y-m-d'))
            ->whereDate('end_date', '>=', $startDate->format('Y-m-d'))
            ->get(['id', 'request_no', 'karyawan_id', 'start_date', 'end_date', 'leave_type', 'is_payable']);

        foreach ($rows as $row) {
            $from = Carbon::parse($row->start_date)->startOfDay();
            $to = Carbon::parse($row->end_date)->startOfDay();
            if ($to->lt($from)) {
                $to = $from->copy();
            }
            if ($from->lt($startDate)) {
                $from = $startDate->copy();
            }
            if ($to->gt($endDate)) {
                $to = $endDate->copy();
            }

            foreach (CarbonPeriod::create($from, $to) as $date) {
                $key = ((int) $row->karyawan_id).'|'.$date->format('Y-m-d');
                $map[$key] = [
                    'request_no' => $row->request_no,
                    'leave_type' => $row->leave_type,
                    'is_payable' => (bool) ($row->is_payable ?? false),
                    'label' => 'Leave Approved',
                    'notes' => trim(($row->request_no ?: '-').' / '.strtoupper((string) $row->leave_type)),
                ];
            }
        }

        return $map;
    }

    // =========================================================================
    // buildOvertimeApprovedMap() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildOvertimeApprovedMap($employeeIds, Carbon $startDate, Carbon $endDate): array
    {
        $map = [];
        if ($employeeIds->isEmpty() || ! class_exists(SuratPerintahLemburModel::class)) {
            return $map;
        }

        $rows = SuratPerintahLemburModel::query()
            ->where('status', 'approved')
            ->where('is_active', true)
            ->whereIn('karyawan_id', $employeeIds)
            ->whereDate('work_date', '>=', $startDate->format('Y-m-d'))
            ->whereDate('work_date', '<=', $endDate->format('Y-m-d'))
            ->with('job:id,code')
            ->get(['id', 'document_no', 'karyawan_id', 'job_id', 'work_date', 'start_time', 'end_time', 'overtime_type', 'overtime_segment', 'rule_payload']);

        foreach ($rows as $row) {
            $dateKey = optional($row->work_date)->format('Y-m-d');
            if (! $dateKey) {
                continue;
            }
            $key = ((int) $row->karyawan_id).'|'.$dateKey;
            $map[$key] ??= [];
            $jobCode = trim((string) ($row->job?->code ?? ''));
            $map[$key][] = [
                'document_no' => $row->document_no,
                'label' => 'SPL Approved',
                'job_code' => $jobCode !== '' ? $jobCode : null,
                'notes' => trim(
                    ($row->document_no ?: '-')
                    .($jobCode !== '' ? (' / '.$jobCode) : '')
                    .' / '.$this->formatOvertimeTypeBadge((string) ($row->overtime_type ?: 'normal'))
                    .' / '.substr((string) $row->start_time, 0, 5).'-'.substr((string) $row->end_time, 0, 5)
                ),
                'start_time' => (string) ($row->start_time ?? ''),
                'end_time' => (string) ($row->end_time ?? ''),
                'overtime_type' => (string) ($row->overtime_type ?: 'normal'),
                'overtime_segment' => (string) ($row->overtime_segment ?? ''),
                'rule_payload' => $row->rule_payload,
            ];
        }

        return $map;
    }

    // =========================================================================
    // buildContinuesNextDayBridgeMap() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildContinuesNextDayBridgeMap($employeeIds, Carbon $startDate, Carbon $endDate): array
    {
        $map = [];
        if ($employeeIds->isEmpty() || ! class_exists(SuratPerintahLemburModel::class)) {
            return $map;
        }

        $rows = SuratPerintahLemburModel::query()
            ->where('status', 'approved')
            ->where('is_active', true)
            ->where('overtime_type', SuratPerintahLemburModel::OVERTIME_TYPE_CONTINUES_NEXT_DAY)
            ->whereIn('karyawan_id', $employeeIds)
            ->whereDate('work_date', '>=', $startDate->copy()->subDay()->format('Y-m-d'))
            ->whereDate('work_date', '<=', $endDate->format('Y-m-d'))
            ->with('job:id,code')
            ->get(['id', 'document_no', 'karyawan_id', 'job_id', 'work_date', 'start_time', 'end_time', 'overtime_type', 'rule_payload']);

        foreach ($rows as $row) {
            $startDateKey = optional($row->work_date)->format('Y-m-d');
            if (! $startDateKey) {
                continue;
            }

            $carryDateKey = optional($row->work_date)?->copy()->addDay()->format('Y-m-d');
            $jobCode = trim((string) ($row->job?->code ?? ''));
            $notes = trim(
                ($row->document_no ?: '-')
                .($jobCode !== '' ? (' / '.$jobCode) : '')
                .' / ContinuesNextDay'
                .' / '.substr((string) ($row->start_time ?? ''), 0, 5).'-'.substr((string) ($row->end_time ?? ''), 0, 5)
            );

            $base = [
                'reference_id' => (int) $row->id,
                'document_no' => (string) ($row->document_no ?: ''),
                'job_code' => $jobCode !== '' ? $jobCode : null,
                'notes' => $notes,
                'start_date' => $startDateKey,
                'carry_date' => $carryDateKey,
                'start_time' => (string) ($row->start_time ?? ''),
                'end_time' => (string) ($row->end_time ?? ''),
                'overtime_type' => (string) ($row->overtime_type ?: SuratPerintahLemburModel::OVERTIME_TYPE_CONTINUES_NEXT_DAY),
                'rule_payload' => is_array($row->rule_payload) ? $row->rule_payload : [],
            ];

            $map[((int) $row->karyawan_id).'|'.$startDateKey] = $base + ['mode' => 'start'];
            if ($carryDateKey) {
                $map[((int) $row->karyawan_id).'|'.$carryDateKey] = $base + ['mode' => 'carry'];
            }
        }

        return $map;
    }

    // =========================================================================
    // buildContinuesNextDayReason() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildContinuesNextDayReason(array $bridge): string
    {
        $documentNo = trim((string) ($bridge['document_no'] ?? '-'));
        $jobCode = trim((string) ($bridge['job_code'] ?? ''));
        $startDate = trim((string) ($bridge['start_date'] ?? ''));
        $carryDate = trim((string) ($bridge['carry_date'] ?? ''));
        $startTime = substr((string) ($bridge['start_time'] ?? ''), 0, 5);
        $endTime = substr((string) ($bridge['end_time'] ?? ''), 0, 5);

        if (($bridge['mode'] ?? '') === 'carry') {
            return trim(
                'Carry-over SPL ContinuesNextDay dari '
                .($startDate !== '' ? Carbon::parse($startDate)->format('d/m/Y') : '-')
                .'.'
                .($documentNo !== '' ? (' SPL Approved: '.$documentNo.'.') : '')
                .($jobCode !== '' ? (' No Job: '.$jobCode.'.') : '')
                .($startTime !== '' || $endTime !== '' ? (' Window: '.($startTime ?: '-').' -> '.($endTime ?: '-').'.') : '')
            );
        }

        return trim(
            'SPL ContinuesNextDay approved, bridged ke '
            .($carryDate !== '' ? Carbon::parse($carryDate)->format('d/m/Y') : 'hari berikutnya')
            .'.'
            .($documentNo !== '' ? (' SPL Approved: '.$documentNo.'.') : '')
            .($jobCode !== '' ? (' No Job: '.$jobCode.'.') : '')
            .($startTime !== '' || $endTime !== '' ? (' Window: '.($startTime ?: '-').' -> next day '.($endTime ?: '-').'.') : '')
        );
    }

    // =========================================================================
    // resolveCrossDayPairingRole() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveCrossDayPairingRole(
        string $dateKey,
        ?string $rawLogInAt,
        ?string $rawLogOutAt,
        bool $isCrossDayShift,
        ?array $continuesBridge = null
    ): ?string {
        if (is_array($continuesBridge)) {
            return ($continuesBridge['mode'] ?? '') === 'carry' ? 'carry' : 'anchor';
        }

        if (! $isCrossDayShift) {
            return null;
        }

        $rawInDate = $rawLogInAt ? substr((string) $rawLogInAt, 0, 10) : null;
        $rawOutDate = $rawLogOutAt ? substr((string) $rawLogOutAt, 0, 10) : null;

        if ($rawInDate === $dateKey && $rawOutDate !== null && $rawOutDate > $dateKey) {
            return 'anchor';
        }

        if ($rawOutDate === $dateKey && $rawInDate !== null && $rawInDate < $dateKey) {
            return 'carry';
        }

        if ($rawInDate === $dateKey && $rawOutDate === $dateKey) {
            return 'single_day';
        }

        return 'paired';
    }

    // =========================================================================
    // resolveContinuesBridgeWindow() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveContinuesBridgeWindow(array $bridge): ?array
    {
        $startDate = trim((string) ($bridge['start_date'] ?? ''));
        $carryDate = trim((string) ($bridge['carry_date'] ?? ''));
        $startTime = substr(trim((string) ($bridge['start_time'] ?? '')), 0, 8);
        $endTime = substr(trim((string) ($bridge['end_time'] ?? '')), 0, 8);

        if ($startDate === '' || $startTime === '' || $endTime === '') {
            return null;
        }

        try {
            $startAt = Carbon::parse($startDate.' '.$startTime);
            $endBaseDate = $carryDate !== '' ? $carryDate : $startDate;
            $endAt = Carbon::parse($endBaseDate.' '.$endTime);
            if ($endAt->lte($startAt)) {
                $endAt->addDay();
            }

            return [
                'start_at' => $startAt,
                'end_at' => $endAt,
                'hours' => round($startAt->diffInMinutes($endAt) / 60, 4),
            ];
        } catch (\Throwable $e) {
            return null;
        }
    }

    // =========================================================================
    // formatOvertimeTypeBadge() - Memformat data untuk output
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function formatOvertimeTypeBadge(string $type): string
    {
        $t = strtolower(trim($type));
        if ($t === SuratPerintahLemburModel::OVERTIME_TYPE_NO_REST) {
            return 'NOREST-1';
        }
        if ($t === (defined(SuratPerintahLemburModel::class.'::OVERTIME_TYPE_NO_REST_SKIP_BREAK')
            ? SuratPerintahLemburModel::OVERTIME_TYPE_NO_REST_SKIP_BREAK
            : 'no_rest_skip_break')) {
            return 'NOREST-2';
        }

        return strtoupper($t !== '' ? $t : 'normal');
    }

    // =========================================================================
    // hasApprovedOvertimeType() - Cek kondisi tertentu, return bool
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function hasApprovedOvertimeType(array $windows, string $type): bool
    {
        $want = strtolower(trim($type));
        foreach ($windows as $w) {
            $got = strtolower(trim((string) ($w['overtime_type'] ?? '')));
            if ($got !== '' && $got === $want) {
                return true;
            }
        }

        return false;
    }

    // =========================================================================
    // resolveApprovedOvertimeWindowForShift() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveApprovedOvertimeWindowForShift(array $windows, ?Carbon $shiftStart, ?Carbon $shiftEnd): array
    {
        $result = [
            'has_any' => ! empty($windows),
            'allow_pre' => false,
            'pre_start' => null,
            'allow_post' => false,
            'post_end' => null,
        ];

        if (empty($windows) || ! $shiftStart || ! $shiftEnd) {
            return $result;
        }

        foreach ($windows as $window) {
            $startTime = substr((string) ($window['start_time'] ?? ''), 0, 8);
            $endTime = substr((string) ($window['end_time'] ?? ''), 0, 8);
            if ($startTime === '' || $endTime === '') {
                continue;
            }

            $windowStart = Carbon::parse($shiftStart->format('Y-m-d').' '.$startTime);
            $windowEnd = Carbon::parse($shiftStart->format('Y-m-d').' '.$endTime);
            if ($windowEnd->lte($windowStart)) {
                $windowEnd->addDay();
            }

            if ($windowStart->lt($shiftStart)) {
                $result['allow_pre'] = true;
                if (! $result['pre_start'] || $windowStart->lt($result['pre_start'])) {
                    $result['pre_start'] = $windowStart->copy();
                }
            }

            if ($windowEnd->gt($shiftEnd)) {
                $result['allow_post'] = true;
                if (! $result['post_end'] || $windowEnd->gt($result['post_end'])) {
                    $result['post_end'] = $windowEnd->copy();
                }
            }
        }

        return $result;
    }

    // =========================================================================
    // assignmentAllowsAutomaticOvertimeWithoutSpl() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function assignmentAllowsAutomaticOvertimeWithoutSpl(?ProfilBulanKaryawanModel $assignment): bool
    {
        static $hasColumn = null;

        if (! $assignment) {
            return false;
        }

        if ($hasColumn === null) {
            $hasColumn = Schema::hasColumn('master_profil_bulan_karyawans', 'overtime_auto_without_spl');
        }

        if (! $hasColumn) {
            return false;
        }

        return (bool) ($assignment->overtime_auto_without_spl ?? false);
    }

    // =========================================================================
    // assignmentAllowsAutomaticNoRestSkipBreak() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function assignmentAllowsAutomaticNoRestSkipBreak(?ProfilBulanKaryawanModel $assignment): bool
    {
        static $hasColumn = null;

        if (! $assignment) {
            return false;
        }

        if ($hasColumn === null) {
            $hasColumn = Schema::hasColumn('master_profil_bulan_karyawans', 'auto_no_rest_skip_break');
        }

        if (! $hasColumn) {
            return false;
        }

        return (bool) ($assignment->auto_no_rest_skip_break ?? false);
    }

    // =========================================================================
    // assignmentAllowsAutomaticNoRestNormalIncluded() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function assignmentAllowsAutomaticNoRestNormalIncluded(?ProfilBulanKaryawanModel $assignment): bool
    {
        static $hasColumn = null;

        if (! $assignment) {
            return false;
        }

        if ($hasColumn === null) {
            $hasColumn = Schema::hasColumn('master_profil_bulan_karyawans', 'auto_no_rest_normal_included');
        }

        if (! $hasColumn) {
            return false;
        }

        return (bool) ($assignment->auto_no_rest_normal_included ?? false);
    }

    // =========================================================================
    // assignmentAutomaticOvertimeWorkdayMode() - Helper function internal
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function assignmentAutomaticOvertimeWorkdayMode(?ProfilBulanKaryawanModel $assignment): string
    {
        static $hasColumn = null;

        if (! $assignment) {
            return 'post_shift';
        }

        if ($hasColumn === null) {
            $hasColumn = Schema::hasColumn('master_profil_bulan_karyawans', 'overtime_auto_workday_mode');
        }

        if (! $hasColumn) {
            return 'post_shift';
        }

        $mode = strtolower(trim((string) ($assignment->overtime_auto_workday_mode ?? 'post_shift')));

        return in_array($mode, ['post_shift', 'full_actual'], true) ? $mode : 'post_shift';
    }

    // =========================================================================
    // detectNoRestSkipBreakCandidate() - Mendeteksi kondisi/pola tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function detectNoRestSkipBreakCandidate(
        string $dateKey,
        string $dayType,
        ?string $breakStartTime,
        ?string $breakEndTime,
        ?string $rawLogInAt,
        ?string $rawLogOutAt
    ): array {
        if ($dayType !== 'workday') {
            return ['candidate' => false, 'minutes' => 0];
        }

        $breakStartTime = trim((string) $breakStartTime);
        $breakEndTime = trim((string) $breakEndTime);
        if ($breakStartTime === '' || $breakEndTime === '' || empty($rawLogInAt) || empty($rawLogOutAt)) {
            return ['candidate' => false, 'minutes' => 0];
        }

        try {
            $rawIn = Carbon::parse((string) $rawLogInAt);
            $rawOut = Carbon::parse((string) $rawLogOutAt);
            if ($rawOut->lte($rawIn)) {
                return ['candidate' => false, 'minutes' => 0];
            }

            $breakStartAt = Carbon::parse($dateKey.' '.substr($breakStartTime, 0, 8));
            $breakEndAt = Carbon::parse($dateKey.' '.substr($breakEndTime, 0, 8));
            if ($breakEndAt->lte($breakStartAt)) {
                $breakEndAt->addDay();
            }

            $overlapStart = $rawIn->gt($breakStartAt) ? $rawIn->copy() : $breakStartAt->copy();
            $overlapEnd = $rawOut->lt($breakEndAt) ? $rawOut->copy() : $breakEndAt->copy();
            if (! $overlapEnd->gt($overlapStart)) {
                return ['candidate' => false, 'minutes' => 0];
            }

            $minutes = $overlapStart->diffInMinutes($overlapEnd);
            $threshold = max(1, (int) env('ATTENDANCE_NOREST2_THRESHOLD_MINUTES', 30));

            return [
                'candidate' => $minutes >= $threshold,
                'minutes' => $minutes,
            ];
        } catch (\Throwable $e) {
            return ['candidate' => false, 'minutes' => 0];
        }
    }

    // =========================================================================
    // buildOvertimeTagMap() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildOvertimeTagMap($employeeIds, Carbon $startDate, Carbon $endDate): array
    {
        $map = [];
        if ($employeeIds->isEmpty() || ! class_exists(SuratPerintahLemburModel::class)) {
            return $map;
        }

        $rows = SuratPerintahLemburModel::query()
            ->whereIn('status', ['draft', 'submitted', 'in_review', 'approved'])
            ->where('is_active', true)
            ->whereIn('karyawan_id', $employeeIds)
            ->whereDate('work_date', '>=', $startDate->format('Y-m-d'))
            ->whereDate('work_date', '<=', $endDate->format('Y-m-d'))
            ->with('job:id,code')
            ->get(['id', 'document_no', 'karyawan_id', 'job_id', 'work_date', 'start_time', 'end_time', 'overtime_type', 'status']);

        foreach ($rows as $row) {
            $dateKey = optional($row->work_date)->format('Y-m-d');
            if (! $dateKey) {
                continue;
            }
            $key = ((int) $row->karyawan_id).'|'.$dateKey;
            $tagKey = match ((string) $row->status) {
                'approved' => 'overtime_approved',
                'in_review' => 'overtime_in_review',
                'submitted' => 'overtime_submitted',
                default => 'overtime_draft',
            };
            $tagLabel = match ((string) $row->status) {
                'approved' => 'SPL Approved',
                'in_review' => 'SPL In Review',
                'submitted' => 'SPL Submitted',
                default => 'SPL Draft',
            };
            $jobCode = trim((string) ($row->job?->code ?? ''));
            $typeBadge = $this->formatOvertimeTypeBadge((string) ($row->overtime_type ?: 'normal'));
            $map[$key] = [
                'reference_id' => (int) $row->id,
                'status' => (string) $row->status,
                'document_no' => (string) ($row->document_no ?: ''),
                'tag_key' => $tagKey,
                'label' => $tagLabel,
                'notes' => trim(
                    ($row->document_no ?: '-')
                    .($jobCode !== '' ? (' / '.$jobCode) : '')
                    .' / '.$typeBadge
                    .' / '.substr((string) $row->start_time, 0, 5).'-'.substr((string) $row->end_time, 0, 5)
                ),
            ];
        }

        return $map;
    }

    // =========================================================================
    // buildOvertimeEntryListMap() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildOvertimeEntryListMap($employeeIds, Carbon $startDate, Carbon $endDate): array
    {
        $map = [];
        if ($employeeIds->isEmpty() || ! class_exists(SuratPerintahLemburModel::class)) {
            return $map;
        }

        $rows = SuratPerintahLemburModel::query()
            ->whereIn('status', ['draft', 'submitted', 'in_review', 'approved'])
            ->where('is_active', true)
            ->whereIn('karyawan_id', $employeeIds)
            ->whereDate('work_date', '>=', $startDate->format('Y-m-d'))
            ->whereDate('work_date', '<=', $endDate->format('Y-m-d'))
            ->with('job:id,code')
            ->orderBy('work_date')
            ->orderBy('id')
            ->get(['id', 'document_no', 'karyawan_id', 'job_id', 'work_date', 'start_time', 'end_time', 'overtime_type', 'status']);

        foreach ($rows as $row) {
            $dateKey = optional($row->work_date)->format('Y-m-d');
            if (! $dateKey) {
                continue;
            }

            $key = ((int) $row->karyawan_id).'|'.$dateKey;
            $tagKey = match ((string) $row->status) {
                'approved' => 'overtime_approved',
                'in_review' => 'overtime_in_review',
                'submitted' => 'overtime_submitted',
                default => 'overtime_draft',
            };
            $tagLabel = match ((string) $row->status) {
                'approved' => 'SPL Approved',
                'in_review' => 'SPL In Review',
                'submitted' => 'SPL Submitted',
                default => 'SPL Draft',
            };
            $jobCode = trim((string) ($row->job?->code ?? ''));
            $typeBadge = $this->formatOvertimeTypeBadge((string) ($row->overtime_type ?: 'normal'));

            $map[$key] ??= [];
            $map[$key][] = [
                'reference_id' => (int) $row->id,
                'status' => (string) $row->status,
                'document_no' => (string) ($row->document_no ?: ''),
                'tag_key' => $tagKey,
                'label' => $tagLabel,
                'overtime_type' => (string) ($row->overtime_type ?: 'normal'),
                'notes' => trim(
                    ($row->document_no ?: '-')
                    .($jobCode !== '' ? (' / '.$jobCode) : '')
                    .' / '.$typeBadge
                    .' / '.substr((string) $row->start_time, 0, 5).'-'.substr((string) $row->end_time, 0, 5)
                ),
            ];
        }

        return $map;
    }

    // =========================================================================
    // hasOvertimeTypeInEntryList() - Cek kondisi tertentu, return bool
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function hasOvertimeTypeInEntryList(array $entries, string $overtimeType): bool
    {
        $want = strtolower(trim($overtimeType));
        if ($want === '') {
            return false;
        }

        foreach ($entries as $entry) {
            $got = strtolower(trim((string) ($entry['overtime_type'] ?? '')));
            if ($got !== '' && $got === $want) {
                return true;
            }
        }

        return false;
    }

    // =========================================================================
    // buildForgettingClockTagMap() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildForgettingClockTagMap($employeeIds, Carbon $startDate, Carbon $endDate): array
    {
        $map = [];
        if ($employeeIds->isEmpty() || ! class_exists(ForgettingClockRequestModel::class)) {
            return $map;
        }

        $rows = ForgettingClockRequestModel::query()
            ->whereIn('status', ['draft', 'submitted', 'in_review', 'approved'])
            ->whereIn('karyawan_id', $employeeIds)
            ->whereDate('work_date', '>=', $startDate->format('Y-m-d'))
            ->whereDate('work_date', '<=', $endDate->format('Y-m-d'))
            ->get(['id', 'request_no', 'karyawan_id', 'work_date', 'requested_checkin_at', 'requested_checkout_at', 'status']);

        foreach ($rows as $row) {
            $dateKey = optional($row->work_date)->format('Y-m-d');
            if (! $dateKey) {
                continue;
            }
            $key = ((int) $row->karyawan_id).'|'.$dateKey;
            $tagKey = match ((string) $row->status) {
                'approved' => 'forgetting_clock_approved',
                'in_review' => 'forgetting_clock_in_review',
                'submitted' => 'forgetting_clock_submitted',
                default => 'forgetting_clock_draft',
            };
            $tagLabel = match ((string) $row->status) {
                'approved' => 'FC Approved',
                'in_review' => 'FC In Review',
                'submitted' => 'FC Submitted',
                default => 'FC Draft',
            };
            $in = optional($row->requested_checkin_at)->format('H:i') ?: '-';
            $out = optional($row->requested_checkout_at)->format('H:i') ?: '-';
            $map[$key] = [
                'tag_key' => $tagKey,
                'label' => $tagLabel,
                'notes' => trim(($row->request_no ?: '-').' / '.$in.'-'.$out),
                'reference_id' => (int) ($row->id ?? 0),
            ];
        }

        return $map;
    }

    // =========================================================================
    // buildOfflinePendingMap() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildOfflinePendingMap($employeeIds, Carbon $startDate, Carbon $endDate): array
    {
        $map = [];
        if ($employeeIds->isEmpty()) {
            return $map;
        }

        $rows = AttendanceLogModel::query()
            ->selectRaw('karyawan_id, DATE(log_at) as work_date, COUNT(*) as total')
            ->whereIn('karyawan_id', $employeeIds)
            ->whereDate('log_at', '>=', $startDate->format('Y-m-d'))
            ->whereDate('log_at', '<=', $endDate->format('Y-m-d'))
            ->where('notes', 'like', '%OFFLINE_PENDING_APPROVAL%')
            ->groupBy('karyawan_id', DB::raw('DATE(log_at)'))
            ->get();

        foreach ($rows as $row) {
            $dateKey = (string) ($row->work_date ?? '');
            $karyawanId = (int) ($row->karyawan_id ?? 0);
            if ($karyawanId <= 0 || $dateKey === '') {
                continue;
            }
            $map[$karyawanId.'|'.$dateKey] = (int) ($row->total ?? 0);
        }

        return $map;
    }

    // =========================================================================
    // resolveAttendanceTag() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveAttendanceTag(string $dateKey, int $karyawanId, array $leaveMap, array $overtimeMap, array $forgettingClockMap = []): array
    {
        $key = $karyawanId.'|'.$dateKey;
        if (isset($leaveMap[$key])) {
            return [
                'tag_key' => 'leave_approved',
                'tag_label' => $leaveMap[$key]['label'] ?? 'Leave Approved',
                'tag_notes' => $leaveMap[$key]['notes'] ?? null,
            ];
        }
        if (isset($overtimeMap[$key])) {
            return [
                'tag_key' => $overtimeMap[$key]['tag_key'] ?? 'overtime_draft',
                'tag_label' => $overtimeMap[$key]['label'] ?? 'SPL Draft',
                'tag_notes' => $overtimeMap[$key]['notes'] ?? null,
                'reference_id' => $overtimeMap[$key]['reference_id'] ?? null,
                'status' => $overtimeMap[$key]['status'] ?? null,
                'document_no' => $overtimeMap[$key]['document_no'] ?? null,
            ];
        }
        if (isset($forgettingClockMap[$key])) {
            return [
                'tag_key' => $forgettingClockMap[$key]['tag_key'] ?? 'forgetting_clock_draft',
                'tag_label' => $forgettingClockMap[$key]['label'] ?? 'FC Draft',
                'tag_notes' => $forgettingClockMap[$key]['notes'] ?? null,
                'reference_id' => $forgettingClockMap[$key]['reference_id'] ?? null,
            ];
        }

        return [
            'tag_key' => null,
            'tag_label' => null,
            'tag_notes' => null,
        ];
    }

    // =========================================================================
    // classifyCalculationSheetLeaveCounterKey() - Mengklasifikasikan data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function classifyCalculationSheetLeaveCounterKey(string $leaveType): ?string
    {
        $type = strtolower(trim($leaveType));
        if ($type === '') {
            return null;
        }

        if (
            str_contains($type, 'collective')
            || str_contains($type, 'cuti_bersama')
            || str_contains($type, 'cuti bersama')
            || str_contains($type, 'bersama')
        ) {
            return 'collective';
        }

        if (
            $type === 'annual'
            || str_contains($type, 'annual_leave')
            || str_contains($type, 'annual')
            || str_contains($type, 'cuti')
        ) {
            return 'annual';
        }

        return null;
    }

    // =========================================================================
    // resolveDayTypeForCalculation() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveDayTypeForCalculation(string $dateKey, array $holidayMap, array $workdayMap, array $holidaySpecialMap = []): string
    {
        if (isset($workdayMap[$dateKey])) {
            return 'workday';
        }

        if (isset($holidaySpecialMap[$dateKey])) {
            return 'holiday_special';
        }

        // Holiday should take precedence over weekend if an explicit calendar event exists.
        // Note: buildCalendarMarks() pre-fills weekend into holidayMap with label "Weekend",
        // so exclude that marker here. Also treat labels containing "weekend" or "mingguan"
        // as weekend even if they are stored as holiday events.
        if (isset($holidayMap[$dateKey])) {
            $label = strtolower(trim((string) $holidayMap[$dateKey]));
            if ($label === 'weekend' || str_contains($label, 'weekend') || str_contains($label, 'mingguan')) {
                return 'weekend';
            }

            return 'holiday';
        }

        $isoDay = (int) date('N', strtotime($dateKey));
        if ($isoDay === 6 || $isoDay === 7) {
            return 'weekend';
        }

        return 'workday';
    }

    // =========================================================================
    // applyOvertimeMultiplier() - Menerapkan perubahan pada data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function applyOvertimeMultiplier(float $overtimeHours, string $dayType, array $rules): float
    {
        return $this->applyOvertimeMultiplierInternal($overtimeHours, $dayType, $rules, false);
    }

    // =========================================================================
    // applyOvertimeMultiplierInternal() - Menerapkan perubahan pada data
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function applyOvertimeMultiplierInternal(float $overtimeHours, string $dayType, array $rules, bool $skipBreak): float
    {
        if ($overtimeHours <= 0) {
            return 0.0;
        }

        $timeline = $this->buildOvertimeTimeline($overtimeHours, $dayType, $rules, $skipBreak);
        $lastMultiplier = ! empty($timeline) ? (float) end($timeline)['multiplier'] : 1.5;
        $weighted = 0.0;
        $remaining = $overtimeHours;
        $hourOrdinal = 1;

        while ($remaining > 0) {
            $chunk = min(1.0, $remaining);
            $multiplier = isset($timeline[$hourOrdinal]) ? (float) ($timeline[$hourOrdinal]['multiplier'] ?? $lastMultiplier) : $lastMultiplier;
            $weighted += $chunk * max(0.0, $multiplier);
            $remaining -= $chunk;
            $hourOrdinal++;
        }

        return round($weighted, 4);
    }

    // =========================================================================
    // calculateOvertimeBreakdownDynamic() - Menghitung/mengkomputasi nilai
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function calculateOvertimeBreakdownDynamic(float $overtimeHours, string $dayType, array $rules): array
    {
        return $this->calculateOvertimeBreakdownDynamicInternal($overtimeHours, $dayType, $rules, false);
    }

    // =========================================================================
    // calculateOvertimeBreakdownDynamicInternal() - Menghitung/mengkomputasi nilai
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function calculateOvertimeBreakdownDynamicInternal(float $overtimeHours, string $dayType, array $rules, bool $skipBreak): array
    {
        $result = [];

        if ($overtimeHours <= 0) {
            return $result;
        }

        $timeline = $this->buildOvertimeTimeline($overtimeHours, $dayType, $rules, $skipBreak);
        $lastMultiplier = ! empty($timeline) ? (float) end($timeline)['multiplier'] : 1.5;

        $remaining = $overtimeHours;
        $hourOrdinal = 1;

        while ($remaining > 0) {
            $chunk = min(1.0, $remaining);
            $multiplier = isset($timeline[$hourOrdinal]) ? (float) ($timeline[$hourOrdinal]['multiplier'] ?? $lastMultiplier) : $lastMultiplier;
            $bucket = number_format($multiplier, 1, '.', '');
            if (! isset($result[$bucket])) {
                $result[$bucket] = 0.0;
            }
            $result[$bucket] += $chunk;
            $remaining -= $chunk;
            $hourOrdinal++;
        }

        foreach ($result as $k => $v) {
            $result[$k] = round($v, 1);
        }

        return $result;
    }

    // =========================================================================
    // calculateOvertimeBreakDeductionHours() - Menghitung/mengkomputasi nilai
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function calculateOvertimeBreakDeductionHours(float $overtimeHours, string $dayType, array $rules): float
    {
        return $this->calculateOvertimeBreakDeductionHoursInternal($overtimeHours, $dayType, $rules, false);
    }

    // =========================================================================
    // calculateOvertimeBreakDeductionHoursInternal() - Menghitung/mengkomputasi nilai
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function calculateOvertimeBreakDeductionHoursInternal(float $overtimeHours, string $dayType, array $rules, bool $skipBreak): float
    {
        if ($overtimeHours <= 0) {
            return 0.0;
        }
        // NoRest-2: skip BREAK x0 (do not deduct any break hours from overtime calculation).
        if ($skipBreak) {
            return 0.0;
        }

        $dayRules = collect($this->resolveOvertimeRulesForDayType($dayType, $rules))
            ->filter(fn ($rule) => (bool) ($rule['is_break'] ?? false))
            ->sortBy([
                ['hour_start', 'asc'],
                ['hour_end', 'asc'],
            ])
            ->values();

        if ($dayRules->isEmpty()) {
            return 0.0;
        }

        $deduction = 0.0;
        foreach ($dayRules as $rule) {
            $start = max(1.0, (float) ($rule['hour_start'] ?? 1));
            $end = max($start, (float) ($rule['hour_end'] ?? $start));
            if ($overtimeHours < $start) {
                continue;
            }

            $coveredEnd = min($overtimeHours, $end);
            if ($coveredEnd < $start) {
                continue;
            }

            $deduction += ($coveredEnd - $start) + 1.0;
        }

        return round(max(0.0, min($overtimeHours, $deduction)), 4);
    }

    // =========================================================================
    // buildOvertimeDetailSegments() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildOvertimeDetailSegments(float $overtimeHours, string $dayType, array $rules): array
    {
        return $this->buildOvertimeDetailSegmentsInternal($overtimeHours, $dayType, $rules, false);
    }

    // =========================================================================
    // buildOvertimeDetailSegmentsInternal() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildOvertimeDetailSegmentsInternal(float $overtimeHours, string $dayType, array $rules, bool $skipBreak): array
    {
        if ($overtimeHours <= 0) {
            return [];
        }

        $timeline = $this->buildOvertimeTimeline($overtimeHours, $dayType, $rules, $skipBreak);
        if (empty($timeline)) {
            return [[
                'label' => 'Jam ke-1 dst x1.5',
                'hours' => round($overtimeHours, 2),
                'is_break' => false,
            ]];
        }

        $segments = [];
        $remaining = $overtimeHours;
        $hourOrdinal = 1;
        $lastMultiplier = (float) end($timeline)['multiplier'];

        while ($remaining > 0) {
            $chunk = min(1.0, $remaining);
            $row = $timeline[$hourOrdinal] ?? ['multiplier' => $lastMultiplier, 'is_break' => false];
            $isBreak = (bool) ($row['is_break'] ?? false);
            $multiplier = (float) ($row['multiplier'] ?? $lastMultiplier);
            $signature = implode('|', [
                $isBreak ? 'break' : 'work',
                number_format($multiplier, 1, '.', ''),
            ]);

            $lastIndex = count($segments) - 1;
            if ($lastIndex >= 0 && ($segments[$lastIndex]['signature'] ?? '') === $signature && (int) $segments[$lastIndex]['end_hour'] === ($hourOrdinal - 1)) {
                $segments[$lastIndex]['end_hour'] = $hourOrdinal;
                $segments[$lastIndex]['hours'] = round((float) $segments[$lastIndex]['hours'] + $chunk, 2);
            } else {
                $segments[] = [
                    'signature' => $signature,
                    'start_hour' => $hourOrdinal,
                    'end_hour' => $hourOrdinal,
                    'hours' => round($chunk, 2),
                    'is_break' => $isBreak,
                    'multiplier' => $multiplier,
                ];
            }

            $remaining -= $chunk;
            $hourOrdinal++;
        }

        return collect($segments)->map(function (array $segment) {
            $rangeLabel = ((int) $segment['start_hour'] === (int) $segment['end_hour'])
                ? 'Jam ke-'.(int) $segment['start_hour']
                : 'Jam ke-'.(int) $segment['start_hour'].' s/d '.(int) $segment['end_hour'];

            if ($segment['is_break']) {
                $label = $rangeLabel.' BREAK';
            } else {
                $multiplierText = rtrim(rtrim(number_format((float) $segment['multiplier'], 1, '.', ''), '0'), '.');
                $label = $rangeLabel.' x'.$multiplierText;
            }

            return [
                'label' => $label,
                'hours' => round((float) $segment['hours'], 2),
                'is_break' => (bool) $segment['is_break'],
            ];
        })->values()->all();
    }

    // =========================================================================
    // buildOvertimeTimeline() - Membangun/membuat data payload
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function buildOvertimeTimeline(float $overtimeHours, string $dayType, array $rules, bool $skipBreak): array
    {
        $need = (int) ceil(max(0.0, $overtimeHours));
        if ($need <= 0) {
            return [];
        }

        $dayRules = collect($this->resolveOvertimeRulesForDayType($dayType, $rules))
            ->sortBy([
                ['hour_start', 'asc'],
                ['hour_end', 'asc'],
            ])
            ->values();

        if ($dayRules->isEmpty()) {
            $fallback = 1.5;
            $timeline = [];
            for ($i = 1; $i <= $need; $i++) {
                $timeline[$i] = ['multiplier' => $fallback, 'is_break' => false];
            }

            return $timeline;
        }

        $lastRule = (array) $dayRules->last();
        $lastNonBreak = (array) ($dayRules
            ->filter(fn ($r) => ! ((bool) ($r['is_break'] ?? false)))
            ->last() ?? $lastRule);
        $fallbackMultiplier = (float) ($lastNonBreak['multiplier'] ?? 1.5);
        if ($fallbackMultiplier <= 0) {
            $fallbackMultiplier = 1.5;
        }

        $timeline = [];
        $rawOrdinal = 1;
        $paidOrdinal = 1;
        $maxRaw = 48; // safety guard

        while ($paidOrdinal <= $need && $rawOrdinal <= $maxRaw) {
            $foundRule = $dayRules->first(function ($rule) use ($rawOrdinal) {
                $start = (float) ($rule['hour_start'] ?? 1);
                $end = (float) ($rule['hour_end'] ?? $start);

                return $rawOrdinal >= $start && $rawOrdinal <= $end;
            }) ?? $lastRule;

            $isBreak = (bool) ($foundRule['is_break'] ?? false);
            if ($skipBreak && $isBreak) {
                $rawOrdinal++;

                continue;
            }

            $multiplier = (float) ($foundRule['multiplier'] ?? $fallbackMultiplier);
            if ($skipBreak && $multiplier <= 0) {
                // For safety: when skipping break, never output a 0 multiplier slot.
                $multiplier = $fallbackMultiplier;
            }

            $timeline[$paidOrdinal] = [
                'multiplier' => $multiplier,
                'is_break' => $isBreak && ! $skipBreak,
            ];

            $paidOrdinal++;
            $rawOrdinal++;
        }

        // If we ran out of rules, keep using fallback multiplier.
        for (; $paidOrdinal <= $need; $paidOrdinal++) {
            $timeline[$paidOrdinal] = ['multiplier' => $fallbackMultiplier, 'is_break' => false];
        }

        return $timeline;
    }

    // =========================================================================
    // resolveOvertimeRulesForDayType() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveOvertimeRulesForDayType(string $dayType, array $rules): array
    {
        $dayRules = collect($rules)
            ->filter(fn ($rule) => ($rule['day_type'] ?? null) === $dayType)
            ->sortBy([
                ['hour_start', 'asc'],
                ['hour_end', 'asc'],
            ])
            ->values()
            ->all();

        if (! empty($dayRules)) {
            return $dayRules;
        }

        if ($dayType === 'holiday_special') {
            return [[
                'day_type' => 'holiday_special',
                'hour_start' => 1.0,
                'hour_end' => 24.0,
                'multiplier' => 4.0,
                'is_break' => false,
            ]];
        }

        return [];
    }

    // =========================================================================
    // isHolidayLikeDayType() - Cek kondisi tertentu, return bool
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function isHolidayLikeDayType(string $dayType): bool
    {
        return in_array($dayType, ['holiday', 'holiday_special'], true);
    }

    // =========================================================================
    // resolveOvertimeColumnsFromRules() - Meresolve/menentukan nilai berdasarkan logic tertentu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function resolveOvertimeColumnsFromRules(array $rules): array
    {
        $multipliers = collect($rules)
            ->filter(fn ($rule) => ! ((bool) ($rule['is_break'] ?? false)))
            ->pluck('multiplier')
            ->filter(fn ($v) => is_numeric($v))
            ->filter(fn ($v) => (float) $v > 0)
            ->map(fn ($v) => (float) $v)
            ->unique()
            ->sort()
            ->values();

        if ($multipliers->isEmpty()) {
            $multipliers = collect([1.5, 2.0, 3.0, 4.0]);
        }

        return $multipliers->map(function (float $multiplier) {
            $key = number_format($multiplier, 1, '.', '');
            $label = rtrim(rtrim(number_format($multiplier * 100, 1, '.', ''), '0'), '.').'%';

            return [
                'key' => $key,
                'multiplier' => $multiplier,
                'label' => $label,
            ];
        })->values()->all();
    }

    // =========================================================================
    // timeToMinute() - Helper konversi waktu
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function timeToMinute(string $time): int
    {
        $parts = explode(':', trim($time));
        $hour = isset($parts[0]) ? max(0, min(23, (int) $parts[0])) : 0;
        $minute = isset($parts[1]) ? max(0, min(59, (int) $parts[1])) : 0;

        return ($hour * 60) + $minute;
    }

    // =========================================================================
    // minuteDistance() - Helper perhitungan menit
    // Dipanggil dari: internal (method lain di controller ini)
    // Output: return value untuk pemanggil internal
    // =========================================================================
    private function minuteDistance(int $a, int $b): int
    {
        $diff = abs($a - $b) % 1440;

        return (int) min($diff, 1440 - $diff);
    }
}






