<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    // REGISTER API
    public function register(Request $request)
    {
        $request->validate([
            'name'     => 'required|string|max:255',
            'email'    => 'nullable|email|unique:users,email',
            'mobile'   => 'nullable|digits:10|unique:users,mobile',
            'password' => 'required|min:6|confirmed',
        ]);

        // At least one: email or mobile
        if (!$request->email && !$request->mobile) {
            return response()->json([
                'status' => false,
                'message' => 'Either email or mobile is required',
            ], 422);
        }

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

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

        return response()->json([
            'status'  => true,
            'message' => 'User registered successfully',
            'token'   => $token,
            'user'    => $user,
        ], 201);
    }

    // LOGIN API (Email OR Mobile)
    public function login(Request $request)
    {
        $request->validate([
            'email_or_mobile' => 'required',
            'password'        => 'required',
        ]);

        // Detect field type
        $field = filter_var($request->email_or_mobile, FILTER_VALIDATE_EMAIL)
            ? 'email'
            : 'mobile';

        $credentials = [
            $field    => $request->email_or_mobile,
            'password' => $request->password,
        ];

        if (!Auth::attempt($credentials)) {
            return response()->json([
                'status'  => false,
                'message' => 'Invalid credentials',
            ], 401);
        }

        $user = Auth::user();
        $token = $user->createToken('API Token')->plainTextToken;

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

   
    // LOGOUT API
    public function logout(Request $request)
    {
        $request->user()->tokens()->delete();

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