<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Wallet;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function register(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name'     => 'required|string|max:255',
            'email'    => 'required|email|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'phone'    => 'nullable|string|max:20',
            'city'     => 'nullable|string|max:100',
            'state'    => 'nullable|string|max:100',
        ]);

        $user = User::create([
            'name'     => $data['name'],
            'email'    => $data['email'],
            'password' => Hash::make($data['password']),
            'role'     => 'escort',
            'phone'    => $data['phone'] ?? null,
            'city'     => $data['city'] ?? null,
            'state'    => $data['state'] ?? null,
        ]);

        // Create wallet for escort
        Wallet::create(['user_id' => $user->id, 'balance' => 0]);

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

        return response()->json([
            'message' => 'Registration successful',
            'user'    => $user,
            'token'   => $token,
        ], 201);
    }

    public function login(Request $request): JsonResponse
    {
        $data = $request->validate([
            'email'    => 'required|email',
            'password' => 'required|string',
        ]);

        if (!Auth::attempt(['email' => $data['email'], 'password' => $data['password']])) {
            throw ValidationException::withMessages([
                'email' => ['Invalid credentials.'],
            ]);
        }

        $user = Auth::user();

        if (!$user->is_active) {
            Auth::logout();
            $reason = $user->suspension_reason ?: 'Your account has been suspended by an administrator.';
            return response()->json(['message' => 'Account Suspended: ' . $reason], 403);
        }

        // Revoke old tokens and create fresh one
        $user->tokens()->delete();
        $token = $user->createToken($user->role . '-token')->plainTextToken;

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

    public function me(Request $request): JsonResponse
    {
        $user = $request->user()->load('wallet');
        return response()->json($user);
    }

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

    /* ═══════════════════════════════════════════
     |  FORGOT PASSWORD — Send reset link email
     ═══════════════════════════════════════════ */
    public function forgotPassword(Request $request): JsonResponse
    {
        $request->validate(['email' => 'required|email']);

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

        // Always return success to avoid user enumeration
        if (!$user) {
            return response()->json(['message' => 'If that email exists, a reset link has been sent.']);
        }

        // Delete old tokens for this email
        DB::table('password_reset_tokens')->where('email', $request->email)->delete();

        // Create a new token
        $plainToken = Str::random(64);
        DB::table('password_reset_tokens')->insert([
            'email'      => $request->email,
            'token'      => Hash::make($plainToken),
            'created_at' => now(),
        ]);

        // Build reset URL pointing to the frontend page
        $frontendUrl = config('app.frontend_url', 'http://localhost:5173');
        $resetUrl    = $frontendUrl . '/reset-password.html?token=' . $plainToken . '&email=' . urlencode($request->email);

        // Send the email
        Mail::send([], [], function ($message) use ($user, $resetUrl) {
            $message->to($user->email, $user->name)
                ->subject('Reset Your Swagvio Password')
                ->html("
                    <div style='font-family:Arial,sans-serif;max-width:560px;margin:0 auto;'>
                        <div style='background:linear-gradient(135deg,#E91E63,#b80049);padding:32px;text-align:center;border-radius:12px 12px 0 0;'>
                            <h1 style='color:#fff;margin:0;font-size:28px;'>&#9829; swagvio</h1>
                            <p style='color:rgba(255,255,255,0.85);margin-top:8px;'>India's Premium Adult Classifieds</p>
                        </div>
                        <div style='background:#fff;padding:32px;border:1px solid #e8e8e8;border-top:none;border-radius:0 0 12px 12px;'>
                            <h2 style='color:#1b1c1c;margin-top:0;'>Reset Your Password</h2>
                            <p style='color:#555;line-height:1.6;'>Hi {$user->name},</p>
                            <p style='color:#555;line-height:1.6;'>We received a request to reset your password. Click the button below to choose a new one. This link is valid for <strong>60 minutes</strong>.</p>
                            <div style='text-align:center;margin:32px 0;'>
                                <a href='{$resetUrl}' style='background:#E91E63;color:#fff;padding:14px 32px;border-radius:9999px;text-decoration:none;font-weight:700;font-size:16px;display:inline-block;'>Reset My Password</a>
                            </div>
                            <p style='color:#888;font-size:13px;'>If you didn't request this, simply ignore this email. Your password will remain unchanged.</p>
                            <hr style='border:none;border-top:1px solid #eee;margin:24px 0;'>
                            <p style='color:#bbb;font-size:12px;text-align:center;'>© 2026 Swagvio India — All rights reserved</p>
                        </div>
                    </div>
                ");
        });

        return response()->json(['message' => 'If that email exists, a reset link has been sent.']);
    }

    /* ═══════════════════════════════════════════
     |  RESET PASSWORD — Validate token & update
     ═══════════════════════════════════════════ */
    public function resetPassword(Request $request): JsonResponse
    {
        $request->validate([
            'email'                 => 'required|email',
            'token'                 => 'required|string',
            'password'              => 'required|string|min:8|confirmed',
        ]);

        $record = DB::table('password_reset_tokens')
            ->where('email', $request->email)
            ->first();

        if (!$record || !Hash::check($request->token, $record->token)) {
            return response()->json(['message' => 'Invalid or expired reset link.'], 422);
        }

        // Check expiry (60 minutes)
        if (now()->diffInMinutes($record->created_at) > 60) {
            DB::table('password_reset_tokens')->where('email', $request->email)->delete();
            return response()->json(['message' => 'Reset link has expired. Please request a new one.'], 422);
        }

        $user = User::where('email', $request->email)->first();
        if (!$user) {
            return response()->json(['message' => 'User not found.'], 404);
        }

        $user->update(['password' => Hash::make($request->password)]);
        $user->tokens()->delete(); // Revoke all sessions

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

        return response()->json(['message' => 'Password reset successful! You can now log in.']);
    }

    /* ═══════════════════════════════════════════
     |  UPDATE PROFILE
     ═══════════════════════════════════════════ */
    public function updateProfile(Request $request): JsonResponse
    {
        $user = $request->user();
        $data = $request->validate([
            'name'  => 'sometimes|string|max:255',
            'phone' => 'sometimes|nullable|string|max:20',
            'city'  => 'sometimes|nullable|string|max:100',
            'state' => 'sometimes|nullable|string|max:100',
        ]);

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

