<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;
use App\Models\CustomerAddress;
class UserAuthController extends Controller
{
  public function sendOtp(Request $request)
{
    try {

        $validator = Validator::make($request->all(), [
            'phone' => 'required'
        ]);

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

        $phone = $request->phone;

        // $otp = rand(100000, 999999);
        $otp = "123456";

        Cache::put(
            'otp_' . $phone,
            $otp,
            now()->addMinutes(5)
        );

        return response()->json([
            'status' => true,
            'message' => 'OTP sent successfully',
            'otp' => $otp, // Remove in production
            'expires_in' => 300
        ]);

    } catch (\Throwable $e) {

        return response()->json([
            'status' => false,
            'message' => 'Something went wrong.',
            'error' => $e->getMessage()
        ], 500);
    }
}

    public function verifyOtp(Request $request)
{
    try {

        $validator = Validator::make($request->all(), [
            'phone' => 'required',
            'otp' => 'required|digits:6'
        ]);

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

        $cachedOtp = Cache::get('otp_' . $request->phone);

        if (!$cachedOtp) {
            return response()->json([
                'status' => false,
                'message' => 'OTP expired'
            ], 422);
        }

        if ($cachedOtp != $request->otp) {
            return response()->json([
                'status' => false,
                'message' => 'Invalid OTP'
            ], 422);
        }

        Cache::forget('otp_' . $request->phone);

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

        $isNewUser = false;

        if (!$user) {

            $isNewUser = true;

            $user = User::create([
                'name' => 'User ' . substr($request->phone, -4),
                'phone' => $request->phone,
                'login_provider' => 'phone',
                'is_phone_verified' => true
            ]);

        } else {

            $user->update([
                'is_phone_verified' => true
            ]);
        }

        // Optional: remove old tokens
        $user->tokens()->delete();

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

        return response()->json([
            'status' => true,
            'message' => 'Login successful',
            'is_new_user' => $isNewUser,
            'token' => $token,
            'user' => $user
        ]);

    } catch (\Throwable $e) {

        return response()->json([
            'status' => false,
            'message' => 'Something went wrong.',
            'error' => $e->getMessage()
        ], 500);
    }
}

  public function save(Request $request)
    {
        try {

            $validator = Validator::make($request->all(), [
                // 'name' => 'required',
                // 'phone' => 'required',
                'address' => 'required',
                'city' => 'required',
                'state' => 'required',
                'pincode' => 'required',
                'latitude' => 'required|numeric',
                'longitude' => 'required|numeric',
                'is_default' => 'nullable|boolean'
            ]);

            if ($validator->fails()) {

                return response()->json([
                    'status' => false,
                    'message' => $validator->errors()->first()
                ], 422);
            }

            $user = auth()->user();

            if ($request->is_default) {

                CustomerAddress::where(
                    'user_id',
                    $user->id
                )->update([
                    'is_default' => false
                ]);
            }

            $address = CustomerAddress::create([
                'user_id' => $user->id,
                // 'name' => $request->name,
                // 'phone' => $request->phone,
                'address' => $request->address,
                'landmark' => $request->landmark,
                'city' => $request->city,
                'state' => $request->state,
                'country' => $request->country ?? 'India',
                'pincode' => $request->pincode,
                'latitude' => $request->latitude,
                'longitude' => $request->longitude,
                'is_default' => $request->is_default ?? false
            ]);

            return response()->json([
                'status' => true,
                'message' => 'Address saved successfully',
                'data' => $address
            ]);

        } catch (\Throwable $e) {

            return response()->json([
                'status' => false,
                'message' => 'Something went wrong',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function saveAddress(Request $request)
{
    $request->validate([
        'name' => 'required',
        'phone' => 'required',
        'address' => 'required',
        'city' => 'required',
        'state' => 'required',
        'pincode' => 'required',
        'latitude' => 'required',
        'longitude' => 'required'
    ]);

    if ($request->is_default) {
        CustomerAddress::where('user_id', auth()->id())
            ->update(['is_default' => 0]);
    }

    $address = CustomerAddress::create([
        'user_id' => auth()->id(),
        'name' => $request->name,
        'phone' => $request->phone,
        'address' => $request->address,
        'landmark' => $request->landmark,
        'city' => $request->city,
        'state' => $request->state,
        'country' => 'India',
        'pincode' => $request->pincode,
        'latitude' => $request->latitude,
        'longitude' => $request->longitude,
        'is_default' => $request->is_default ?? 0
    ]);

    return response()->json([
        'status' => true,
        'data' => $address
    ]);
}
}
