<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserAuth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;
use App\Traits\ApiResponseTrait;
use Illuminate\Support\Facades\Password;
use App\Mail\ForgotPasswordMail;
use Illuminate\Support\Facades\Mail;

class UserAuthController extends Controller
{
    use ApiResponseTrait;

    /**
     * REGISTER USER
     */
    public function register(Request $request)
    {
        $data = $request->validate([
            'first_name' => 'required|string',
            'last_name'  => 'required|string',
            'email'      => 'required|email|unique:user_auth,email',
            'password'   => 'required|min:6|confirmed',
            'role_id'    => 'nullable|exists:user_role_master,id',
        ]);

        // Create login record
        $auth = UserAuth::create([
            'email'    => $data['email'],
            'username' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        // Create profile record
        $user = User::create([
            'user_auth_id' => $auth->id,
            'first_name'   => $data['first_name'],
            'last_name'    => $data['last_name'],
            'email'        => $data['email'],
            'role_id'      => $data['role_id'],
        ]);

        return $this->successResponse('User registered successfully', $user, 201);
    }

    /**
     * LOGIN
     */
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email'    => 'required|email',
            'password' => 'required',
        ]);

        $auth = UserAuth::where('username', $credentials['email'])->first();

        if (!$auth || !Hash::check($credentials['password'], $auth->password)) {
            return $this->errorResponse('Invalid credentials', null, 401);
        }

        $user = User::where('user_auth_id', $auth->id)
         ->with(['office' => fn($q) => $q->where('is_deleted', 0)])
         ->with(['role' => fn($q) => $q->where('is_deleted', 0)])
         ->first();

        if (!$user || !$user->is_active || $user->is_deleted) {
            return $this->errorResponse(
                'Account access denied. Please contact the system administrator.',
                null,
                401
            );
        }

        $token = JWTAuth::fromUser($user);

        $auth->update(['auth_token' => $token]);

        return $this->successResponse('Login successful', [
            'access_token' => $token,
            'token_type'   => 'bearer',
            'expires_in'   => JWTAuth::factory()->getTTL() * 60,
            'user'         => $user
        ]);
    }

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

        $auth = UserAuth::where('email', $request->email)->first();
        if (!$auth) {
            return $this->errorResponse('Email not found', null, 404);
        }

        $token = Str::random(64);
        $auth->update([
            'reset_token'      => $token,
            'token_expires_on' => now()->addMinutes(15)
        ]);

         // Send email
        Mail::to($auth->email)->send(new ForgotPasswordMail($token, $auth->email));

        return $this->successResponse('Reset token generated');
    }

    /**
     * RESET PASSWORD
     */
    public function resetPassword(Request $request)
    {
        $data = $request->validate([
            'reset_token' => 'required',
            'password'    => 'required|min:6|confirmed'
        ]);

        $auth = UserAuth::where('reset_token', $data['reset_token'])->first();

        if (!$auth || now()->greaterThan($auth->token_expires_on)) {
            return $this->errorResponse('Invalid or expired reset token', null, 400);
        }

        $auth->update([
            'password' => Hash::make($data['password']),
            'reset_token' => null
        ]);

        return $this->successResponse('Password reset successful');
    }

    /**
     * PROFILE DETAILS
     */
    public function me()
    {
        try {
            $user = JWTAuth::parseToken()->authenticate();
            return $this->successResponse('User details fetched successfully', $user);
        } catch (\Exception $e) {
            return $this->errorResponse('Token invalid or expired', null, 401);
        }
    }



    /**
     * LOGOUT
     */
    public function logout()
    {
        try {
            JWTAuth::invalidate(JWTAuth::getToken());
            return $this->successResponse('Logged out successfully');
        } catch (\Exception $e) {
            return $this->errorResponse('Unable to logout', $e->getMessage(), 500);
        }
    }

    public function setupPassword(Request $request)
    {
        $data = $request->validate([
            'email' => 'required|email|exists:user_auth,email',
            'token' => 'required|string',
            'password' => 'required|min:6|confirmed',
        ]);

        // Find user auth record
        $userAuth = UserAuth::where('email', $data['email'])->first();

        if (!$userAuth) {
            return $this->errorResponse('User not found', null, 404);
        }

        // Verify token
        if (!Password::tokenExists($userAuth, $data['token'])) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid or expired token',
                'data' => null
            ], 400);
        }

        // Update password
        $userAuth->password = Hash::make($data['password']);
        $userAuth->save();

        // Delete token
        Password::deleteToken($userAuth);

        return response()->json([
            'success' => true,
            'message' => 'Password set successfully. You can now log in.',
            'data' => null
        ], 200);
    }

}
