<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\DeviceLog;
use Illuminate\Support\Facades\Log;

class DeviceSyncController extends Controller
{
    public function sync(Request $request)
    {
        // Many devices send data in query params even for POST, or form-data body.
        $data = $request->all();

        Log::info('Biometric Device Sync Request:', $data);

        $requestCode = $request->input('request_code');
        $devId = $request->input('dev_id');

        if ($requestCode === 'realtime_glog') {
            // It's an attendance punch
            $userId = $request->input('user_id');
            $ioTime = $request->input('io_time'); // Format: 20260518154413
            $verifyMode = $request->input('verify_mode');
            $ioMode = $request->input('io_mode');

            if ($ioTime && strlen($ioTime) === 14) {
                // Parse YYYYMMDDHHMMSS to YYYY-MM-DD HH:MM:SS
                $formattedTime = substr($ioTime, 0, 4) . '-' .
                    substr($ioTime, 4, 2) . '-' .
                    substr($ioTime, 6, 2) . ' ' .
                    substr($ioTime, 8, 2) . ':' .
                    substr($ioTime, 10, 2) . ':' .
                    substr($ioTime, 12, 2);

                // Find employee by employee_code/enroll_no from biometric device
                $employee = \App\Models\Employee::where('employee_code', $userId)
                    ->orWhere('enroll_no', $userId)
                    ->first();

                // Use employee's user_id (users.id) as the identifier — NOT employees.id
                $employeeUserId = $employee ? $employee->user_id : null;
                $companyId = $employee ? $employee->company_id : null;

                if ($employeeUserId) {
                    \App\Models\Punch::create([
                        'company_id' => $companyId,
                        'employee_id' => $employeeUserId,   // stores users.id
                        'punch_time' => $formattedTime,
                        'punch_type' => 'Machine',
                        'device' => $devId,
                        'verify_mode' => $verifyMode,
                        'io_mode' => $ioMode,
                        'status' => 'Unknown',
                    ]);

                    // Trigger attendance processing using employee's user_id
                    $dateString = substr($formattedTime, 0, 10);
                    $processor = new \App\Services\AttendanceProcessor();
                    $processor->processForDate($dateString, $employeeUserId);
                }
            }

            // Return success response based on generic standard, or 'OK' as raw string.
            return response("OK", 200)->header('Content-Type', 'text/plain');
        }

        if ($requestCode === 'realtime_enroll_data') {
            $userId = $request->input('user_id'); // e.g. 00000002
            $userName = $request->input('user_name'); // e.g. t

            // Map dev_id to machine to find company_id
            $machine = \App\Models\Machine::where('serial_no', $devId)->first();
            $companyId = $machine ? $machine->company_id : null;

            if ($companyId && $userId) {
                // Check if employee already exists
                $existingEmployee = \App\Models\Employee::where('company_id', $companyId)
                    ->where(function ($q) use ($userId) {
                        $q->where('employee_code', $userId)
                            ->orWhere('enroll_no', $userId);
                    })->first();

                if (!$existingEmployee) {
                    // Find superadmin_id from the machine
                    $superadminId = $machine->superadmin_id ?? null;

                    // Use the provided user_name, append userId to ensure it stays unique
                    $uniqueUsername = ($userName ?: 'Unknown') . '_' . $userId;

                    // Create User first
                    $newUser = \App\Models\User::create([
                        'username' => $uniqueUsername,
                        'email' => 'emp' . $userId . '_' . $companyId . '@vitxpert.com',
                        'password' => \Illuminate\Support\Facades\Hash::make('password123'),
                        'role_id' => 3, // Employee
                        'superadmin_id' => $superadminId,
                        'company_admin_id' => $companyId,
                        'company_id' => $companyId,
                    ]);

                    // Create Employee
                    \App\Models\Employee::create([
                        'user_id' => $newUser->id,
                        'company_id' => $companyId,
                        'superadmin_id' => $superadminId,
                        'employee_code' => $userId,
                        'enroll_no' => $userId,
                        'name' => $userName ?? 'Unknown Employee',
                        'email' => 'emp' . $userId . '_' . $companyId . '@vitxpert.com',
                    ]);
                }
            }

            return response("OK", 200)->header('Content-Type', 'text/plain');
        }

        // Return a generic OK for other ping/heartbeat requests
        return response("OK", 200)->header('Content-Type', 'text/plain');
    }
}
