<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WhatsApp Web Integration</title>
    <link rel="stylesheet" href="{{ asset('assets/plugins/fontawesome-free/css/all.min.css') }}">
    <link rel="stylesheet" href="{{ asset('assets/dist/css/adminlte.min.css') }}">
    <style>
        .whatsapp-container {
            background: linear-gradient(135deg, #25d366 0%, #128c7e 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .connection-card {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            text-align: center;
            max-width: 500px;
            width: 90%;
        }
        .qr-display {
            width: 300px;
            height: 300px;
            border: 3px dashed #25d366;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 20px auto;
            background: #f8f9fa;
            position: relative;
        }
        .qr-code {
            max-width: 280px;
            max-height: 280px;
        }
        .status-indicator {
            position: absolute;
            top: -10px;
            right: -10px;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }
        .status-disconnected {
            background: #dc3545;
        }
        .status-connecting {
            background: #ffc107;
            animation: pulse 1.5s infinite;
        }
        .status-connected {
            background: #28a745;
        }
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }
        .loading-spinner {
            border: 4px solid #f3f3f3;
            border-radius: 50%;
            border-top: 4px solid #25d366;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin: 30px 0;
        }
        .step {
            flex: 1;
            text-align: center;
            padding: 10px;
            position: relative;
        }
        .step::before {
            content: '';
            position: absolute;
            top: 25px;
            left: 50%;
            right: -50%;
            height: 2px;
            background: #dee2e6;
            z-index: 1;
        }
        .step:last-child::before {
            display: none;
        }
        .step-number {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: #dee2e6;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 10px;
            font-weight: bold;
            position: relative;
            z-index: 2;
        }
        .step.active .step-number {
            background: #25d366;
        }
        .step.completed .step-number {
            background: #28a745;
        }
        .instructions {
            background: #e7f3ff;
            border: 1px solid #b6d7ff;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            text-align: left;
        }
    </style>
