<?php

namespace App\Http\Controllers\APIS\CustomerApi;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Hash;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Http;
class AuthController extends Controller
{


     /**
     * Created By : sayali parab
     * Created at : 11 March 2025
     * Use : To login user.
     */

    public function login(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'email' => 'required|email',
                'password' => 'required',
            ]);
            if ($validator->fails()) {
                $validationErrors = $validator->errors()->all();
                Log::error("Login validation error: " . implode(", ", $validationErrors));
                return jsonResponseWithErrorMessageApi($validationErrors, 403);
            }
            $isExistEmail = User::where('email', $request->email)->first();

            if ($isExistEmail == null) {
                return jsonResponseWithErrorMessageApi(__('auth.incorrect_email'), 403);
            }
            if ($isExistEmail && !(Hash::check($request->password, $isExistEmail->password))) {
                Log::error('Entered Password is wrong for ' . $request->email);
                return jsonResponseWithErrorMessageApi(__('auth.incorrect_password'), 403);
            }
            $credentials = [
                'email' => $request->email,
                'password' => $request->password,
            ];

            if (Auth::attempt($credentials)) {
                $user = Auth::user();
                $token = JWTAuth::fromUser($user);

                // Return success response with JWT token
                $response = [
                    'access_token' => $token,
                    'user' => $user,
                ];

                return jsonResponseWithSuccessMessage(__('auth.data_fetched_successfully'), $response, 2);
            }
        }
        catch (QueryException $e) {
            Log::error('Customer Login Failed: ' . $e->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.authentication_failed'), 401);
        }
    }
    // public function login()
    // {
    //     // Define the API endpoint
    //     $url = 'http://65.0.131.117:8080/api/auth/login';

    //     // Define the payload
    //     $payload = [
    //         'username' => 'veoliauser@mail.com',
    //         'password' => 'veolia123',
    //     ];

    //     // Make the POST request
    //     $response = Http::withHeaders([
    //         'Content-Type' => 'application/json',
    //     ])->post($url, $payload);

    //     // Return the response
    //     return response()->json($response->json(), $response->status());
    // }


}

