<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\ValidationException;
use Carbon\Carbon;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'phone' => 'nullable|string|max:20',
            'role' => 'required|in:owner,rider,customer',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'phone' => $request->phone,
            'role' => $request->role,
        ]);

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

        return response()->json([
            'user' => $user,
            'token' => $token,
        ], 201);
    }

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

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

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

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

        return response()->json([
            'user' => $user,
            'token' => $token,
        ]);
    }

    /**
     * Customer email-only auth: send OTP code
     */
    public function sendOtp(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email|max:255',
        ]);

        $testEmail = env('TEST_CUSTOMER_EMAIL', 'test@test.com');
        $testOtp = (string) env('TEST_CUSTOMER_OTP', '12345');
        $code = $request->email === $testEmail
            ? $testOtp
            : str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);

        $otpQuery = DB::table('email_otps')->where('email', $request->email);
        if ($request->email === $testEmail) {
            $otpQuery->where('code', '!=', $testOtp);
        }
        $otpQuery->delete();

        DB::table('email_otps')->insert([
            'email' => $request->email,
            'code' => $code,
            'expires_at' => Carbon::now()->addMinutes(10),
            'used' => false,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Send email
        try {
            Mail::raw("Your FreshPress verification code is: {$code}\n\nThis code expires in 10 minutes.", function ($message) use ($request) {
                $message->to($request->email)
                    ->subject('FreshPress - Your Verification Code');
            });
        } catch (\Exception $e) {
            // Log but don't fail - in dev the code is returned
        }

        // Return OTP code only for the dedicated test email
        $response = ['message' => 'Verification code sent to your email.'];
        if ($request->email === $testEmail) {
            $response['code'] = $code;
        }

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

    /**
     * Customer email-only auth: verify OTP and login/create account
     */
    public function verifyOtp(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'code' => 'required|string|min:5|max:6',
        ]);

        $testEmail = env('TEST_CUSTOMER_EMAIL', 'test@test.com');
        $testOtp = (string) env('TEST_CUSTOMER_OTP', '12345');

        $otp = DB::table('email_otps')
            ->where('email', $request->email)
            ->where('code', $request->code)
            ->where('used', false)
            ->where('expires_at', '>', Carbon::now())
            ->first();

        if (!$otp) {
            throw ValidationException::withMessages([
                'code' => ['Invalid or expired verification code.'],
            ]);
        }

        if (!($request->email === $testEmail && $request->code === $testOtp)) {
            DB::table('email_otps')->where('id', $otp->id)->update(['used' => true]);
        }

        // Find or create customer user
        $user = User::where('email', $request->email)->first();

        if (!$user) {
            $user = User::create([
                'name' => explode('@', $request->email)[0],
                'email' => $request->email,
                'password' => Hash::make(str()->random(32)),
                'role' => 'customer',
            ]);
        }

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

        return response()->json([
            'user' => $user,
            'token' => $token,
        ]);
    }

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

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

    public function user(Request $request)
    {
        $user = $request->user();
        $user->load(['rider', 'ownedDryCleaners']);
        return response()->json($user);
    }

    public function updateProfile(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'name' => 'sometimes|string|max:255',
            'phone' => 'sometimes|string|max:20',
            'profile_pic' => 'sometimes|image|max:2048',
        ]);

        if ($request->hasFile('profile_pic')) {
            $path = $request->file('profile_pic')->store('profiles', 'public');
            $user->profile_pic = $path;
        }

        $user->fill($request->only(['name', 'phone']));
        $user->save();

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