<?php

namespace App\Modules\HR\Attendance\Services;

use App\Modules\HR\Attendance\Models\Attendance;
use App\Modules\HR\Attendance\Models\AttendanceDetail;
use App\Modules\HR\Attendance\Models\AttendanceRawPunch;
use App\Modules\HR\Attendance\Models\AttendanceImportLog;
use App\Modules\HR\Core\Models\Employee;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class AttendanceRecordCreatorService
{
    /**
     * Create attendance records from normalized data
     */
    public function createRecords(Collection $normalizedRecords, $setting, int $branchId, ?int $logId = null): array
    {
        $stats = [
            'success' => 0,
            'failed' => 0,
            'skipped' => 0,
            'errors' => [],
        ];

        // Flatten records
        $flatRecords = $this->flattenRecords($normalizedRecords);
        foreach ($flatRecords as $record) {
            try {
                AttendanceRawPunch::create([
                    'branch_id' => $branchId,
                    'employee_code' => $record['emp_id'],
                    'punch_time' => $record['datetime'],
                    'punch_type' => $record['punch_type'] ?? null,
                    'source' => $record['source'] ?? 'IMPORT',
                    'attendance_import_log_id' => $logId,
                ]);
                $stats['success']++;
            } catch (\Exception $e) {
                $stats['failed']++;
                $stats['errors'][] = [
                    'message' => $e->getMessage(),
                    'emp_id' => $record['emp_id'] ?? 'N/A',
                ];
            }
        }

        return $stats;
    }

    /**
     * Flatten nested record arrays
     */
    private function flattenRecords(Collection $records): Collection
    {
        $flat = collect();

        foreach ($records as $record) {
            if ($record === null) {
                continue;
            }

            // Check if it's an array of records (from direct IN/OUT mode)
            if (isset($record[0]) && is_array($record[0])) {
                foreach ($record as $subRecord) {
                    if ($subRecord !== null) {
                        $flat->push($subRecord);
                    }
                }
            } else {
                $flat->push($record);
            }
        }

        return $flat;
    }
}
