<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Driver;
use App\Models\Rider;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    /**
     * Unified Login & Registration: Step 1 (Request OTP)
     */
    public function sendOtp(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'phone' => 'required|string|max:20',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        // Find or Create User (Placeholder)
        $user = User::firstOrCreate(
            ['phone' => $request->phone],
            ['user_type' => 'rider'] // Default
        );

        // Generate 4-digit OTP
        $otp = (string) rand(1111, 9999); 
        $user->otp_code = $otp;
        $user->otp_expires_at = now()->addMinutes(15);
        $user->save();

        // Send SMS via Termii
        $this->sendSmsOtp($user->phone, $otp);

        return response()->json([
            'success' => true,
            'message' => 'OTP sent successfully',
            'otp' => $otp, // For dev testing
        ]);
    }

    /**
     * Verify OTP: Step 2
     */
    public function verifyOtp(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'phone' => 'required|string|exists:users,phone',
            'otp' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

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

        if ($user->otp_code === $request->otp && $user->otp_expires_at->isFuture()) {
            $user->otp_code = null;
            $user->otp_expires_at = null;
            
            $token = Str::random(64);
            $user->api_token = $token;
            $user->save();

            // Profile is completed if first_name is set
            $profileCompleted = !empty($user->first_name);

            return response()->json([
                'success' => true,
                'message' => 'OTP verified successfully',
                'user' => $user->load($user->user_type ?: 'rider'),
                'access_token' => $token,
                'token_type' => 'Bearer',
                'profile_completed' => $profileCompleted,
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Invalid or expired OTP',
        ], 401);
    }

    /**
     * Complete Profile: Step 3 (Secure)
     */
    public function completeProfile(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'user_type' => 'required|string|in:rider,driver',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        $user = $request->user();

        try {
            DB::transaction(function () use ($request, $user) {
                $user->update([
                    'first_name' => $request->first_name,
                    'last_name' => $request->last_name,
                    'name' => $request->first_name . ' ' . $request->last_name,
                    'user_type' => $request->user_type,
                ]);

                // Create associated profile if it doesn't exist
                if ($request->user_type === 'driver') {
                    Driver::firstOrCreate(['user_id' => $user->id]);
                    Rider::where('user_id', $user->id)->delete(); // Clean up if they were previously a rider
                } else {
                    Rider::firstOrCreate(['user_id' => $user->id]);
                    Driver::where('user_id', $user->id)->delete(); // Clean up
                }
            });

            return response()->json([
                'success' => true,
                'message' => 'Profile completed successfully',
                'user' => $user->load($request->user_type),
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to complete profile: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Send SMS OTP using Termii
     */
    private function sendSmsOtp($phone, $otp)
    {
        $apiKey = env('TERMII_API_KEY');
        if (!$apiKey) {
            Log::warning("Termii API Key not set. SMS not sent to $phone");
            return;
        }

        $formattedPhone = $phone;
        if (str_starts_with($formattedPhone, '+')) {
            $formattedPhone = substr($formattedPhone, 1);
        }

        try {
            Http::post('https://api.ng.termii.com/api/sms/send', [
                "api_key" => $apiKey,
                "to" => $formattedPhone,
                "from" => "METRODROP",
                "sms" => "Your METRO DROP verification code is: $otp. Valid for 15 minutes.",
                "type" => "plain",
                "channel" => "generic"
            ]);
        } catch (\Exception $e) {
            Log::error("Failed to send SMS to $phone: " . $e->getMessage());
        }
    }
}
