<?php

use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\Auth\HomeController;
use App\Http\Controllers\Admin\AdminDashboardController;
use App\Http\Controllers\Admin\UserController;
use App\Http\Controllers\Admin\CallController;
use App\Http\Controllers\Admin\FinanceController;
use App\Http\Controllers\Admin\AnalyticsController;
use App\Http\Controllers\Admin\SettingsController;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Mail;
use Illuminate\Http\Request;
use App\Http\Controllers\WalletController;
use App\Http\Controllers\Webhook\RazorpayWebhookController;
use App\Http\Controllers\FrontUser\DashboardController as FrontUserDashboardController;
use App\Http\Controllers\FrontUser\CallsController as FrontUserCallsController;
use App\Http\Controllers\FrontUser\WalletController as FrontUserWalletController;
use App\Http\Controllers\FrontUser\ReportsController as FrontUserReportsController;
use App\Http\Controllers\FrontUser\ProfileController as FrontUserProfileController;
use App\Http\Controllers\FrontUser\UserSettingsController as FrontUserUserSettingsController;
use App\Http\Controllers\FrontUser\SearchController as FrontUserSearchController;
use App\Http\Controllers\FrontUser\AIDashboardController;
use App\Http\Controllers\AI\AIController;
use App\Http\Controllers\AI\AIAPIController;

// Home routes -> redirect to user dashboard (protected by auth)
Route::middleware(['auth'])->group(function () {
    Route::get('/home', function () { return redirect()->route('user.dashboard'); })->name('home');
    Route::get('/dashboard', function () { return redirect()->route('user.dashboard'); })->name('dashboard');
});

// Authentication Routes
Route::get('/login', [LoginController::class, 'showLoginForm'])->name('login');
Route::post('/login', [LoginController::class, 'login']);
Route::post('/logout', [LoginController::class, 'logout'])->name('logout');

// Password Reset Routes
Route::get('/forgot-password', [LoginController::class, 'showForgotPasswordForm'])->name('password.request');
Route::post('/forgot-password', [LoginController::class, 'sendResetLinkEmail'])->name('password.email');
Route::get('/reset-password/{token}', [LoginController::class, 'showResetForm'])->name('password.reset');
Route::post('/reset-password', [LoginController::class, 'reset'])->name('password.update');

// Registration disabled (UI shows message)
Route::get('/register', [RegisterController::class, 'showRegistrationForm'])->name('register');
// Route::post('/register', [RegisterController::class, 'register']);

// Admin Routes - All protected by auth middleware
Route::prefix('admin')->name('admin.')->middleware(['auth', 'admin'])->group(function () {
    Route::get('/dashboard', [AdminDashboardController::class, 'index'])->name('dashboard');
    
    // User Management - Consolidated into one group
    Route::prefix('users')->name('users.')->group(function () {
        Route::get('/', [UserController::class, 'index'])->name('index');
        Route::get('/create', [UserController::class, 'create'])->name('create');
        Route::post('/', [UserController::class, 'store'])->name('store');
        Route::get('/{user}', [UserController::class, 'show'])->name('show');
        Route::get('/{user}/edit', [UserController::class, 'edit'])->name('edit');
        Route::put('/{user}', [UserController::class, 'update'])->name('update');
        Route::delete('/{user}', [UserController::class, 'destroy'])->name('destroy');
        Route::post('/{user}/wallet/credit', [UserController::class, 'creditWallet'])->name('wallet.credit');
        Route::put('/{user}/license', [UserController::class, 'updateLicense'])->name('license.update');
    });
    
    // Call Management
    Route::get('/calls', [CallController::class, 'index'])->name('calls.index');
    
    // Financial Reports
    Route::get('/finance', [FinanceController::class, 'index'])->name('finance.index');
    
    // Analytics
    Route::get('/analytics', [AnalyticsController::class, 'index'])->name('analytics.index');
    
    // System Settings
    Route::get('/settings', [SettingsController::class, 'index'])->name('settings.index');
});

// Redirect root to home
Route::get('/', function () {
    return redirect('/home');
});

// Test email routes (remove in production)
Route::get('/test-email-page', function () {
    return view('test-email');
});

