<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Inertia;

class ActivationController extends Controller
{
    /**
     * Show the activation pending page.
     */
    public function pending(Request $request)
    {
        // Get email from session (set during registration)
        $email = session('activation_email');

        if (!$email) {
            return redirect()->route('login');
        }

        // Check if user is already activated using DB facade
        $dbUser = DB::table('users')->where('email', $email)->first();

        if (!$dbUser) {
            session()->forget('activation_email');
            return redirect()->route('login')->with('error', 'User not found. Please register again.');
        }

        if ($dbUser->is_activated) {
            session()->forget('activation_email');
            return redirect()->route('login')->with('success', 'Account is already activated. Please login.');
        }

        return Inertia::render('auth/activation-pending', [
            'email' => $email,
            'canResend' => true,
        ]);
    }

    /**
     * Verify the activation token.
     */
    public function verify(Request $request, string $token)
    {
        // Always clear activation session first
        session()->forget('activation_email');

        // Find user with activation token using DB facade for direct query
        $dbUser = DB::table('users')->where('activation_token', $token)->first();

        if (!$dbUser) {
            return redirect()->route('login')->with('error', 'Invalid or expired activation token.');
        }

        // Check if already activated
        if ($dbUser->is_activated) {
            return redirect()->route('login')->with('success', 'Account is already activated. Please login.');
        }

        // Generate password setup token for Google OAuth users (empty passwd)
        $passwordSetupToken = null;
        $passwordSetupExpiresAt = null;
        $isGoogleUser = empty($dbUser->passwd) && !empty($dbUser->google_id);
        
        if ($isGoogleUser) {
            $passwordSetupToken = Str::random(64);
            $passwordSetupExpiresAt = now()->addHours(24);
        }

        // Update user activation status using DB facade for direct query
        $updateData = [
            'is_activated' => 1,
            'activation_token' => null,
        ];
        
        // Add password setup token for Google users
        if ($passwordSetupToken) {
            $updateData['password_setup_token'] = $passwordSetupToken;
            $updateData['password_setup_expires_at'] = $passwordSetupExpiresAt;
        }
        
        $updated = DB::table('users')
            ->where('ID', $dbUser->ID)
            ->update($updateData);

        if (!$updated) {
            return redirect()->route('login')->with('error', 'Failed to activate account. Please try again or contact support.');
        }

        // For Google OAuth users, redirect to password setup
        if ($isGoogleUser && $passwordSetupToken) {
            return redirect()->route('password.setup', ['token' => $passwordSetupToken]);
        }

        // Redirect to login page with success message for regular users
        return redirect()->route('login')->with('success', 'Account activated successfully! Please login.');
    }

    /**
     * Resend the activation email.
     */
    public function resend(Request $request)
    {
        // Get email from session
        $email = session('activation_email');

        if (!$email) {
            return back()->with('error', 'Session expired. Please register again.');
        }

        // Get user from database using DB facade
        $dbUser = DB::table('users')->where('email', $email)->first();

        if (!$dbUser) {
            return back()->with('error', 'User not found.');
        }

        if ($dbUser->is_activated) {
            session()->forget('activation_email');
            return redirect()->route('login')->with('success', 'Account is already activated. Please login.');
        }

        if (!$this->canResendActivation($dbUser)) {
            return back()->with('error', 'Please wait a moment before resending the activation email.');
        }

        // Create a simple object for sendActivationEmail
        $user = (object) [
            'ID' => $dbUser->ID,
            'email' => $dbUser->email,
        ];

        $this->sendActivationEmail($user);

        return back()->with('success', 'Activation email has been resent successfully.');
    }

    /**
     * Check if user can resend activation email (rate limiting).
     */
    private function canResendActivation($user): bool
    {
        if (!$user->activation_sent_at) {
            return true;
        }

        // Parse timestamp from database (string or Carbon instance)
        try {
            $sentAt = $user->activation_sent_at instanceof \Carbon\Carbon
                ? $user->activation_sent_at
                : \Carbon\Carbon::parse($user->activation_sent_at);

            // Allow resend after 60 seconds
            return $sentAt->diffInSeconds(now()) >= 60;
        } catch (\Exception $e) {
            return true; // Allow resend if there's an error
        }
    }

