<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Role;
use App\Events\NewUserRegistered;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use App\Mail\PasswordResetMail;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Support\Facades\DB;



class AuthController extends Controller
{
    public function register(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'email' => 'required|email|unique:users,email',
                'password' => 'required|string|min:8|confirmed',
                'role_name' => 'required|in:parent,babysitter',
                'first_name' => 'required|string|max:100',
                'last_name' => 'required|string|max:100',
                'phone_number' => 'nullable|string|max:20|unique:users,phone_number',
                'date_of_birth' => 'nullable|date|before:today',
                'gender' => 'nullable|in:male,female,other,prefer_not_to_say',
                'profile_picture' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:5120'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $validated = $validator->validated();

            // Get role ID based on role name
            $role = Role::where('role_name', $validated['role_name'])->first();

            if (!$role) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid role selected'
                ], 422);
            }

            // Handle profile picture upload
            $profilePictureUrl = null;
            if ($request->hasFile('profile_picture')) {
                $file = $request->file('profile_picture');
                $fileName = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
                $file->move(public_path('storage/profile-pictures'), $fileName);
                $profilePictureUrl = 'profile-pictures/' . $fileName;
            }

            // Create user
            $user = User::create([
                'email' => $validated['email'],
                'password_hash' => Hash::make($validated['password']),
                'role_id' => $role->role_id,
                'first_name' => $validated['first_name'],
                'last_name' => $validated['last_name'],
                'phone_number' => $validated['phone_number'] ?? null,
                'profile_picture_url' => $profilePictureUrl,
                'date_of_birth' => $validated['date_of_birth'] ?? null,
                'gender' => $validated['gender'] ?? null,
                'is_active' => true,
            ]);

            // ✅ CREATE TOKEN
            $token = $user->createToken('auth-token')->plainTextToken;

            // ✅ DIRECT PUSHER USE KARO - EVENT ki jagah
            $userType = $validated['role_name'] === 'babysitter' ? 'Babysitter' : 'Parent';

            $pusher = new \Pusher\Pusher(
                config('broadcasting.connections.pusher.key'),
                config('broadcasting.connections.pusher.secret'),
                config('broadcasting.connections.pusher.app_id'),
                [
                    'cluster' => config('broadcasting.connections.pusher.options.cluster'),
                    'useTLS' => true
                ]
            );

            $data = [
                'user_id' => $user->user_id,
                'user_name' => $user->first_name . ' ' . $user->last_name,
                'user_email' => $user->email,
                'user_type' => $userType,
                'message' => 'New ' . $userType . ' registered: ' . $user->first_name . ' ' . $user->last_name,
                'profile_picture' => $user->profile_picture_url,
                'registration_date' => $user->created_at->toDateTimeString(),
                'timestamp' => now()->toDateTimeString(),
                'icon' => '👤'
            ];



            // Trigger the event
            $result = $pusher->trigger('public-notifications', 'user.registered', $data);

            

            $user->load('role');

            // Full public URL provide karein
            if ($user->profile_picture_url) {
                $user->profile_picture_url = url('storage/' . $user->profile_picture_url);
            }

            return response()->json([
                'success' => true,
                'message' => 'User registered successfully',
                'data' => [
                    'user' => $user,
                    'access_token' => $token,
                    'token_type' => 'Bearer',
                    'real_time_notification_sent' => true,
                    'pusher_broadcast_result' => $result
                ]
            ], 201);
        } catch (\Exception $e) {


            return response()->json([
                'success' => false,
                'message' => 'Registration failed',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

   /**
 * Request password reset
 */
public function forgotPassword(Request $request): JsonResponse
{
    try {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|exists:users,email'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

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

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User with this email does not exist'
            ], 404);
        }

        // Generate reset token
        $token = Str::random(60);

        // Store token in password_reset_tokens table
        DB::table('password_reset_tokens')->updateOrInsert(
            ['email' => $email],
            [
                'token' => Hash::make($token),
                'created_at' => now()
            ]
        );

        // ✅ Direct website URL with token and email
        $websiteUrl = 'http://localhost:5173/reset-password?token=' . $token . '&email=' . urlencode($email);

        // ✅ Send simple email with direct link
        Mail::to($user->email)->send(new PasswordResetMail($websiteUrl, $user));

        Log::info('Password reset link sent via email', [
            'email' => $email,
            'token' => $token,
            'website_url' => $websiteUrl
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Password reset link sent to your email',
            'data' => [
                'email' => $email
            ]
        ]);
    } catch (\Exception $e) {
        Log::error('Failed to process password reset request: ' . $e->getMessage());
        return response()->json([
            'success' => false,
            'message' => 'Failed to process password reset request',
            'error' => config('app.debug') ? $e->getMessage() : null
        ], 500);
    }
}

    /**
     * Reset password with token
     */
    public function resetPassword(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'email' => 'required|email|exists:users,email',
                'token' => 'required|string',
                'password' => 'required|string|min:8|confirmed'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

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

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

            // Check if token exists and is valid
            $tokenData = DB::table('password_reset_tokens')
                ->where('email', $request->email)
                ->first();

            if (!$tokenData) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid or expired reset token'
                ], 422);
            }

            // Check if token is valid (within 1 hour) and matches
            $tokenExpired = now()->subHour()->gt($tokenData->created_at);
            $tokenValid = Hash::check($request->token, $tokenData->token);

            if (!$tokenValid || $tokenExpired) {
                // Delete invalid token
                DB::table('password_reset_tokens')->where('email', $request->email)->delete();

                return response()->json([
                    'success' => false,
                    'message' => 'Invalid or expired reset token'
                ], 422);
            }

            // Update password
            $user->update([
                'password_hash' => Hash::make($request->password)
            ]);

            // Delete used token
            DB::table('password_reset_tokens')->where('email', $request->email)->delete();

            Log::info('Password reset successfully', [
                'user_id' => $user->user_id,
                'email' => $user->email
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Password reset successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to reset password: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to reset password',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Verify reset token (for frontend to check if token is valid before showing reset form)
     */
    public function verifyResetToken(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'email' => 'required|email|exists:users,email',
                'token' => 'required|string'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

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

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

            // Check if token exists and is valid
            $tokenData = DB::table('password_reset_tokens')
                ->where('email', $request->email)
                ->first();

            if (!$tokenData) {
                return response()->json([
                    'success' => true,
                    'data' => [
                        'is_valid' => false,
                        'email' => $user->email
                    ]
                ]);
            }

            // Check if token is valid (within 1 hour) and matches
            $tokenExpired = now()->subHour()->gt($tokenData->created_at);
            $tokenValid = Hash::check($request->token, $tokenData->token);

            $isValid = $tokenValid && !$tokenExpired;

            // If token is invalid, delete it
            if (!$isValid) {
                DB::table('password_reset_tokens')->where('email', $request->email)->delete();
            }

            return response()->json([
                'success' => true,
                'data' => [
                    'is_valid' => $isValid,
                    'email' => $user->email
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to verify reset token: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to verify reset token',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }
    /**
     * Register Super Admin with Profile Picture
     */
    public function registerSuperAdmin(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'email' => 'required|email|unique:users,email',
                'password' => 'required|string|min:8|confirmed',
                'first_name' => 'required|string|max:100',
                'last_name' => 'required|string|max:100',
                'phone_number' => 'nullable|string|max:20|unique:users,phone_number',
                'profile_picture' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:5120' // 5MB max
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            // SUPER ADMIN ROLE ID = 1 (Fixed)
            $superAdminRoleId = 1;

            // Check if super admin role exists
            $superAdminRole = Role::find($superAdminRoleId);
            if (!$superAdminRole || $superAdminRole->role_name !== 'super_admin') {
                return response()->json([
                    'success' => false,
                    'message' => 'Super admin role not found in system'
                ], 500);
            }

            // STRICT CHECK: Super admin already exists or not
            $existingSuperAdmin = User::where('role_id', $superAdminRoleId)->first();
            if ($existingSuperAdmin) {
                return response()->json([
                    'success' => false,
                    'message' => 'Super admin already exists in system. Cannot create another super admin.'
                ], 422);
            }

            $validated = $validator->validated();

            // Handle profile picture upload - PUBLIC/STORAGE mein save karein
            $profilePictureUrl = null;
            if ($request->hasFile('profile_picture')) {
                $file = $request->file('profile_picture');
                $fileName = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();

                // ✅ PUBLIC/STORAGE/PROFILE-PICTURES mein save karein
                $file->move(public_path('storage/profile-pictures'), $fileName);
                $profilePictureUrl = 'profile-pictures/' . $fileName;
            }

            // Create super admin user
            $user = User::create([
                'email' => $validated['email'],
                'password_hash' => Hash::make($validated['password']),
                'role_id' => $superAdminRoleId,
                'first_name' => $validated['first_name'],
                'last_name' => $validated['last_name'],
                'phone_number' => $validated['phone_number'] ?? null,
                'profile_picture_url' => $profilePictureUrl,
                'is_active' => true,
                'is_email_verified' => true,
                'is_profile_completed' => true,
            ]);

            // Create authentication token
            $token = $user->createToken('auth-token')->plainTextToken;

            $user->load('role');

            // ✅ Full public URL provide karein
            if ($user->profile_picture_url) {
                $user->profile_picture_url = url('storage/' . $user->profile_picture_url);
            }

            return response()->json([
                'success' => true,
                'message' => 'Super Admin registered successfully',
                'data' => [
                    'user' => $user,
                    'access_token' => $token,
                    'token_type' => 'Bearer'
                ]
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Super Admin registration failed',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Check if Super Admin exists
     */
    public function checkSuperAdmin(): JsonResponse
    {
        try {
            $superAdminRoleId = 1;
            $superAdminExists = User::where('role_id', $superAdminRoleId)->exists();

            return response()->json([
                'success' => true,
                'data' => [
                    'super_admin_exists' => $superAdminExists,
                    'message' => $superAdminExists ?
                        'Super admin already exists in system' :
                        'No super admin found. You can register one.'
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to check super admin status',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Login user with email or mobile number
     */
    public function login(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'login' => 'required|string', // Can be email or phone_number
                'password' => 'required|string'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $login = $request->login;
            $password = $request->password;

            // Determine if login is email or phone number
            $isEmail = filter_var($login, FILTER_VALIDATE_EMAIL);

            if ($isEmail) {
                // Login with email
                $user = User::where('email', $login)->first();
            } else {
                // Login with phone number
                $user = User::where('phone_number', $login)->first();
            }

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

            if (!$user->is_active) {
                return response()->json([
                    'success' => false,
                    'message' => 'Your account has been deactivated. Please contact administrator.'
                ], 403);
            }

            // Update last login
            $user->update(['last_login_at' => now()]);

            // Load role and role-specific data based on role_id
            $user->load([
                'role',
                'babysitterProfile',
                'parentProfile',
                'addresses',
                'userLanguages'
            ]);

            // Get role-specific data
            $roleSpecificData = null;

            if ($user->role_id == 2 && $user->babysitterProfile) { // Babysitter
                $roleSpecificData = $user->babysitterProfile;
            } elseif ($user->role_id == 3 && $user->parentProfile) { // Parent
                $roleSpecificData = $user->parentProfile;
            }

            // Create new token
            $token = $user->createToken('auth-token')->plainTextToken;

            // ✅ Full public URL provide karein profile picture ke liye
            if ($user->profile_picture_url) {
                $user->profile_picture_url = url('storage/' . $user->profile_picture_url);
            }

            return response()->json([
                'success' => true,
                'message' => 'Login successful',
                'data' => [
                    'user' => $user,
                    'role_specific_data' => $roleSpecificData,
                    'access_token' => $token,
                    'token_type' => 'Bearer',
                    'login_method' => $isEmail ? 'email' : 'mobile'
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Login failed',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }
    /**
     * Logout user
     */
    public function logout(Request $request): JsonResponse
    {
        try {
            $request->user()->currentAccessToken()->delete();

            return response()->json([
                'success' => true,
                'message' => 'Logout successful'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Logout failed',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get authenticated user profile
     */
    public function me(Request $request): JsonResponse
    {
        try {
            $user = $request->user()->load([
                'addresses',
                'userLanguages',
                'babysitterProfile',
                'parentProfile'
            ]);

            return response()->json([
                'success' => true,
                'data' => $user
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch user profile',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Refresh token
     */
    public function refresh(Request $request): JsonResponse
    {
        try {
            $user = $request->user();

            $request->user()->currentAccessToken()->delete();

            $token = $user->createToken('auth-token')->plainTextToken;

            return response()->json([
                'success' => true,
                'message' => 'Token refreshed successfully',
                'data' => [
                    'access_token' => $token,
                    'token_type' => 'Bearer'
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Token refresh failed',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }
}
