<?php
/**
 * @var object $campaign Campaign object with id and name properties
 * @var object $batch Batch object with id, batch_number, and scheduled_for properties
 */
if (!isset($campaign) || !isset($batch)) {
    show_404();
    return;
}
?>
<style>
.delivery-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
    border-radius: 16px;
    padding: 2rem;
    color: white;
    margin-bottom: 2rem;
    box-shadow: 0 4px 20px rgba(59, 130, 246, 0.15);
}

.delivery-header h1 {
    font-size: 1.75rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.delivery-header .campaign-name {
    font-size: 1rem;
    opacity: 0.95;
    font-weight: 400;
}

.delivery-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}

.delivery-stat-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    border: 1px solid rgba(59, 130, 246, 0.1);
    transition: all 0.3s ease;
}

.delivery-stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(59, 130, 246, 0.12);
}

.delivery-stat-card .icon-wrapper {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 1rem;
    font-size: 1.5rem;
}

.delivery-stat-card.assigned .icon-wrapper {
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    color: white;
}

.delivery-stat-card.delivered .icon-wrapper {
    background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
    color: white;
}

.delivery-stat-card.failed .icon-wrapper {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white;
}

.delivery-stat-card.scheduled .icon-wrapper {
    background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
    color: white;
}

.delivery-stat-card .stat-label {
    font-size: 0.875rem;
    color: #64748b;
    font-weight: 500;
    margin-bottom: 0.5rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.delivery-stat-card .stat-number {
    font-size: 2rem;
    font-weight: 700;
    color: #1e293b;
    font-family: 'Space Grotesk', sans-serif;
}

.delivery-stat-card.scheduled .stat-number {
    font-size: 1.25rem;
}

.data-table-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    overflow: hidden;
}

.data-table-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
    padding: 1.5rem;
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.data-table-header h3 {
    font-size: 1.25rem;
    font-weight: 600;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.export-buttons {
    display: flex;
    gap: 0.75rem;
}

.export-btn {
    background: rgba(255, 255, 255, 0.15);
    color: white;
    border: 1px solid rgba(255, 255, 255, 0.3);
    padding: 0.5rem 1rem;
    border-radius: 8px;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.export-btn:hover {
    background: rgba(255, 255, 255, 0.25);
    border-color: rgba(255, 255, 255, 0.5);
    transform: translateY(-1px);
}

.data-table-body {
    padding: 1.5rem;
}

.privacy-alert {
    background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
    border: 1px solid #93c5fd;
    border-radius: 12px;
    padding: 1rem 1.25rem;
    margin-bottom: 1.5rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
    color: #1e40af;
}

.privacy-alert i {
    font-size: 1.25rem;
}

#batchSendsTable {
    width: 100% !important;
}

#batchSendsTable thead {
    background: #f8fafc;
    border-bottom: 2px solid #e2e8f0;
}

#batchSendsTable thead th {
    padding: 1rem;
    font-weight: 600;
    color: #475569;
    font-size: 0.875rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border: none;
}

#batchSendsTable tbody td {
    padding: 1rem;
    vertical-align: middle;
    border-bottom: 1px solid #f1f5f9;
    color: #334155;
}

#batchSendsTable tbody tr:hover {
    background: #f8fafc;
}

.table-wrapper {
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #e2e8f0;
}

.dataTables_wrapper .dataTables_filter input {
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 0.5rem 1rem;
    margin-left: 0.5rem;
}

.dataTables_wrapper .dataTables_length select {
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 0.375rem 2rem 0.375rem 0.75rem;
}

.back-button {
    background: rgba(255, 255, 255, 0.15);
    color: white;
    border: 1px solid rgba(255, 255, 255, 0.3);
    padding: 0.625rem 1.25rem;
    border-radius: 10px;
    font-weight: 500;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    transition: all 0.3s ease;
}

.back-button:hover {
    background: rgba(255, 255, 255, 0.25);
    color: white;
    transform: translateY(-1px);
}
</style>

<div class="delivery-header">
    <div class="d-flex justify-content-between align-items-start">
        <div>
            <h1>
                <i class="bi bi-send-check-fill"></i>
                Delivery <?= (int)$batch->batch_number ?> Details
            </h1>
            <div class="campaign-name">Campaign: <?= html_escape($campaign->name) ?></div>
        </div>
        <a href="<?= base_url('user/campaign_view/' . $campaign->id) ?>" class="back-button">
            <i class="bi bi-arrow-left"></i> Back to Campaign
        </a>
    </div>
