<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Setting;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class AuthController extends Controller
{
    /**
     * Get Auth Configuration
     */
    public function config()
    {
        return response()->json([
            'enable_email_login' => Setting::where('key', 'enable_email_login')->value('value') === '1',
            'enable_google_login' => Setting::where('key', 'enable_google_login')->value('value') === '1',
            'allow_registration' => true 
        ]);
    }

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

            // Check if email login is enabled
            $enabled = Setting::where('key', 'enable_email_login')->value('value');
            if ($enabled === '0') {
                return response()->json(['message' => 'Email login is currently disabled'], 403);
            }

            if (!Auth::attempt($request->only('email', 'password'))) {
                return response()->json(['message' => 'Invalid credentials'], 401);
            }

            $user = User::with('currentPlan')->where('email', $request->email)->firstOrFail();
            $token = $user->createToken('auth_token')->plainTextToken;

            return response()->json([
                'message' => 'Login successful',
                'user' => $user,
                'token' => $token,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Login failed: ' . $e->getMessage(),
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ], 500);
        }
    }

    /**
     * Register
     */
    public function register(Request $request)
    {
        // Check if email login (and thus registration) is enabled
        $enabled = Setting::where('key', 'enable_email_login')->value('value');
        if ($enabled === '0') {
            return response()->json(['message' => 'Email registration is currently disabled'], 403);
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        // Auto-assign default plan to new user
        $defaultPlan = DB::table('user_plans')
            ->where('is_default', true)
            ->where('status', 'Active')
            ->first();

        if ($defaultPlan) {
            $user->current_plan_id = $defaultPlan->id;
            $user->plan_expires_at = now()->addDays($defaultPlan->validity_days ?? 30);
            $user->membership_type = $defaultPlan->plan_name;
            $user->save();
        }

        // Load current plan relation
        $user->load('currentPlan');

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

        return response()->json([
            'message' => 'User registered successfully',
            'user' => $user,
            'token' => $token,
            'plan' => $defaultPlan ? [
                'id' => $defaultPlan->id,
                'name' => $defaultPlan->plan_name,
                'expires_at' => $user->plan_expires_at,
            ] : null,
        ], 201);
    }

    /**
     * Logout
     */
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json(['message' => 'Logged out successfully']);
    }

    /**
     * Google Login
     */
    public function googleLogin(Request $request)
    {
        $request->validate([
            'token' => 'required|string', // ID Token from Google
        ]);

        $enabled = Setting::where('key', 'enable_google_login')->value('value');
        if ($enabled === '0') {
            return response()->json(['message' => 'Google login is currently disabled'], 403);
        }

        $idToken = $request->input('token');

        // Verify Token with Google
        try {
            $response = Http::get('https://oauth2.googleapis.com/tokeninfo', [
                'id_token' => $idToken,
            ]);

            if ($response->failed()) {
                return response()->json(['message' => 'Invalid Google Token'], 401);
            }

            $googleUser = $response->json();
            
            // Expected fields: email, name, sub (google id), picture
            $email = $googleUser['email'] ?? null;
            $name = $googleUser['name'] ?? 'Google User';
            $googleId = $googleUser['sub'] ?? null;
            $avatar = $googleUser['picture'] ?? null;

            if (!$email) {
                return response()->json(['message' => 'Email not found in Google Token'], 400);
            }

            // Find or Create User
            $user = User::with('currentPlan')->where('email', $email)->first();

            if (!$user) {
                $user = User::create([
                    'name' => $name,
                    'email' => $email,
                    'password' => Hash::make(Str::random(24)), // Random password
                    'google_id' => $googleId, // Assuming you add this column or ignore it
                    'avatar' => $avatar,      // Assuming you have this column
                    'email_verified_at' => now(),
                ]);
            } else {
                // Update existing user info if needed
                $user->email_verified_at = now(); // Google emails are verified
                $user->save();
            }

            // Login
            Auth::login($user);
            $token = $user->createToken('auth_token')->plainTextToken;

            return response()->json([
                'message' => 'Google Login successful',
                'user' => $user,
                'token' => $token,
            ]);

        } catch (\Exception $e) {
            return response()->json(['message' => 'Google Login failed: ' . $e->getMessage()], 500);
        }
    }

     public function refresh(Request $request)
    {
        $user = $request->user()->load('currentPlan');
        $user->tokens()->delete();
        $token = $user->createToken('auth_token')->plainTextToken;
        
        return response()->json([
            'token' => $token,
            'user' => $user
        ]);
    }

    public function forgotPassword() {
        return response()->json(['message' => 'Not implemented yet'], 501);
    }
    
    public function resetPassword() {
        return response()->json(['message' => 'Not implemented yet'], 501);
    }

    /**
     * Change Password
     */
    public function changePassword(Request $request)
    {
        $request->validate([
            'current_password' => 'required',
            'new_password' => 'required|min:8|confirmed',
        ]);

        $user = $request->user();

        if (!Hash::check($request->current_password, $user->password)) {
            return response()->json(['message' => 'Current password does not match'], 400);
        }

        $user->password = Hash::make($request->new_password);
        $user->save();

        return response()->json(['message' => 'Password changed successfully']);
    }

    /**
     * Update Profile
     */
    public function updateProfile(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'name' => 'sometimes|string|max:255',
            'email' => 'sometimes|email|unique:users,email,' . $user->id,
            'phone_number' => 'nullable|string|max:20', // Changed from phone to phone_number matches DB
            'bio' => 'nullable|string|max:500',
            'area' => 'nullable|string|max:100',
            'city' => 'nullable|string|max:100',
            'state' => 'nullable|string|max:100',
            'country' => 'nullable|string|max:100',
            'latitude' => 'nullable|numeric',
            'longitude' => 'nullable|numeric',
        ]);

        if ($request->has('name')) $user->name = $request->name;
        if ($request->has('email')) $user->email = $request->email;
        if ($request->has('phone_number')) $user->phone_number = $request->phone_number;
        if ($request->has('bio')) $user->bio = $request->bio;
        
        // Location Updates
        if ($request->has('city')) $user->city = $request->city;
        if ($request->has('area')) $user->area = $request->area;
        if ($request->has('state')) $user->state = $request->state;
        if ($request->has('country')) $user->country = $request->country;
        if ($request->has('latitude')) $user->latitude = $request->latitude;
        if ($request->has('longitude')) $user->longitude = $request->longitude;

        $user->save();
        $user->load('currentPlan');

        return response()->json([
            'message' => 'Profile updated successfully',
            'user' => $user
        ]);
    }

    /**
     * Delete Account
     */
    public function deleteAccount(Request $request)
    {
        $user = $request->user();
        
        // Revoke tokens
        $user->tokens()->delete();
        
        // Delete user (or soft delete if model supports it)
        $user->delete();

        return response()->json(['message' => 'Account deleted successfully']);
    }

    /**
     * Register Device Token for Push Notifications
     */
    public function registerDeviceToken(Request $request)
    {
        $request->validate([
            'device_token' => 'required|string',
            'device_type' => 'nullable|string|in:android,ios,web',
        ]);

        $user = $request->user();
        $user->device_token = $request->device_token;
        $user->device_type = $request->device_type ?? 'android';
        $user->device_token_updated_at = now();
        $user->save();

        return response()->json([
            'message' => 'Device token registered successfully',
            'device_token' => $user->device_token
        ]);
    }
}
