<?php

namespace App\Http\Controllers\Api\V1\Delivery;

use App\Http\Controllers\Controller;
use App\Models\DeliveryAgent;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function login(Request $request): JsonResponse
    {
        $request->validate([
            'phone' => 'required|string',
            'password' => 'required|string',
        ]);

        $user = User::where('phone', $request->phone)
            ->where('role', 'delivery_agent')
            ->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'phone' => ['The provided credentials are incorrect.'],
            ]);
        }

        $deliveryAgent = $user->deliveryAgent;
        if (! $deliveryAgent || $deliveryAgent->status !== 'active') {
            return response()->json([
                'message' => 'Your account is not active. Please contact admin.',
            ], 403);
        }

        $token = $user->createToken('delivery-agent-token')->plainTextToken;

        return response()->json([
            'success' => true,
            'message' => 'Login successful',
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'phone' => $user->phone,
                'agent_code' => $deliveryAgent->agent_code,
                'availability_status' => $deliveryAgent->availability_status,
                'is_online' => $deliveryAgent->is_online,
            ],
        ]);
    }

    public function sendOtp(Request $request): JsonResponse
    {
        $request->validate([
            'phone' => 'required|string|exists:users,phone',
        ]);

        $user = User::where('phone', $request->phone)
            ->where('role', 'delivery_agent')
            ->first();

        if (! $user) {
            return response()->json([
                'message' => 'Phone number not found.',
            ], 404);
        }

        // Generate OTP (in production, use SMS service)
        $otp = str_pad((string) rand(1000, 9999), 4, '0', STR_PAD_LEFT);
        
        // Store OTP in session/cache (for demo, return it)
        // In production: cache()->put("otp:{$request->phone}", $otp, now()->addMinutes(5));
        
        return response()->json([
            'success' => true,
            'message' => 'OTP sent successfully',
            'otp' => $otp, // Remove in production
        ]);
    }

    public function verifyOtp(Request $request): JsonResponse
    {
        $request->validate([
            'phone' => 'required|string',
            'otp' => 'required|string|size:4',
        ]);

        // In production: $storedOtp = cache()->get("otp:{$request->phone}");
        // For demo, accept any 4-digit OTP
        
        $user = User::where('phone', $request->phone)
            ->where('role', 'delivery_agent')
            ->first();

        if (! $user) {
            return response()->json([
                'message' => 'Phone number not found.',
            ], 404);
        }

        $deliveryAgent = $user->deliveryAgent;
        if (! $deliveryAgent || $deliveryAgent->status !== 'active') {
            return response()->json([
                'message' => 'Your account is not active. Please contact admin.',
            ], 403);
        }

        $token = $user->createToken('delivery-agent-token')->plainTextToken;

        return response()->json([
            'success' => true,
            'message' => 'OTP verified successfully',
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'phone' => $user->phone,
                'agent_code' => $deliveryAgent->agent_code,
                'availability_status' => $deliveryAgent->availability_status,
                'is_online' => $deliveryAgent->is_online,
            ],
        ]);
    }
}
