<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\AttendanceService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AttendanceController extends Controller
{
    public function __construct(protected AttendanceService $service) {}

    /**
     * POST /api/scan-attendance
     * Online scan submission.
     */
    public function scan(Request $request)
    {
        $request->validate([
            'qr_payload' => 'required|string',
            'device_id'  => 'required|string|max:255',
            'latitude'   => 'nullable|numeric|between:-90,90',
            'longitude'  => 'nullable|numeric|between:-180,180',
        ]);

        $user = Auth::user();
        if (!$user) {
            return response()->json(['success' => false, 'message' => 'Unauthenticated.'], 401);
        }

        $result = $this->service->recordScan(
            $user,
            $request->qr_payload,
            $request->device_id,
            'online',
            $request->latitude,
            $request->longitude
        );

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

    /**
     * POST /api/sync-offline
     * Batch offline sync.
     */
    public function syncOffline(Request $request)
    {
        $request->validate([
            'records'              => 'required|array|min:1|max:200',
            'records.*.temp_id'    => 'required|string',
            'records.*.qr_payload' => 'required|string',
            'records.*.device_id'  => 'required|string',
            'records.*.timestamp'  => 'required|date',
        ]);

        $user = Auth::user();
        if (!$user) {
            return response()->json(['success' => false, 'message' => 'Unauthenticated.'], 401);
        }

        $results = $this->service->syncOfflineBatch($request->records, $user);

        $synced = collect($results)->where('status', 'synced')->count();
        $failed = collect($results)->where('status', 'failed')->count();

        return response()->json([
            'success' => true,
            'summary' => ['synced' => $synced, 'failed' => $failed, 'total' => count($results)],
            'details' => $results,
        ]);
    }

    /**
     * GET /api/attendance-report
     */
    public function report(Request $request)
    {
        $request->validate([
            'date'        => 'nullable|date',
            'user_id'     => 'nullable|integer|exists:users,id',
            'location_id' => 'nullable|integer|exists:locations,id',
            'role'        => 'nullable|in:admin,teacher,student',
        ]);

        $query = \App\Models\Attendance::with(['user', 'location'])
            ->orderByDesc('created_at');

        if ($request->date) {
            $query->whereDate('created_at', $request->date);
        }
        if ($request->user_id) {
            $query->where('user_id', $request->user_id);
        }
        if ($request->location_id) {
            $query->where('location_id', $request->location_id);
        }
        if ($request->role) {
            $query->where('role', $request->role);
        }

        // Non-admin users can only see their own records
        $user = Auth::user();
        if ($user && !$user->isAdmin()) {
            $query->where('user_id', $user->id);
        }

        $records = $query->paginate(50);

        return response()->json($records);
    }
}