Route::get('/test-email', function () {
    try {
        \App\Helpers\EmailConfig::configureMail();
        
        $user = (object) [
            'name' => 'Test User',
            'email' => 'dizaartsystem@gmail.com',
            'id' => 999
        ];
        
        Mail::to('dizaartsystem@gmail.com')->send(new \App\Mail\UserWelcomeMail($user, 'testpassword123'));
        
        return '<div style="font-family: Arial; padding: 20px; text-align: center;">
                    <h2 style="color: green;">✅ Email Sent Successfully!</h2>
                    <p>Test email sent to dizaartsystem@gmail.com</p>
                    <p>Check your inbox (and spam folder) for the email.</p>
                    <a href="/test-email-page" style="color: #4f46e5;">← Back to Test Page</a>
                </div>';
    } catch (\Exception $e) {
        return '<div style="font-family: Arial; padding: 20px; text-align: center;">
                    <h2 style="color: red;">❌ Email Failed</h2>
                    <p>Error: ' . $e->getMessage() . '</p>
                    <a href="/test-email-page" style="color: #4f46e5;">← Back to Test Page</a>
                </div>';
    }
});

Route::get('/test-welcome-email', function () {
    try {
        \App\Helpers\EmailConfig::configureMail();
        
        $user = (object) [
            'name' => 'John Doe',
            'email' => 'dizaartsystem@gmail.com',
            'id' => 123,
            'company_name' => 'Test Company',
            'contact_number' => '+1234567890'
        ];
        
        Mail::to('dizaartsystem@gmail.com')->send(new \App\Mail\UserWelcomeMail($user, 'Welcome123!'));
        
        return '<div style="font-family: Arial; padding: 20px; text-align: center;">
                    <h2 style="color: green;">✅ Welcome Email Sent Successfully!</h2>
                    <p>Welcome email sent to dizaartsystem@gmail.com</p>
                    <p>Check your inbox (and spam folder) for the email.</p>
                    <a href="/test-email-page" style="color: #4f46e5;">← Back to Test Page</a>
                </div>';
    } catch (\Exception $e) {
        return '<div style="font-family: Arial; padding: 20px; text-align: center;">
                    <h2 style="color: red;">❌ Welcome Email Failed</h2>
                    <p>Error: ' . $e->getMessage() . '</p>
                    <a href="/test-email-page" style="color: #4f46e5;">← Back to Test Page</a>
                </div>';
    }
});

// AI Test Route with message parameter (for XAMPP testing)
Route::get('/ai-test-simple', function (Request $request) {
    try {
        $phi3 = new \App\Services\AI\Phi3Service();
        
        if ($request->has('message')) {
            // Test with a message
            $result = $phi3->generateResponse($request->get('message'), [], 'general');
            return response()->json([
                'success' => true,
                'message' => 'AI response generated',
                'details' => [
                    'response' => $result['response'],
                    'model' => $result['model'],
                    'tokens_used' => $result['tokens_used'] ?? 0
                ]
            ]);
        } else {
            // Test connection
            $result = $phi3->testConnection();
            return response()->json([
                'success' => $result['success'],
                'message' => $result['message'],
                'details' => $result['details'] ?? null
            ]);
        }
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage()
        ]);
    }
});

// Test route for Twilio webhook (both GET and POST)
Route::get('/twilio-test', [\App\Http\Controllers\TwilioPhoneController::class, 'handleIncomingCall'])->withoutMiddleware(['csrf', 'web']);
Route::post('/twilio-test', [\App\Http\Controllers\TwilioPhoneController::class, 'handleIncomingCall'])->withoutMiddleware(['csrf', 'web']);

// Simple test webhook that returns XML directly
Route::get('/webhook-test', function() {
    return response('<?xml version="1.0" encoding="UTF-8"?><Response><Say>Hello from webhook test!</Say></Response>', 200)->header('Content-Type', 'text/xml');
})->withoutMiddleware(['csrf', 'web']);

Route::post('/webhook-test', function() {
    return response('<?xml version="1.0" encoding="UTF-8"?><Response><Say>Hello from webhook test POST!</Say></Response>', 200)->header('Content-Type', 'text/xml');
})->withoutMiddleware(['csrf', 'web']);

// Test Gemini integration
Route::get('/test-gemini', function() {
    try {
        $geminiService = new \App\Services\AI\GeminiService();
        $result = $geminiService->testConnection();
        
        return response()->json([
            'success' => true,
            'message' => 'Gemini test completed',
            'result' => $result
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage()
        ], 500);
    }
});

