<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;
use App\Models\User;

class UserAuthController extends Controller
{

    public function refreshToken()
    {
        try {
            $newToken = JWTAuth::refresh(JWTAuth::getToken());

            return response()->json([
                'success' => true,
                'token' => $newToken,
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Could not refresh token.',
            ], 401);
        }
    }

    /**
     * User Login
     */
    public function login(Request $request)
    {
        $request->validate([
            'login_id' => 'required|string', // can be email, mobile, or customer_id
            'password' => 'required|string',
        ]);

        // Find user by email OR mobile_no OR customer_id
        $user = User::where('email', $request->login_id)
            ->orWhere('mobile_no', $request->login_id)
            ->orWhere('customer_id', $request->login_id)
            ->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found with given credentials.',
            ], 404);
        }

        // Check hashed password
        if (!Hash::check($request->password, $user->password)) {
            return response()->json([
                'success' => false,
                'message' => 'Incorrect password.',
            ], 401);
        }

        // Generate JWT token
        $token = JWTAuth::fromUser($user);

        return response()->json([
            'success' => true,
            'message' => 'Login successful.',
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'customer_id' => $user->customer_id,
                'customer_name' => $user->customer_name,
                'company_name' => $user->company_name,
                'email' => $user->email,
                'mobile_no' => $user->mobile_no,
                'address' => $user->address,
                'pincode' => $user->pincode,
            ]
        ]);
    }

    

    /**
     * User Logout
     */
    public function logout(Request $request)
    {
        try {
            JWTAuth::invalidate(JWTAuth::getToken());

            return response()->json([
                'success' => true,
                'message' => 'Logout successful.',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to logout. Token may be invalid or expired.',
            ], 500);
        }
    }
}