</div>

<div class="delivery-stats">
    <div class="delivery-stat-card assigned">
        <div class="icon-wrapper">
            <i class="bi bi-check2-square"></i>
        </div>
        <div class="stat-label">Total Assigned</div>
        <div class="stat-number"><?= number_format($total_assigned ?? 0) ?></div>
    </div>
    
    <div class="delivery-stat-card delivered">
        <div class="icon-wrapper">
            <i class="bi bi-check-circle-fill"></i>
        </div>
        <div class="stat-label">Delivered</div>
        <div class="stat-number"><?= number_format($total_delivered ?? 0) ?></div>
    </div>
    
    <div class="delivery-stat-card failed">
        <div class="icon-wrapper">
            <i class="bi bi-x-circle-fill"></i>
        </div>
        <div class="stat-label">Failed</div>
        <div class="stat-number"><?= number_format($total_failed_actual ?? 0) ?></div>
    </div>
<!--     
    <div class="delivery-stat-card scheduled">
        <div class="icon-wrapper">
            <i class="bi bi-calendar-check-fill"></i>
        </div>
        <div class="stat-label">Scheduled For</div>
        <div class="stat-number"><?= date('M d, Y H:i', strtotime($batch->scheduled_for ?? 'now')) ?></div>
    </div> -->
</div>

<div class="data-table-card">
    <div class="data-table-header">
        <h3>
            <i class="bi bi-journal-text"></i>
            Delivery Log
        </h3>
        <div class="export-buttons" id="exportButtons">
            <!-- Export buttons will be added by JavaScript -->
        </div>
    </div>
    <div class="data-table-body">
        <?php if (!empty($send_data)): ?>
            <div class="privacy-alert">
                <i class="bi bi-shield-check-fill"></i>
                <div>
                    <strong>Privacy Notice:</strong> All personal data is masked for security. Exports remain masked.
                </div>
            </div>

            <div class="table-wrapper">
                <table class="table table-sm table-hover mb-0" id="batchSendsTable">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Mobile</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Status</th>
                            <th>Username</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Data loaded via AJAX -->
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="alert alert-warning">
                <i class="bi bi-inbox"></i> No delivery data available for this batch yet.
            </div>
        <?php endif; ?>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.31/jspdf.plugin.autotable.min.js"></script>

<script>
const campaignId = <?= (int)$campaign->id ?>;
const batchId = <?= (int)$batch->id ?>;

// Initialize DataTable with server-side processing
$(document).ready(function() {
    console.log('Initializing DataTable...');
    
    const table = $('#batchSendsTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '<?= base_url('user/get_batch_sends_data/' . (int)$campaign->id . '/' . (int)$batch->id) ?>',
            type: 'GET',
            timeout: 30000, // 30 second timeout
            error: function(xhr, error, code) {
                console.error('AJAX Error:', error, code);
                console.error('Response:', xhr.responseText);
                
                let errorMsg = 'Error loading data.';
                if (error === 'timeout') {
                    errorMsg = 'Request timed out. The database query is taking too long with <?= number_format($total_sends) ?> records. Please contact administrator to add database indexes.';
                } else if (xhr.status === 500) {
                    errorMsg = 'Server error. The query may be timing out due to large dataset (<?= number_format($total_sends) ?> records). Check application logs.';
                } else if (xhr.status === 0) {
                    errorMsg = 'Connection failed. Server may be overloaded or query timed out.';
                }
                
                alert(errorMsg + '\n\nTechnical details in browser console (F12).');
            }
        },
        columns: [
            { data: 0, orderable: false, title: '#' },
            { data: 1, orderable: false, title: 'Mobile' },
            { data: 2, orderable: false, title: 'Name' },
            { data: 3, orderable: false, title: 'Email' },
            { 
                data: 4,
                orderable: false,
                title: 'Status',
                render: function(data) {
                    if (data === 'sent') {
                        return '<span class="badge bg-success">Sent</span>';
                    } else if (data === 'failed') {
                        return '<span class="badge bg-danger">Failed</span>';
                    } else {
                        return '<span class="badge bg-info">Send</span>';
                    }
                }
            },
            { data: 5, orderable: false, title: 'Username' }
        ],
        dom: 'frtip',
        
        pageLength: 25,
        lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
        order: [],
        language: {
            processing: '<i class="bi bi-hourglass-split"></i> Loading...',
            emptyTable: 'No send data available',
            zeroRecords: 'No matching records found'
        }
    });
    
    // Add custom export buttons
    $('#exportButtons').html(`
        <button onclick="exportStreamCSV()" class="export-btn" title="Fast CSV export - No memory limits!">
            <i class="bi bi-filetype-csv"></i> Export CSV (Fast)
        </button>
        <button onclick="exportTableToExcel()" class="export-btn">
            <i class="bi bi-file-earmark-excel-fill"></i> Export Excel
        </button>
        <button onclick="exportTableToPDF()" class="export-btn">
            <i class="bi bi-file-earmark-pdf-fill"></i> Export PDF
        </button>
    `);
    
    console.log('DataTable initialized');
});