// Real-time streaming AI endpoint
Route::post('/ai-stream', function(Request $request) {
    try {
        $message = $request->input('message');
        $context = $request->input('context', []);
        $conversationType = $request->input('type', 'general');
        
        if (!$message) {
            return response()->json(['success' => false, 'error' => 'Message required'], 400);
        }
        
        $aiService = new \App\Services\AI\Phi3Service();
        $response = $aiService->generateResponse($message, $context, $conversationType);
        
        if ($response['success']) {
            return response()->json([
                'success' => true,
                'response' => $response['response'],
                'model' => $response['model'] ?? 'gemini-1.5-flash',
                'usage' => $response['usage'] ?? []
            ]);
        }
        
        return response()->json([
            'success' => false,
            'error' => $response['error'] ?? 'AI service failed'
        ], 500);
        
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => 'Server error: ' . $e->getMessage()
        ], 500);
    }
})->withoutMiddleware(['csrf']);

// Simple AI test without CSRF
Route::get('/ai-instant-test', function(Request $request) {
    try {
        $message = $request->input('message', 'Hello');
        
        $aiService = new \App\Services\AI\Phi3Service();
        $response = $aiService->generateResponse($message, [], 'general');
        
        if ($response['success']) {
            return response()->json([
                'success' => true,
                'response' => $response['response'],
                'model' => $response['model'] ?? 'gemini-1.5-flash'
            ]);
        }
        
        return response()->json([
            'success' => false,
            'error' => $response['error'] ?? 'AI service failed'
        ], 500);
        
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => 'Server error: ' . $e->getMessage()
        ], 500);
    }
});

// Real-time streaming AI endpoint
Route::get('/ai-stream-words', function(Request $request) {
    try {
        $message = $request->input('message', 'Hello');
        
        $aiService = new \App\Services\AI\Phi3Service();
        $response = $aiService->generateResponse($message, [], 'general');
        
        if ($response['success']) {
            $fullText = $response['response'];
            $words = explode(' ', $fullText);
            
            // Return words array for streaming
            return response()->json([
                'success' => true,
                'words' => $words,
                'full_text' => $fullText,
                'model' => $response['model'] ?? 'gemini-1.5-flash'
            ]);
        }
        
        return response()->json([
            'success' => false,
            'error' => $response['error'] ?? 'AI service failed'
        ], 500);
        
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => 'Server error: ' . $e->getMessage()
        ], 500);
    }
});

// Test route for making calls (no auth required for testing)
Route::post('/test-make-call', function (Request $request) {
    try {
        $to = $request->input('to');
        $message = $request->input('message', 'Hello! This is DizzCall AI calling you.');
        
        if (!$to) {
            return response()->json([
                'success' => false,
                'error' => 'Phone number is required'
            ], 400);
        }
        
        // Get Twilio credentials
        $accountSid = config('twilio.account_sid');
        $authToken = config('twilio.auth_token');
        $phoneNumber = config('twilio.phone_number');
        
        if (!$accountSid || !$authToken || !$phoneNumber) {
            return response()->json([
                'success' => false,
                'error' => 'Twilio configuration missing'
            ], 500);
        }
        
        // Create Twilio client
        $client = new \Twilio\Rest\Client($accountSid, $authToken);
        
        // Use ngrok URL for webhook
        $webhookUrl = 'https://d4f73a63faa0.ngrok-free.app/dizzcall-ai/public/api/twilio/webhook/outbound';
        
        // Check if test mode is enabled
        $testMode = $request->input('test_mode', false);
        
        if ($testMode) {
            // Test mode - simulate call without actually calling
            return response()->json([
                'success' => true,
                'call_sid' => 'TEST_' . uniqid(),
                'status' => 'queued',
                'message' => 'Test call simulated successfully (no trial message)',
                'webhook_url' => $webhookUrl,
                'test_mode' => true
            ]);
        }
        
        // Make the actual call
        $call = $client->calls->create(
            $to,
            $phoneNumber,
            [
                'url' => $webhookUrl,
                'method' => 'POST',
                'timeout' => 30,
                'statusCallback' => $webhookUrl,
                'statusCallbackEvent' => ['initiated', 'ringing', 'answered', 'completed']
            ]
        );
        
        return response()->json([
            'success' => true,
            'call_sid' => $call->sid,
            'status' => $call->status,
            'message' => 'Call initiated successfully',
            'webhook_url' => $webhookUrl,
            'trial_message' => 'Note: Trial account will play upgrade message'
        ]);
        
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => 'Failed to make call: ' . $e->getMessage()
        ], 500);
    }
})->withoutMiddleware(['csrf', 'web']);

