<?php

namespace App\Http\Controllers\Api;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\LoginRequest;
use App\Http\Requests\ChangePasswordRequest;
use App\Services\AuthService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    protected $authService;

    public function __construct(AuthService $authService)
    {
        $this->authService=$authService;
    }

    public function login(LoginRequest $request)
    {
        $login=$this->authService->login($request);

        if(!$login['success'])
        {
            return ApiResponse::error($login['message']);
        }

        return ApiResponse::success(
            'Login Successful',
            [
                'token'=>$login['token'],
                'user'=>$login['user']
            ]
        );
    }

    public function logout(Request $request)
    {
  
        $request->user()->currentAccessToken()->delete();
    
        return response()->json([
            'success' => true,
            'message' => 'Logged out successfully.'
        ]);
      
    }

   public function changePassword(ChangePasswordRequest $request)
    {
        $user = $request->user();
    
        if (!Hash::check($request->old_password, $user->password)) {
            return response()->json([
                'success' => false,
                'message' => 'Old password is incorrect.'
            ], 400);
        }
    
        $user->update([
            'password' => Hash::make($request->password)
        ]);
    
        return response()->json([
            'success' => true,
            'message' => 'Password changed successfully.'
        ]);
    }
    
    public function forgotPassword(Request $request)
    {
        $request->validate([
            'email' => 'required|email'
        ]);
    
        $status = Password::sendResetLink(
            $request->only('email')
        );
    
        if ($status === Password::RESET_LINK_SENT) {
    
            return response()->json([
                'success' => true,
                'message' => __($status)
            ]);
        }
    
        return response()->json([
            'success' => false,
            'message' => __($status)
        ], 400);
    }

}