<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use App\Models\User;
use App\Mail\ForgotPasswordMail;

class AuthController extends Controller
{
    // LOGIN
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
            'fcm_token' => 'nullable|string',
        ]);

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

        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid credentials',
            ], 401);
        }

        if ($user->status !== 'Active') {
            return response()->json([
                'success' => false,
                'message' => 'Account not active',
            ], 403);
        }

        $user->api_token = Str::random(80);
        $user->fcm_token = $request->fcm_token ?? $user->fcm_token;
        $user->save();

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

    // LOGOUT
    public function logout(Request $request)
    {
        $user = $request->authUser;
        $user->api_token = null;
        $user->save();

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

    // FORGOT PASSWORD
    public function forgotPassword(Request $request)
    {
        $request->validate([
            'email' => 'required|email|exists:users,email',
        ]);

        $user = User::where('email', $request->email)
            ->where('status', 'Active')
            ->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'No active account found',
            ], 404);
        }

        $newPassword = Str::random(8);
        $user->password = bcrypt($newPassword);
        $user->save();

        Mail::to($user->email)
            ->send(new ForgotPasswordMail($newPassword, $user->email, config('app.name')));

        return response()->json([
            'success' => true,
            'message' => 'New password sent to email',
        ], 200);
    }
}