// Simple AI Test Route for Dashboard (no auth required)
Route::get('/ai-test-dashboard', function (Request $request) {
    try {
        $phi3 = new \App\Services\AI\Phi3Service();
        
        if ($request->has('message')) {
            // Test with a message
            $result = $phi3->generateResponse($request->get('message'), [], 'general');
            return response()->json([
                'success' => true,
                'message' => 'AI response generated',
                'data' => [
                    'ai_message' => [
                        'content' => $result['response']
                    ]
                ]
            ]);
        } else {
            // Test connection
            $result = $phi3->testConnection();
            return response()->json([
                'success' => $result['success'],
                'message' => $result['message'],
                'details' => $result['details'] ?? null
            ]);
        }
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'AI Error: ' . $e->getMessage()
        ]);
    }
});

// Client Test Dashboard (no auth required)
Route::get('/client-test-dashboard', function () {
    return view('client-test-dashboard');
});

// AI API Routes (no auth required for testing)
Route::prefix('api/ai')->group(function () {
    Route::post('/test-connection', [AIAPIController::class, 'testConnection']);
    Route::post('/conversations/start', [AIAPIController::class, 'startConversation']);
    Route::post('/conversations/{id}/message', [AIAPIController::class, 'sendMessage']);
    Route::get('/conversations/{id}', [AIAPIController::class, 'getConversation']);
    Route::post('/analyze-sentiment', [AIAPIController::class, 'analyzeSentiment']);
    Route::post('/extract-insights', [AIAPIController::class, 'extractInsights']);
});

// Client Test API Routes (for client testing - no auth required)
Route::prefix('api/client-test')->group(function () {
    Route::get('/connection', [\App\Http\Controllers\ClientTestController::class, 'testConnection']);
    Route::post('/simulate-call', [\App\Http\Controllers\ClientTestController::class, 'simulatePhoneCall']);
    Route::post('/test-responses', [\App\Http\Controllers\ClientTestController::class, 'testAIResponses']);
    Route::post('/simulate-webhook', [\App\Http\Controllers\ClientTestController::class, 'simulateWebhook']);
    Route::get('/performance', [\App\Http\Controllers\ClientTestController::class, 'getPerformanceMetrics']);
    Route::get('/scenarios', [\App\Http\Controllers\ClientTestController::class, 'testScenarios']);
});

// Twilio Phone Integration Routes
Route::prefix('api/twilio')->group(function () {
    // Webhook routes (no auth required - called by Twilio) - Support both GET and POST
    Route::get('/webhook/incoming', [\App\Http\Controllers\TwilioPhoneController::class, 'handleIncomingCall'])->name('twilio.incoming')->withoutMiddleware(['csrf', 'web']);
    Route::post('/webhook/incoming', [\App\Http\Controllers\TwilioPhoneController::class, 'handleIncomingCall'])->name('twilio.incoming')->withoutMiddleware(['csrf', 'web']);
    Route::get('/webhook/speech', [\App\Http\Controllers\TwilioPhoneController::class, 'handleSpeech'])->name('twilio.speech')->withoutMiddleware(['csrf', 'web']);
    Route::post('/webhook/speech', [\App\Http\Controllers\TwilioPhoneController::class, 'handleSpeech'])->name('twilio.speech')->withoutMiddleware(['csrf', 'web']);
    Route::get('/webhook/outbound', [\App\Http\Controllers\TwilioPhoneController::class, 'handleOutboundCall'])->name('twilio.outbound')->withoutMiddleware(['csrf', 'web']);
    Route::post('/webhook/outbound', [\App\Http\Controllers\TwilioPhoneController::class, 'handleOutboundCall'])->name('twilio.outbound')->withoutMiddleware(['csrf', 'web']);
    
    // API routes (auth required)
    Route::middleware('auth')->group(function () {
        Route::post('/make-call', [\App\Http\Controllers\TwilioPhoneController::class, 'makeCall']);
        Route::get('/call-status', [\App\Http\Controllers\TwilioPhoneController::class, 'getCallStatus']);
    });
});

// Wallet routes (authenticated users)
Route::middleware(['auth'])->group(function () {
    Route::get('/wallet/topup', [WalletController::class, 'showTopUpForm'])->name('wallet.topup');
    Route::post('/wallet/order', [WalletController::class, 'createOrder'])->name('wallet.order');
    Route::post('/wallet/verify', [WalletController::class, 'verify'])->name('wallet.verify');
});

// Razorpay webhook (signature verified inside controller)
Route::post('/webhooks/razorpay', [RazorpayWebhookController::class, 'handle'])->name('webhooks.razorpay');