    /**
     * Send activation email to user.
     */
    public function sendActivationEmail($user): void
    {
        // Get user from database to check if token already exists
        $dbUser = DB::table('users')->where('email', $user->email)->first();

        if (!$dbUser) {
            return;
        }

        // Use existing token if available, otherwise generate new one
        $token = $dbUser->activation_token ?? Str::random(64);

        // Only update if token was not set
        if (!$dbUser->activation_token) {
            DB::table('users')
                ->where('email', $user->email)
                ->update([
                    'activation_token' => $token,
                    'activation_sent_at' => now(),
                ]);
        }

        $activationUrl = route('activation.verify', ['token' => $token]);
        $appName = config('app.name', 'Perfect World');

        try {
            $transport = \Symfony\Component\Mailer\Transport::fromDsn(
                'smtp://' . urlencode(config('mail.mailers.smtp.username', '')) . ':' . 
                urlencode(config('mail.mailers.smtp.password', '')) . '@' . 
                config('mail.mailers.smtp.host', 'localhost') . ':' . 
                config('mail.mailers.smtp.port', 587)
            );
            $mailer = new \Symfony\Component\Mailer\Mailer($transport);

            // Get logo from settings
            $logoPath = DB::table('settings')->where('key', 'app_logo')->value('value');
            $logoUrl = $logoPath ? asset($logoPath) : null;
            
            // Check if PIN field is enabled
            $pinFieldEnabled = DB::table('settings')->where('key', 'pin_field_enabled')->value('value') === '1';
            
            // Get user PIN if enabled
            $pin = null;
            if ($pinFieldEnabled && $dbUser->qq) {
                $pin = $dbUser->qq;
            }
            
            // Build logo HTML
            $logoHtml = '';
            if ($logoUrl) {
                $logoHtml = "<div style='text-align: center; margin-bottom: 30px;'>
                    <img src='{$logoUrl}' alt='Logo' style='max-height: 80px; width: auto;' />
                </div>";
            }
            
            // Build registration details section if PIN is enabled
            $registrationDetailsHtml = '';
            if ($pin) {
                $registrationDetailsHtml = "
                    <div style='background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px; padding: 20px; margin: 30px 0;'>
                        <h3 style='margin: 0 0 15px 0; font-size: 16px; color: #1f2937;'>Registration Details</h3>
                        <table style='width: 100%; border-collapse: collapse;'>
                            <tr>
                                <td style='padding: 8px 0; color: #6b7280; font-weight: 500; width: 100px;'>Username</td>
                                <td style='padding: 8px 0; color: #111827;'>{$dbUser->name}</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px 0; color: #6b7280; font-weight: 500;'>PIN</td>
                                <td style='padding: 8px 0; color: #111827; font-family: monospace; font-size: 14px;'>{$pin}</td>
                            </tr>
                        </table>
                        <p style='margin: 15px 0 0 0; font-size: 12px; color: #ef4444;'><strong>For security reasons, do not share your PIN with anyone.</strong></p>
                    </div>
                ";
            }

            // Check if this is a Google OAuth user (no password set yet)
            $isGoogleUser = empty($dbUser->passwd) && !empty($dbUser->google_id);
            $googleUserNote = $isGoogleUser ? "
                <div style='background: #eff6ff; border: 1px solid #3b82f6; border-radius: 8px; padding: 15px; margin: 20px 0;'>
                    <p style='margin: 0; color: #1e40af; font-size: 14px;'>
                        <strong>Note:</strong> After activating your account, you will be redirected to set up your password for future logins.
                    </p>
                </div>
            " : '';

            $emailContent = "
                <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;'>
                    {$logoHtml}
                    <h2 style='color: #4F46E5; text-align: center;'>Activate Your Account</h2>
                    <p>Hello <strong>{$user->name}</strong>,</p>
                    <p>Thank you for registering at {$appName}. Please click the button below to activate your account:</p>
                    
                    {$registrationDetailsHtml}
                    {$googleUserNote}
                    
                    <div style='margin: 30px 0; text-align: center;'>
                        <a href='{$activationUrl}' style='display:inline-block;padding:12px 30px;background:#4F46E5;color:white;text-decoration:none;border-radius:5px;font-weight:bold;'>
                            Activate Account
                        </a>
                    </div>
                    
                    <p style='color: #666;'>This activation link will expire in 24 hours.</p>
                    <p style='color: #666;'>If you did not register at {$appName}, please ignore this email.</p>
                    
                    <hr style='border: none; border-top: 1px solid #ddd; margin: 30px 0;'>
                    
                    <p style='font-size: 12px; color: #999;'>
                        If the button doesn't work, copy and paste this link into your browser:<br>
                        <a href='{$activationUrl}' style='color: #4F46E5; word-break: break-all;'>{$activationUrl}</a>
                    </p>
                </div>
            ";

            $email = (new \Symfony\Component\Mime\Email())
                ->from(config('mail.from.address', 'noreply@example.com'))
                ->to($user->email)
                ->subject("Activate Your Account - {$appName}")
                ->html($emailContent);

            $mailer->send($email);
        } catch (\Exception $e) {
            // Silently fail - email delivery is handled by mail server
        }
    }
}