// NEW: Stream CSV Export - Direct download, no memory issues!
function exportStreamCSV() {
    const totalRecords = <?= $total_sends ?>;
    
    if (totalRecords === 0) {
        alert('No data to export');
        return;
    }
    
    if (totalRecords > 100000) {
        if (!confirm(`Export ${totalRecords.toLocaleString()} records as CSV?\n\nThis will download directly without loading into browser memory.\nNo timeout or memory issues!\n\nContinue?`)) {
            return;
        }
    }
    
    // Direct download via URL - server streams the data
    const url = '<?= base_url('user/stream_batch_sends_csv/' . (int)$campaign->id . '/' . (int)$batch->id) ?>';
    
    console.log('Starting stream CSV export...');
    alert('Download will start shortly. This may take a few moments for large datasets.');
    
    // Trigger download
    window.location.href = url;
}

function exportTableToExcel() {
    const btn = event.target.closest('button');
    btn.disabled = true;
    btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Exporting...';
    
    console.log('Starting Excel export...');
    
    // With 2.2M records, we need batch export
    const totalRecords = <?= $total_sends ?>;
    const batchSize = 50000;
    const totalBatches = Math.ceil(totalRecords / batchSize);
    
    if (totalRecords > 100000) {
        if (!confirm(`This will export ${totalRecords.toLocaleString()} records in ${totalBatches} batches. This may take a few minutes. Continue?`)) {
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-file-earmark-excel-fill"></i> Export Excel';
            return;
        }
    }
    
    let allData = [];
    let currentBatch = 0;
    
    function fetchBatch() {
        const start = currentBatch * batchSize;
        const url = '<?= base_url('user/get_batch_sends_data/' . (int)$campaign->id . '/' . (int)$batch->id) ?>';
        const params = new URLSearchParams({
            start: start,
            length: batchSize,
            draw: currentBatch + 1
        });
        
        console.log(`Fetching batch ${currentBatch + 1}/${totalBatches} (records ${start} to ${start + batchSize})`);
        btn.innerHTML = `<i class="bi bi-hourglass-split"></i> Exporting... Batch ${currentBatch + 1}/${totalBatches}`;
        
        fetch(`${url}?${params.toString()}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(result => {
                console.log(`Batch ${currentBatch + 1} received:`, result.data.length, 'records');
                
                if (result.data && result.data.length > 0) {
                    allData = allData.concat(result.data);
                }
                
                currentBatch++;
                
                if (currentBatch < totalBatches && result.data && result.data.length > 0) {
                    // Fetch next batch
                    setTimeout(fetchBatch, 100); // Small delay to prevent server overload
                } else {
                    // All batches fetched, generate Excel
                    generateExcel();
                }
            })
            .catch(error => {
                console.error('Export error:', error);
                alert('Error exporting data: ' + error.message + '\n\nTry refreshing the page and export again.');
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-file-earmark-excel-fill"></i> Export Excel';
            });
    }
    
    function generateExcel() {
        console.log('Generating Excel with', allData.length, 'records...');
        btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Generating Excel...';
        
        if (allData.length === 0) {
            alert('No data available to export');
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-file-earmark-excel-fill"></i> Export Excel';
            return;
        }
        
        try {
            const wsData = [
                ['#', 'Mobile', 'Name', 'Email', 'Status', 'Username']
            ];
            
            allData.forEach((row) => {
                wsData.push([
                    row[0] || '',
                    row[1] || 'N/A',
                    row[2] || 'N/A',
                    row[3] || 'N/A',
                    row[4] || 'pending',
                    row[5] || 'N/A'
                ]);
            });
            
            console.log('Creating Excel worksheet...');
            const ws = XLSX.utils.aoa_to_sheet(wsData);
            
            // Set column widths
            ws['!cols'] = [
                {wch: 5},  // #
                {wch: 15}, // Mobile
                {wch: 20}, // Name
                {wch: 25}, // Email
                {wch: 10}, // Status
                {wch: 15}  // Username
            ];
            
            console.log('Creating workbook...');
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "Delivery " + <?= (int)$batch->batch_number ?>);
            
            console.log('Writing file...');
            const filename = 'Delivery_<?= (int)$batch->batch_number ?>_<?= date('Y-m-d') ?>_Complete.xlsx';
            XLSX.writeFile(wb, filename);
            
            console.log('Export complete!');
            alert(`Successfully exported ${allData.length.toLocaleString()} records!`);
            
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-file-earmark-excel-fill"></i> Export Excel';
        } catch(e) {
            console.error('Excel generation error:', e);
            alert('Error generating Excel file: ' + e.message);
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-file-earmark-excel-fill"></i> Export Excel';
        }
    }
    
    // Start fetching
    fetchBatch();
}

function exportTableToPDF() {
    const btn = event.target.closest('button');
    
    const totalRecords = <?= $total_sends ?>;
    
    if (totalRecords > 10000) {
        alert('PDF export is limited to 10,000 records for performance.\n\nYou have ' + totalRecords.toLocaleString() + ' records.\n\nPlease use Excel export instead for large datasets.');
        return;
    }
    
    btn.disabled = true;
    btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Exporting...';
    
    console.log('Starting PDF export...');
    
    const url = '<?= base_url('user/get_batch_sends_data/' . (int)$campaign->id . '/' . (int)$batch->id) ?>';
    const params = new URLSearchParams({
        start: 0,
        length: Math.min(totalRecords, 10000),
        draw: 1
    });
    
    fetch(`${url}?${params.toString()}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            console.log('PDF data received:', result.data.length, 'records');
            
            if (!result.data || result.data.length === 0) {
                alert('No data available to export');
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-file-earmark-pdf-fill"></i> Export PDF';
                return;
            }
                
                const { jsPDF } = window.jspdf;
                const doc = new jsPDF('l', 'mm', 'a4'); // Landscape for more columns
                
                // Header
                doc.setFontSize(18);
                doc.setTextColor(59, 130, 246);
                doc.text('Delivery <?= (int)$batch->batch_number ?> - Complete Report', 14, 15);
                
                doc.setFontSize(10);
                doc.setTextColor(100, 100, 100);
                doc.text('Campaign: <?= addslashes($campaign->name) ?>', 14, 23);
                doc.text('Generated: <?= date('M d, Y H:i') ?>', 14, 28);
                doc.text('Total Records: ' + result.recordsFiltered, 14, 33);
                doc.text('Scheduled: <?= date('M d, Y H:i', strtotime($batch->scheduled_for ?? '')) ?>', 14, 38);
                
                // Prepare table data
                const tableData = [];
                result.data.forEach((row) => {
                    tableData.push([
                        row[0] || '',
                        row[1] || 'N/A',
                        row[2] || 'N/A',
                        row[3] || 'N/A',
                        row[4] || 'pending',
                        row[5] || 'N/A'
                    ]);
                });
                
                // Add table
                doc.autoTable({
                    head: [['#', 'Mobile', 'Name', 'Email', 'Status', 'Username']],
                    body: tableData,
                    startY: 43,
                    headStyles: { 
                        fillColor: [59, 130, 246],
                        textColor: [255, 255, 255],
                        fontSize: 9,
                        fontStyle: 'bold'
                    },
                    styles: { 
                        fontSize: 8,
                        cellPadding: 3
                    },
                    alternateRowStyles: {
                        fillColor: [245, 247, 250]
                    },
                    margin: { left: 14, right: 14 }
                });
                
            console.log('Generating PDF...');
            const filename = 'Delivery_<?= (int)$batch->batch_number ?>_<?= date('Y-m-d') ?>_Complete.pdf';
            doc.save(filename);
            
            console.log('PDF export complete!');
            alert(`Successfully exported ${result.data.length.toLocaleString()} records to PDF!`);
            
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-file-earmark-pdf-fill"></i> Export PDF';
        })
        .catch(error => {
            console.error('PDF export error:', error);
            alert('Error exporting PDF: ' + error.message + '\n\nTry refreshing the page and export again.');
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-file-earmark-pdf-fill"></i> Export PDF';
        });
}
</script>