// FrontUser routes (authenticated users)
Route::prefix('user')->name('user.')->middleware(['auth'])->group(function () {
    // Dashboard
    Route::get('/', [FrontUserDashboardController::class, 'index'])->name('dashboard');
    Route::get('/dashboard', [FrontUserDashboardController::class, 'index'])->name('dashboard.alt');
    
    // AI Dashboard
    Route::get('/ai', [AIDashboardController::class, 'index'])->name('ai.dashboard');
    Route::get('/ai/analytics', [AIDashboardController::class, 'getAnalytics'])->name('ai.analytics');
    Route::get('/ai/status', [AIDashboardController::class, 'getAIStatus'])->name('ai.status');
    Route::post('/ai/settings', [AIDashboardController::class, 'updateSettings'])->name('ai.settings');
    Route::get('/ai/performance', [AIDashboardController::class, 'getPerformanceMetrics'])->name('ai.performance');

    // Calls
    Route::get('/calls', [FrontUserCallsController::class, 'index'])->name('calls.index');
    Route::get('/calls/create', [FrontUserCallsController::class, 'create'])->name('calls.create');
    Route::post('/calls', [FrontUserCallsController::class, 'store'])->name('calls.store');
    Route::get('/calls/bulk', [FrontUserCallsController::class, 'bulkCreate'])->name('calls.bulk.create');
    Route::post('/calls/bulk', [FrontUserCallsController::class, 'bulkStore'])->name('calls.bulk.store');
    Route::get('/calls/{id}', [FrontUserCallsController::class, 'show'])->name('calls.show');
    Route::get('/calls/{id}/edit', [FrontUserCallsController::class, 'edit'])->name('calls.edit');
    Route::put('/calls/{id}', [FrontUserCallsController::class, 'update'])->name('calls.update');
    Route::delete('/calls/{id}', [FrontUserCallsController::class, 'destroy'])->name('calls.destroy');
    Route::post('/calls/{id}/start', [FrontUserCallsController::class, 'startCall'])->name('calls.start');
    Route::post('/calls/{id}/end', [FrontUserCallsController::class, 'endCall'])->name('calls.end');
    Route::get('/calls/analytics', [FrontUserCallsController::class, 'getCallAnalytics'])->name('calls.analytics');

    // Wallet
    Route::get('/wallet', [FrontUserWalletController::class, 'index'])->name('wallet.index');
    Route::get('/wallet/transactions', [FrontUserWalletController::class, 'transactions'])->name('wallet.transactions');
    Route::post('/wallet/add-funds', [FrontUserWalletController::class, 'addFunds'])->name('wallet.add-funds');
    Route::post('/wallet/withdraw', [FrontUserWalletController::class, 'withdrawFunds'])->name('wallet.withdraw');
    Route::get('/wallet/payment-methods', [FrontUserWalletController::class, 'getPaymentMethods'])->name('wallet.payment-methods');

    // Reports
    Route::get('/reports', [FrontUserReportsController::class, 'index'])->name('reports.index');

    // Search
    Route::get('/search', [FrontUserSearchController::class, 'index'])->name('search');
    Route::get('/search/api', [FrontUserSearchController::class, 'search'])->name('search.api');

    // Profile
    Route::get('/profile', [FrontUserProfileController::class, 'index'])->name('profile.index');
    Route::put('/profile', [FrontUserProfileController::class, 'update'])->name('profile.update');
    Route::put('/profile/password', [FrontUserProfileController::class, 'changePassword'])->name('profile.password');

    // Settings
    Route::get('/settings', [FrontUserUserSettingsController::class, 'index'])->name('settings.index');
    Route::post('/settings/profile', [FrontUserUserSettingsController::class, 'updateProfile'])->name('settings.profile.update');
    Route::post('/settings/notifications', [FrontUserUserSettingsController::class, 'updateNotifications'])->name('settings.notifications.update');
    Route::post('/settings/api', [FrontUserUserSettingsController::class, 'updateApi'])->name('settings.api.update');
    Route::post('/settings/avatar', [FrontUserUserSettingsController::class, 'uploadAvatar'])->name('settings.avatar.upload');

    // AI Voice Agent Routes
    Route::prefix('ai')->name('ai.')->group(function () {
        // Main AI dashboard - now using the working chat interface
        Route::get('/', function() {
            return view('FrontUser.ai.simple-chat');
        })->name('dashboard');
        
        Route::post('/conversations/start', [AIController::class, 'startConversation'])->name('conversations.start');
        Route::post('/conversations/{id}/message', [AIController::class, 'sendMessage'])->name('conversations.message');
        Route::get('/conversations/{id}', [AIController::class, 'getConversation'])->name('conversations.get');
        Route::post('/conversations/{id}/complete', [AIController::class, 'completeConversation'])->name('conversations.complete');
        Route::get('/conversations', [AIController::class, 'getUserConversations'])->name('conversations.list');
        Route::post('/test-connection', [AIController::class, 'testConnection'])->name('test.connection');
        Route::post('/analyze-sentiment', [AIController::class, 'analyzeSentiment'])->name('analyze.sentiment');
        Route::post('/extract-insights', [AIController::class, 'extractInsights'])->name('extract.insights');
        
        // Simple AI chat route for authenticated users
        Route::get('/chat', function() {
            return view('FrontUser.ai.simple-chat');
        })->name('chat');
    });

    // CRM Routes
    Route::prefix('crm')->name('crm.')->group(function () {
        Route::get('/', [\App\Http\Controllers\FrontUser\CRMController::class, 'index'])->name('dashboard');
        Route::post('/conversations/start', [\App\Http\Controllers\FrontUser\CRMController::class, 'startConversation'])->name('conversations.start');
        Route::post('/conversations/{id}/message', [\App\Http\Controllers\FrontUser\CRMController::class, 'sendMessage'])->name('conversations.message');
        Route::get('/conversations/{id}', [\App\Http\Controllers\FrontUser\CRMController::class, 'getConversation'])->name('conversations.get');
        Route::post('/conversations/{id}/complete', [\App\Http\Controllers\FrontUser\CRMController::class, 'completeConversation'])->name('conversations.complete');
        Route::get('/conversations', [\App\Http\Controllers\FrontUser\CRMController::class, 'getUserConversations'])->name('conversations.list');
        Route::post('/test-connection', [\App\Http\Controllers\FrontUser\CRMController::class, 'testConnection'])->name('test.connection');
        Route::get('/analytics', [\App\Http\Controllers\FrontUser\CRMController::class, 'getAnalytics'])->name('analytics');
        Route::get('/contacts/{id}/lead-scoring', [\App\Http\Controllers\FrontUser\CRMController::class, 'getLeadScoring'])->name('lead.scoring');
        Route::get('/contacts/{id}/behavior', [\App\Http\Controllers\FrontUser\CRMController::class, 'getCustomerBehavior'])->name('customer.behavior');
    });
});