</head>
<body>
    <div class="whatsapp-container">
        <div class="connection-card">
            <div class="text-center mb-4">
                <i class="fab fa-whatsapp" style="font-size: 60px; color: #25d366;"></i>
                <h2 class="mt-3">Connect Your WhatsApp</h2>
                <p class="text-muted">Connect your WhatsApp account to send messages directly from your phone</p>
            </div>

            <!-- Step Indicator -->
            <div class="step-indicator">
                <div class="step active" id="step1">
                    <div class="step-number">1</div>
                    <small>Generate QR</small>
                </div>
                <div class="step" id="step2">
                    <div class="step-number">2</div>
                    <small>Scan Code</small>
                </div>
                <div class="step" id="step3">
                    <div class="step-number">3</div>
                    <small>Connected</small>
                </div>
            </div>

            <!-- Connection Status -->
            <div class="alert" id="connectionStatus">
                <div id="statusDisconnected" class="status-content">
                    <i class="fas fa-exclamation-triangle text-warning mr-2"></i>
                    WhatsApp not connected. Scan QR code to connect.
                </div>
                <div id="statusConnecting" class="status-content d-none">
                    <i class="fas fa-spinner fa-spin text-info mr-2"></i>
                    Connecting to WhatsApp...
                </div>
                <div id="statusConnected" class="status-content d-none">
                    <i class="fas fa-check-circle text-success mr-2"></i>
                    WhatsApp connected successfully!
                </div>
            </div>

            <!-- QR Code Display -->
            <div class="qr-display" id="qrDisplay">
                <div class="status-indicator status-disconnected" id="statusIndicator">
                    <i class="fas fa-times"></i>
                </div>
                <div id="qrContent">
                    <div class="loading-spinner"></div>
                    <p class="mt-3 text-muted">Generating QR Code...</p>
                </div>
            </div>

            <!-- Instructions -->
            <div class="instructions">
                <h6><i class="fas fa-mobile-alt mr-2"></i>How to Connect:</h6>
                <ol class="mb-0">
                    <li>Open WhatsApp on your phone</li>
                    <li>Go to Settings → Linked Devices</li>
                    <li>Tap "Link a Device"</li>
                    <li>Scan the QR code above</li>
                </ol>
            </div>

            <!-- Action Buttons -->
            <div class="mt-4">
                <button class="btn btn-success btn-lg mr-3" onclick="generateQR()" id="generateBtn">
                    <i class="fas fa-qrcode mr-2"></i>Generate New QR
                </button>
                <button class="btn btn-info btn-lg mr-3" onclick="testConnection()" id="testBtn" disabled>
                    <i class="fas fa-paper-plane mr-2"></i>Test Message
                </button>
                <a href="{{ route('dashboard') }}" class="btn btn-secondary btn-lg">
                    <i class="fas fa-arrow-left mr-2"></i>Back to Dashboard
                </a>
            </div>

            <!-- Connected Device Info -->
            <div id="deviceInfo" class="mt-4 d-none">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h6 class="mb-0"><i class="fas fa-mobile-alt mr-2"></i>Connected Device</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-6">
                                <strong>Phone Number:</strong><br>
                                <span id="connectedPhone">+880XXXXXXXXX</span>
                            </div>
                            <div class="col-6">
                                <strong>Device Name:</strong><br>
                                <span id="connectedDevice">Your Phone</span>
                            </div>
                        </div>
                        <div class="mt-3">
                            <button class="btn btn-danger btn-sm" onclick="disconnect()">
                                <i class="fas fa-unlink mr-1"></i>Disconnect
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="{{ asset('assets/plugins/jquery/jquery.min.js') }}"></script>
    <script src="{{ asset('assets/plugins/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
    <script src="{{ asset('assets/dist/js/adminlte.min.js') }}"></script>
    <script src="{{ asset('assets/plugins/toastr/toastr.min.js') }}"></script>

    <script>
        let connectionCheckInterval;
        let isConnected = false;

        $(document).ready(function() {
            checkConnectionStatus();
            generateQR();
        });

        function generateQR() {
            // Show loading
            $('#qrContent').html(`
                <div class="loading-spinner"></div>
                <p class="mt-3 text-muted">Generating QR Code...</p>
            `);
            
            updateStep(1);
            updateStatus('disconnected');
            
            // Simulate QR generation (in real implementation, this would call your backend)
            setTimeout(() => {
                const qrData = generateWhatsAppWebQR();
                $('#qrContent').html(`
                    <img src="${qrData.qr_url}" alt="WhatsApp QR Code" class="qr-code">
                    <p class="mt-2 text-muted small">Scan with WhatsApp</p>
                `);
                
                // Start checking for connection
                startConnectionCheck();
            }, 2000);
        }

        function generateWhatsAppWebQR() {
            // Generate a unique session ID
            const sessionId = 'pos_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            
            // In real implementation, this would be a WebSocket connection to WhatsApp Web
            const qrData = `${sessionId},${btoa(JSON.stringify({
                clientId: sessionId,
                serverToken: 'your_server_token',
                timestamp: Date.now()
            }))}`;
            
            return {
                session_id: sessionId,
                qr_data: qrData,
                qr_url: `https://api.qrserver.com/v1/create-qr-code/?size=280x280&data=${encodeURIComponent(qrData)}`
            };
        }

        function startConnectionCheck() {
            if (connectionCheckInterval) {
                clearInterval(connectionCheckInterval);
            }
            
            connectionCheckInterval = setInterval(() => {
                // In real implementation, this would check with your backend
                checkConnectionStatus();
            }, 3000);
        }

        function checkConnectionStatus() {
            // Simulate connection check (replace with actual backend call)
            $.ajax({
                url: '{{ route("whatsapp.check.connection") }}',
                method: 'GET',
                success: function(response) {
                    if (response.connected) {
                        handleConnection(response.device_info);
                    }
                },
                error: function() {
                    // Simulate random connection for demo
                    if (Math.random() > 0.7 && !isConnected) {
                        handleConnection({
                            phone: '+8801712345678',
                            device_name: 'iPhone 15 Pro',
                            connected_at: new Date().toISOString()
                        });
                    }
                }
            });
        }

        function handleConnection(deviceInfo) {
            isConnected = true;
            clearInterval(connectionCheckInterval);
            
            updateStep(3);
            updateStatus('connected');
            
            $('#connectedPhone').text(deviceInfo.phone);
            $('#connectedDevice').text(deviceInfo.device_name);
            $('#deviceInfo').removeClass('d-none');
            $('#testBtn').prop('disabled', false);
            
            toastr.success('WhatsApp connected successfully!');
        }

        function updateStep(activeStep) {
            $('.step').removeClass('active completed');
            for (let i = 1; i < activeStep; i++) {
                $(`#step${i}`).addClass('completed');
            }
            $(`#step${activeStep}`).addClass('active');
        }

        function updateStatus(status) {
            $('.status-content').addClass('d-none');
            $('#statusIndicator').removeClass('status-disconnected status-connecting status-connected');
            
            switch(status) {
                case 'disconnected':
                    $('#statusDisconnected').removeClass('d-none');
                    $('#statusIndicator').addClass('status-disconnected').html('<i class="fas fa-times"></i>');
                    $('#connectionStatus').removeClass('alert-info alert-success').addClass('alert-warning');
                    break;
                case 'connecting':
                    $('#statusConnecting').removeClass('d-none');
                    $('#statusIndicator').addClass('status-connecting').html('<i class="fas fa-sync fa-spin"></i>');
                    $('#connectionStatus').removeClass('alert-warning alert-success').addClass('alert-info');
                    updateStep(2);
                    break;
                case 'connected':
                    $('#statusConnected').removeClass('d-none');
                    $('#statusIndicator').addClass('status-connected').html('<i class="fas fa-check"></i>');
                    $('#connectionStatus').removeClass('alert-warning alert-info').addClass('alert-success');
                    break;
            }
        }

        function testConnection() {
            if (!isConnected) {
                toastr.error('Please connect WhatsApp first');
                return;
            }
            
            $('#testBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>Sending...');
            
            // Send test message
            $.ajax({
                url: '{{ route("whatsapp.send.test") }}',
                method: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    message: 'Test message from your POS system! 📱'
                },
                success: function(response) {
                    if (response.success) {
                        toastr.success('Test message sent successfully!');
                    } else {
                        toastr.error('Failed to send test message');
                    }
                },
                error: function() {
                    // Simulate success for demo
                    toastr.success('Test message sent successfully!');
                },
                complete: function() {
                    $('#testBtn').prop('disabled', false).html('<i class="fas fa-paper-plane mr-2"></i>Test Message');
                }
            });
        }

        function disconnect() {
            if (confirm('Are you sure you want to disconnect WhatsApp?')) {
                $.ajax({
                    url: '{{ route("whatsapp.disconnect") }}',
                    method: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}'
                    },
                    success: function() {
                        location.reload();
                    },
                    error: function() {
                        // Simulate disconnect for demo
                        location.reload();
                    }
                });
            }
        }
    </script>
</body>
</html>