<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\QrAttendanceService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class QrScannerController extends Controller
{
    public function __construct(
        protected QrAttendanceService $qrAttendanceService
    ) {}

    /**
     * Check if QR scanner is enabled and user can scan.
     */
    public function status(Request $request): JsonResponse
    {
        $user = $request->user();
        $company = $user->company;

        return response()->json([
            'success' => true,
            'data' => [
                'scanner_enabled' => $company->qr_scanner_enabled ?? false,
                'card_enabled' => $company->qr_card_enabled ?? false,
                'can_scan' => $user->hasRole(['admin', 'super_admin']),
                'scanner_radius' => $company->qr_scanner_radius ?? 100,
            ],
        ]);
    }

    /**
     * Process QR scan for attendance.
     */
    public function scan(Request $request): JsonResponse
    {
        $request->validate([
            'qr_data' => 'required|string',
            'scan_type' => 'required|in:check_in,check_out',
            'latitude' => 'required|numeric|between:-90,90',
            'longitude' => 'required|numeric|between:-180,180',
            'device_id' => 'nullable|string',
            'device_model' => 'nullable|string',
            'device_brand' => 'nullable|string',
            'os_version' => 'nullable|string',
            'app_version' => 'nullable|string',
        ]);

        $deviceInfo = [
            'device_id' => $request->device_id,
            'device_model' => $request->device_model,
            'device_brand' => $request->device_brand,
            'os_version' => $request->os_version,
            'app_version' => $request->app_version,
        ];

        $result = $this->qrAttendanceService->processQrScan(
            qrData: $request->qr_data,
            scanner: $request->user(),
            scanType: $request->scan_type,
            latitude: $request->latitude,
            longitude: $request->longitude,
            deviceInfo: $deviceInfo
        );

        return response()->json($result, $result['success'] ? 200 : 400);
    }

    /**
     * Get scan history (admin only).
     */
    public function history(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $filters = [
            'date' => $request->date,
            'scanner_id' => $request->scanner_id,
            'status' => $request->status,
            'scan_type' => $request->scan_type,
            'limit' => $request->get('limit', 50),
        ];

        $logs = $this->qrAttendanceService->getScanHistory(
            companyId: $user->company_id,
            filters: array_filter($filters)
        );

        return response()->json([
            'success' => true,
            'data' => $logs->map(function ($log) {
                return [
                    'id' => $log->id,
                    'scanned_user' => $log->scannedUser ? [
                        'id' => $log->scannedUser->id,
                        'name' => $log->scannedUser->name,
                        'employee_id' => $log->scannedUser->employee_id,
                    ] : null,
                    'scanner_user' => [
                        'id' => $log->scannerUser->id,
                        'name' => $log->scannerUser->name,
                    ],
                    'scan_type' => $log->scan_type,
                    'scan_status' => $log->scan_status,
                    'failure_reason' => $log->failure_reason,
                    'scanned_at' => $log->scanned_at->toIso8601String(),
                    'attendance_id' => $log->attendance_id,
                ];
            }),
        ]);
    }

    /**
     * Get scan statistics (admin only).
     */
    public function statistics(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $period = $request->get('period', 'today');

        $stats = $this->qrAttendanceService->getScanStatistics(
            companyId: $user->company_id,
            period: $period
        );

        return response()->json([
            'success' => true,
            'data' => $stats,
        ]);
    }
}