// Ultra-fast phone AI endpoint - instant responses
Route::get('/ai-phone-instant', function(Request $request) {
    $message = $request->input('message', 'Hello');
    
    // Pre-defined fast responses for common phone queries - CRM style
    $fastResponses = [
        'services' => 'Absolutely! We specialize in custom software development, mobile applications, Salesforce solutions, video editing, digital marketing, AI automation, and comprehensive IT support. What specific solution interests you most?',
        'hello' => 'Hi there! This is Alex from Dizaart Systems. I\'m excited to help you today. What can I assist you with?',
        'help' => 'I\'m absolutely here to help! We provide cutting-edge custom software development, mobile apps, and AI-powered solutions. What would you like to know more about?',
        'contact' => 'Perfect! You can reach us at info@dizaartsystems.com or visit our office at Nx One A318, Techzone 4, Greater Noida. I can also connect you directly with our team right now.',
        'price' => 'Great question! Our pricing is tailored to each project\'s specific requirements. I\'d love to connect you with our team for a personalized quote. What type of solution are you considering?',
        'demo' => 'Excellent! I can absolutely schedule a demo for you. What type of solution are you most interested in? We have amazing demos for our software, mobile apps, and AI automation tools.'
    ];
    
    $messageLower = strtolower($message);
    
    // Check for keywords and return instant response
    foreach ($fastResponses as $keyword => $response) {
        if (strpos($messageLower, $keyword) !== false) {
            return response()->json([
                'success' => true,
                'response' => $response,
                'model' => 'instant-phone'
            ]);
        }
    }
    
    // Default fast response - CRM style
    return response()->json([
        'success' => true,
        'response' => 'Thank you for calling Dizaart Systems! I\'m Alex, and I\'m thrilled to help you today. We specialize in custom software development, mobile applications, and cutting-edge AI solutions. What can I do for you?',
        'model' => 'instant-phone'
    ]);
})->withoutMiddleware(['csrf']);