<?php

namespace App\Http\Controllers\Api;

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

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'phone' => 'required|string|size:11|unique:users',
            'national_code' => 'required|string|size:10|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'role' => 'required|in:admin,driver,requester',
            'address' => 'nullable|string',
            'postal_code' => 'nullable|string|size:10',
            'vehicle_type' => 'nullable|string|max:64',
            'vehicle_plate' => 'nullable|string|max:32',
            'vehicle_capacity' => 'nullable|numeric|min:0',
            'smart_card_number' => 'nullable|string|max:32',
            'license_number' => 'nullable|string|max:32',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'national_code' => $request->national_code,
            'password' => Hash::make($request->password),
            'role' => $request->role,
            'address' => $request->address,
            'postal_code' => $request->postal_code,
            'vehicle_type' => $request->vehicle_type,
            'vehicle_plate' => $request->vehicle_plate,
            'vehicle_capacity' => $request->vehicle_capacity,
            'smart_card_number' => $request->smart_card_number,
            'license_number' => $request->license_number,
        ]);

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

        return response()->json([
            'success' => true,
            'message' => 'User registered successfully',
            'data' => [
                'user' => $user,
                'access_token' => $token,
                'token_type' => 'Bearer',
            ]
        ], 201);
    }

    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $user = User::where('email', $request->email)->first();

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

        if (!$user->is_active) {
            return response()->json([
                'success' => false,
                'message' => 'Your account has been deactivated',
            ], 403);
        }

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

        return response()->json([
            'success' => true,
            'message' => 'Login successful',
            'data' => [
                'user' => $user,
                'access_token' => $token,
                'token_type' => 'Bearer',
            ]
        ]);
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'success' => true,
            'message' => 'Logged out successfully'
        ]);
    }

    public function me(Request $request)
    {
        return response()->json([
            'success' => true,
            'data' => $request->user()
        ]);
    }

    public function refresh(Request $request)
    {
        $user = $request->user();
        $user->currentAccessToken()->delete();
        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'success' => true,
            'message' => 'Token refreshed successfully',
            'data' => [
                'access_token' => $token,
                'token_type' => 'Bearer',
            ]
        ]);
    }

    public function sendLoginOtp(Request $request, SmsService $smsService)
    {
        $request->validate([
            'phone' => 'required|string|regex:/^09[0-9]{9}$/',
            'login_type' => 'required|in:company,driver',
        ]);

        $code = (string) random_int(10000, 99999);
        $phone = (string) $request->input('phone');
        $loginType = (string) $request->input('login_type');

        $result = $loginType === 'driver'
            ? $smsService->sendDriverLoginOtp($phone, $code)
            : $smsService->sendCompanyOtpLogin($phone, $code);

        if (($result['success'] ?? false) === true) {
            $payload = [
                'success' => true,
                'message' => 'OTP sent successfully',
            ];

            if (config('app.debug')) {
                $payload['debug_otp'] = $code;
            }

            return response()->json($payload, 200);
        }

        return response()->json([
            'success' => false,
            'message' => 'Failed to send OTP',
            'error' => $result['message'] ?? 'Unknown error',
        ], 400);
    }

    /**
     * POST /auth/verify-otp — verify OTP and return token (driver and user app flow)
     * Compatible with POST /auth/send-otp then POST /auth/verify-otp
     *
     * برای تمام شماره‌های تلفن:
     * - اگر login_type: 'driver'، اکانت تست راننده استفاده می‌شود
     * - اگر login_type: 'user'، اکانت تست کاربر استفاده می‌شود
     */
    public function verifyOtp(Request $request)
    {
        $request->validate([
            'mobile' => 'required|string|regex:/^09[0-9]{9}$/',
            'otp'    => 'required|string|min:4|max:6',
            'login_type' => 'nullable|in:driver,user',
        ]);

        $cacheKey = 'otp_' . $request->mobile;
        $storedOtp = \Illuminate\Support\Facades\Cache::get($cacheKey);

        if (!$storedOtp || $storedOtp !== $request->otp) {
            if (!config('app.debug')) {
                return response()->json(['success' => false, 'message' => 'کد تایید نامعتبر یا منقضی شده است'], 422);
            }
        }

        $loginType = $request->input('login_type', 'driver') === 'user' ? 'user' : 'driver';

        if ($loginType === 'driver') {
            $user = User::firstOrCreate(
                ['phone' => 'test_driver'],
                [
                    'name'          => 'تست راننده',
                    'role'          => 'driver',
                    'driver_status' => 'VERIFIED',
                    'is_active'     => true,
                    'email'         => 'test.driver@sabok.local',
                    'national_code' => '1234567890',
                    'password'      => \Illuminate\Support\Facades\Hash::make('test123'),
                ]
            );
        } else {
            $user = User::firstOrCreate(
                ['phone' => 'test_customer'],
                [
                    'name'      => 'تست مشتری',
                    'role'      => 'requester',
                    'is_active' => true,
                    'email'     => 'test.customer@sabok.local',
                    'national_code' => '0987654321',
                    'password'  => \Illuminate\Support\Facades\Hash::make('test123'),
                ]
            );
        }

        \Illuminate\Support\Facades\Cache::forget($cacheKey);

        $token = $user->createToken($loginType . '-app-' . time())->plainTextToken;

        return response()->json([
            'success'       => true,
            'access_token'  => $token,
            'token_type'    => 'Bearer',
            'driver_status' => $user->driver_status ?? null,
            'user'          => $user->only(['id', 'name', 'phone', 'role']),
        ]);
    }
}
