<?php
$defaultCampaignType = isset($campaign->type) ? $campaign->type : 'Custom';
$campaignMeta = campaign_type_meta($defaultCampaignType);
$imageExtensions = array('jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp');
?>

<div class="page-title d-flex justify-content-between align-items-center">
    <div>
        <h2 class="mb-1">
            <i class="bi bi-megaphone-fill"></i> <?= html_escape($campaign->name) ?>
        </h2>
        <span class="badge <?= $campaignMeta['badge'] ?>">
            <i class="bi <?= $campaignMeta['icon'] ?> me-1"></i><?= html_escape($campaignMeta['label']) ?>
        </span>
    </div>
    <a href="<?= base_url('user/campaigns') ?>" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left"></i> Back
    </a>
</div>

<div class="row mb-4">
    <div class="col-md-3">
        <div class="stat-card primary">
            <i class="bi bi-check2-square stat-icon"></i>
            <div class="stat-label">Total Assigned</div>
            <div class="stat-value"><?= number_format($total_assigned) ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card success">
            <i class="bi bi-check-circle-fill stat-icon"></i>
            <div class="stat-label">Successfully Sent</div>
            <div class="stat-value"><?= number_format($total_sent) ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card danger">
            <i class="bi bi-x-circle-fill stat-icon"></i>
            <div class="stat-label">Send Failed</div>
            <div class="stat-value"><?= number_format($total_failed) ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card warning">
            <i class="bi bi-hourglass-split stat-icon"></i>
            <div class="stat-label">Pending</div>
            <div class="stat-value"><?= number_format($total_pending) ?></div>
        </div>
    </div>
</div>

<div class="alert alert-info">
    <i class="bi bi-info-circle-fill"></i> Direct sending from the user panel is disabled. Messages are scheduled automatically by the admin team.
</div>

<div class="panel mb-4">
    <div class="panel-header d-flex justify-content-between align-items-center">
        <span><i class="bi bi-calendar-week"></i> Broadcast Schedule</span>
        <div>
            <?php if (!empty($message_schedules)): ?>
                <button type="button" class="view-all-btn me-2" data-bs-toggle="modal" data-bs-target="#allMessagesModal">
                    <i class="bi bi-envelope-open"></i> See All Messages
                </button>
            <?php endif; ?>
            <span class="badge bg-secondary">Auto Managed</span>
        </div>
    </div>
    <div class="panel-body">
        <div class="panel-inner">
        <?php if (empty($message_schedules)): ?>
            <p class="text-muted mb-0">
                <i class="bi bi-calendar-x" style="font-size: 48px; display: block; margin-bottom: 12px; opacity: 0.3;"></i>
                No message schedules are available for this campaign yet.
            </p>
        <?php else: ?>
            <?php foreach ($message_schedules as $schedule): ?>
                <?php
                    $scheduleMeta = campaign_type_meta(isset($schedule->campaign_type) ? $schedule->campaign_type : $defaultCampaignType);
                    $rawContent = trim((string) $schedule->message_content);
                    $previewHint = $scheduleMeta['preview'];
                    $imageUrl = null;
                    $attachmentUrl = null;
                    $caption = $rawContent;

                    if (!empty($schedule->attachment)) {
                        $attachmentUrl = (strpos($schedule->attachment, 'http') === 0) ? $schedule->attachment : base_url($schedule->attachment);
                    }

                    if ($previewHint === 'image') {
                        if (preg_match('/https?:\/\/\S+/i', $rawContent, $matches)) {
                            $candidate = rtrim($matches[0], '.,)');
                            $path = parse_url($candidate, PHP_URL_PATH);
                            $extension = $path ? strtolower(pathinfo($path, PATHINFO_EXTENSION)) : '';

                            if ($path && in_array($extension, $imageExtensions, true)) {
                                $imageUrl = $candidate;
                                $caption = trim(str_replace($candidate, '', $rawContent));
                            }
                        }

                        if (!$imageUrl) {
                            $previewHint = 'text';
                        }
                    }

                    $textPreviewClass = 'text-preview';

                    if ($previewHint === 'whatsapp') {
                        $textPreviewClass = 'whatsapp-preview';
                    } elseif ($previewHint === 'sms') {
                        $textPreviewClass = 'sms-preview';
                    }
                ?>
                <div class="mb-4">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <div class="d-flex align-items-center gap-2 flex-wrap">
                                <h6 class="mb-1">Sender ID: <?= html_escape($schedule->sender_id ?: 'N/A') ?></h6>
                                <span class="badge <?= $scheduleMeta['badge'] ?>"><i class="bi <?= $scheduleMeta['icon'] ?> me-1"></i><?= html_escape($scheduleMeta['label']) ?></span>
                            </div>
                            <!-- <p class="text-muted small mb-2">Created <?= date('M d, Y H:i', strtotime($schedule->created_at)) ?> by <?= html_escape($schedule->admin_name) ?> · Audience <?= number_format($schedule->total_recipients) ?></p> -->
                        </div>
                        <!-- <span class="badge bg-info text-dark">Schedule #<?= $schedule->id ?></span> -->
                         <br>
                    </div>
                    <div class="mb-3">
                        <button type="button" class="btn-outline" data-bs-toggle="modal" data-bs-target="#scheduleMessageModal_<?= $schedule->id ?>">
                            <i class="bi bi-eye-fill"></i> Show Message
                        </button>
                        <?php
                        // Find first sent batch for view sends link
                        $firstSentBatch = null;
                        foreach ($schedule->batches as $batch) {
                            if ($batch->status === 'sent') {
                                $firstSentBatch = $batch;
                                break;
                            }
                        }
                        ?>
                        <?php if ($firstSentBatch): ?>
                            <a href="<?= base_url('user/campaign_sends/' . $campaign->id . '/' . $firstSentBatch->id) ?>" 
                               class="btn-outline ms-2">
                                <i class="bi bi-send-check"></i> See Delivery Status
                            </a>
                        <?php endif; ?>
                    </div>
                    <div class="schedule-table-wrapper">
                        <div class="row g-3 schedule-batches">
                            <?php foreach ($schedule->batches as $batch): ?>
                                <div class="col-12 col-md-6">
                                    <div class="schedule-batch-card p-3">
                                        <div class="d-flex align-items-start justify-content-between">
                                            <div>
                                                <div class="fw-bold">Delivery <?= htmlspecialchars($batch->batch_number) ?></div>
                                                <div class="small text-muted">Audience <?= number_format($batch->batch_size) ?></div>
                                            </div>
                                            <div class="text-end">
                                                <div>
                                                    <?php if ($batch->status === 'sent'): ?>
                                                        <span class="badge badge-status-sent">Sent</span>
                                                        <?php if (!empty($batch->sent_at)): ?>
                                                            <div class="small text-muted mt-1"><?= date('M d, Y H:i', strtotime($batch->sent_at)) ?></div>
                                                        <?php endif; ?>
                                                    <?php elseif ($batch->status === 'processing'): ?>
                                                        <span class="badge badge-status-pending">In Progress</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-info">Scheduled</span>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="mt-2 d-flex flex-column gap-2">
                                                    <a href="<?= base_url('user/campaign_sends/' . $campaign->id . '/' . $batch->id) ?>" class="btn-outline">
                                                        <i class="bi bi-list-check"></i> View Details
                                                    </a>
                                                    <?php if ($batch->status === 'sent'): ?>
                                                        <!-- <button onclick="exportBatchExcel(<?= $campaign->id ?>, <?= $batch->id ?>, <?= $batch->batch_number ?>)" class="btn-outline btn-sm" style="font-size: 0.8rem; padding: 0.375rem 0.75rem;">
                                                            <i class="bi bi-file-earmark-excel-fill"></i> Export Excel
                                                        </button> -->
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="mt-2 small text-muted">Scheduled for: <?= date('M d, Y H:i', strtotime($batch->scheduled_for)) ?></div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <!-- <p class="text-muted small">Status updates automatically when the scheduled time arrives. No manual action is needed on the user side.</p> -->
                </div>

                <div class="modal fade" id="scheduleMessageModal_<?= $schedule->id ?>" tabindex="-1" aria-labelledby="scheduleMessageModalLabel_<?= $schedule->id ?>" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="scheduleMessageModalLabel_<?= $schedule->id ?>"><i class="bi <?= $scheduleMeta['icon'] ?> me-2"></i>Broadcast Message Preview</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <p class="text-muted small mb-3">This is the exact message delivered to the masked audience for this schedule.</p>
                                <?php if (!empty($attachmentUrl)): ?>
                                    <?php $attExt = strtolower(pathinfo($attachmentUrl, PATHINFO_EXTENSION)); ?>
                                    <?php if (in_array($attExt, ['jpg','jpeg','png','gif','bmp','webp'], true)): ?>
                                        <div class="message-preview image-preview mb-3">
                                            <img src="<?= html_escape($attachmentUrl) ?>" alt="Scheduled image preview">
                                        </div>
                                        <div class="small mb-3">
                                            <i class="bi bi-link-45deg"></i> <a href="<?= html_escape($attachmentUrl) ?>" target="_blank" rel="noopener">Open image in new tab</a>
                                        </div>
                                        <?php if ($caption !== ''): ?>
                                            <div class="message-preview text-preview mb-0">
                                                <?= nl2br(html_escape($caption)) ?>
                                            </div>
                                        <?php endif; ?>
                                    <?php elseif ($attExt === 'pdf'): ?>
                                        <div class="message-preview image-preview mb-3">
                                            <embed src="<?= html_escape($attachmentUrl) ?>" type="application/pdf" width="100%" height="400px" />
                                        </div>
                                        <div class="small mb-3">
                                            <i class="bi bi-link-45deg"></i> <a href="<?= html_escape($attachmentUrl) ?>" target="_blank" rel="noopener">Open PDF in new tab</a>
                                        </div>
                                    <?php else: ?>
                                        <div class="message-preview text-preview mb-0">
                                            <i class="bi bi-paperclip"></i> <a href="<?= html_escape($attachmentUrl) ?>" target="_blank" rel="noopener">Download attachment</a>
                                        </div>
                                    <?php endif; ?>
                                <?php elseif ($previewHint === 'image' && $imageUrl): ?>
                                    <div class="message-preview image-preview mb-3">
                                        <img src="<?= html_escape($imageUrl) ?>" alt="Scheduled image preview">
                                    </div>
                                    <div class="small mb-3">
                                        <i class="bi bi-link-45deg"></i> <a href="<?= html_escape($imageUrl) ?>" target="_blank" rel="noopener">Open image in new tab</a>
                                    </div>
                                    <?php if ($caption !== ''): ?>
                                        <div class="message-preview text-preview mb-0">
                                            <?= nl2br(html_escape($caption)) ?>
                                        </div>
                                    <?php endif; ?>
                                <?php elseif ($previewHint === 'status'): ?>
                                    <div class="message-preview status-preview mb-0">
                                        <div class="status-card">
                                            <?= nl2br(html_escape($rawContent)) ?>
                                        </div>
                                    </div>
                                <?php else: ?>
                                    <div class="message-preview <?= $textPreviewClass ?> mb-0">
                                        <?= nl2br(html_escape($rawContent)) ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
        </div>
    </div>
</div>

<!-- All Messages Modal -->
<div class="modal fade" id="allMessagesModal" tabindex="-1" aria-labelledby="allMessagesModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="allMessagesModalLabel"><i class="bi bi-envelope-open"></i> All Broadcast Messages</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <?php if (!empty($message_schedules)): ?>
                    <?php foreach ($message_schedules as $idx => $schedule): ?>
                        <?php
                            $scheduleMeta = campaign_type_meta(isset($schedule->campaign_type) ? $schedule->campaign_type : $defaultCampaignType);
                            $rawContent = trim((string) $schedule->message_content);
                            $previewHint = $scheduleMeta['preview'];
                            $imageUrl = null;
                            $attachmentUrl = null;
                            $caption = $rawContent;

                            if (!empty($schedule->attachment)) {
                                $attachmentUrl = (strpos($schedule->attachment, 'http') === 0) ? $schedule->attachment : base_url($schedule->attachment);
                            }

                            if ($previewHint === 'image') {
                                if (preg_match('/https?:\/\/\S+/i', $rawContent, $matches)) {
                                    $candidate = rtrim($matches[0], '.,)');
                                    $path = parse_url($candidate, PHP_URL_PATH);
                                    $extension = $path ? strtolower(pathinfo($path, PATHINFO_EXTENSION)) : '';

                                    if ($path && in_array($extension, $imageExtensions, true)) {
                                        $imageUrl = $candidate;
                                        $caption = trim(str_replace($candidate, '', $rawContent));
                                    }
                                }

                                if (!$imageUrl) {
                                    $previewHint = 'text';
                                }
                            }

                            if ($previewHint === 'sms') {
                                $textPreviewClass = 'sms-preview';
                            } elseif ($previewHint === 'whatsapp') {
                                $textPreviewClass = 'whatsapp-preview';
                            } else {
                                $textPreviewClass = 'text-preview';
                            }
                        ?>
                        <div class="message-card mb-3 p-3">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <div>
                                    <h6 class="mb-1">Schedule #<?= $schedule->id ?> - <?= html_escape($schedule->sender_id ?: 'N/A') ?></h6>
                                    <span class="badge <?= $scheduleMeta['badge'] ?>"><i class="bi <?= $scheduleMeta['icon'] ?> me-1"></i><?= html_escape($scheduleMeta['label']) ?></span>
                                    <p class="text-muted small mb-0 mt-1">Created <?= date('M d, Y H:i', strtotime($schedule->created_at)) ?> · Audience <?= number_format($schedule->total_recipients) ?></p>
                                </div>
                            </div>
                            
                            <?php if (!empty($attachmentUrl)): ?>
                                <?php $attExt = strtolower(pathinfo($attachmentUrl, PATHINFO_EXTENSION)); ?>
                                <?php if (in_array($attExt, ['jpg','jpeg','png','gif','bmp','webp'], true)): ?>
                                    <div class="message-preview image-preview mb-2">
                                        <img src="<?= html_escape($attachmentUrl) ?>" alt="Message image" style="max-width: 100%; border-radius: 0.5rem;">
                                    </div>
                                    <?php if ($caption !== ''): ?>
                                        <div class="message-preview text-preview">
                                            <?= nl2br(html_escape($caption)) ?>
                                        </div>
                                    <?php endif; ?>
                                <?php elseif ($attExt === 'pdf'): ?>
                                    <div class="message-preview image-preview mb-2">
                                        <embed src="<?= html_escape($attachmentUrl) ?>" type="application/pdf" width="100%" height="350px" />
                                    </div>
                                <?php else: ?>
                                    <div class="message-preview text-preview">
                                        <i class="bi bi-paperclip"></i> <a href="<?= html_escape($attachmentUrl) ?>" target="_blank" rel="noopener">Download attachment</a>
                                    </div>
                                <?php endif; ?>
                                <?php elseif ($previewHint === 'image' && $imageUrl): ?>
                                    <div class="message-preview image-preview mb-2">
                                        <img src="<?= html_escape($imageUrl) ?>" alt="Message image" style="max-width: 100%; border-radius: 0.5rem;">
                                    </div>
                                    <?php if ($caption !== ''): ?>
                                        <div class="message-preview text-preview">
                                            <?= nl2br(html_escape($caption)) ?>
                                        </div>
                                    <?php endif; ?>
                                <?php elseif ($previewHint === 'status'): ?>
                                <div class="message-preview status-preview">
                                    <div class="status-card">
                                        <?= nl2br(html_escape($rawContent)) ?>
                                    </div>
                                </div>
                            <?php else: ?>
                                <div class="message-preview <?= $textPreviewClass ?>">
                                    <?= nl2br(html_escape($rawContent)) ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="text-muted text-center mb-0">No messages available.</p>
                <?php endif; ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<style>
.message-preview {
    border: 1px solid #dee2e6;
    border-radius: 0.75rem;
    padding: 1rem;
    background-color: #f8f9fa;
    position: relative;
}

.message-preview.text-preview,
.message-preview.sms-preview,
.message-preview.whatsapp-preview {
    white-space: pre-wrap;
}

.message-preview.sms-preview {
    background-color: #eef2f7;
    border-color: #d0d7de;
}

.message-preview.whatsapp-preview {
    background-color: #dcf8c6;
    border-color: #34b7f1;
}

.message-preview.image-preview {
    background-color: #f3f6f9;
    border: 1px dashed #c5d1e3;
}

.message-preview.image-preview img {
    max-width: 100%;
    border-radius: 0.75rem;
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}

.message-preview.status-preview {
    border: none;
    background: transparent;
    padding: 0;
}

.status-card {
    border-radius: 1rem;
    padding: 2rem 1.5rem;
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    color: #fff;
    font-weight: 600;
    text-align: center;
    box-shadow: 0 10px 20px rgba(79, 172, 254, 0.35);
    position: relative;
}

.schedule-table-actions .btn {
    min-width: 90px;
}

.schedule-table-wrapper .dt-buttons {
    display: none;
}

/* Schedule batch card */
.schedule-batch-card {
    background: #fff;
    border-radius: 10px;
    border: 1px solid var(--border-color);
    box-shadow: 0 6px 18px rgba(16,24,40,0.04);
}
.schedule-batch-card .badge-status-sent {
    background: linear-gradient(135deg, var(--success-color) 0%, #059669 100%);
    color: green;
    padding: 6px 10px;
    border-radius: 8px;
    font-weight:700;
}
.schedule-batch-card .badge-status-pending {
    background: linear-gradient(135deg, var(--warning-color) 0%, #d97706 100%);
    color: #fff;
    padding: 6px 10px;
    border-radius: 8px;
    font-weight:700;
}

/* Compact message card for All Messages modal */
.message-card {
    background: #fff;
    border-radius: 12px;
    border: 1px solid var(--border-color);
    box-shadow: 0 8px 30px rgba(16,24,40,0.06);
}
.message-card .message-header {
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
}
.message-card .message-meta { color: var(--text-secondary); font-size:13px; }
.message-card .message-actions a { margin-left:8px; }
.message-card .message-preview.image-preview img { max-height: 320px; object-fit: cover; border-radius: 0.5rem; box-shadow: 0 12px 24px rgba(0,0,0,0.12); }
</style>

<!-- Modal for viewing batch sends -->
<div class="modal fade" id="batchSendsModal" tabindex="-1" aria-labelledby="batchSendsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="batchSendsModalLabel"><i class="bi bi-bar-chart"></i> Send Statistics</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="batchSendsContent">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">Loading send data...</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<script>
// Wait for jQuery to be loaded (deferred execution)
(function() {
    function initializePage() {
        if (typeof jQuery === 'undefined') {
            setTimeout(initializePage, 50);
            return;
        }
        
        jQuery(document).ready(function($) {
    if ($('#campaignDataTable').length) {
        $('#campaignDataTable').DataTable({
            pageLength: 20,
            dom: 'Bfrtip',
            buttons: [
                {
                    extend: 'excelHtml5',
                    title: 'Masked Campaign Data'
                },
                {
                    extend: 'pdfHtml5',
                    title: 'Masked Campaign Data',
                    orientation: 'landscape',
                    pageSize: 'A4'
                },
                {
                    extend: 'print',
                    title: 'Masked Campaign Data'
                }
            ],
            order: [[0, 'asc']],
            columnDefs: [
                { targets: [4], orderable: false }
            ]
        });
    }

    window.scheduleTables = window.scheduleTables || {};

    $('.user-schedule-table').each(function() {
        const $table = $(this);
        const title = $table.data('title') || 'Broadcast Schedule';
        const tableId = $table.attr('id');

        const dataTable = $table.DataTable({
            dom: 'Bfrtip',
            buttons: [
                { extend: 'excelHtml5', title: title, className: 'export-excel' },
                { extend: 'pdfHtml5', title: title, orientation: 'landscape', pageSize: 'A4', className: 'export-pdf' },
                { extend: 'print', title: title, className: 'export-print' }
            ],
            order: [[2, 'asc']],
            paging: false,
            searching: false,
            info: false
        });

        window.scheduleTables[tableId] = dataTable;
    });

    $('.js-export-table').on('click', function() {
        const tableId = $(this).data('table');
        const exportType = $(this).data('export');
        const dataTable = window.scheduleTables ? window.scheduleTables[tableId] : null;

        if (!dataTable) {
            return;
        }

        if (exportType === 'excel') {
            dataTable.button('.export-excel').trigger();
        } else if (exportType === 'pdf') {
            dataTable.button('.export-pdf').trigger();
        } else if (exportType === 'print') {
            dataTable.button('.export-print').trigger();
        }
    });

    // Handle view sends button click - using event delegation
    $(document).on('click', '.view-sends-btn', function() {
        console.log('View sends button clicked');
        const batchId = $(this).data('batch-id');
        const batchNumber = $(this).data('batch-number');
        const scheduleId = $(this).data('schedule-id');
        const campaignId = <?= $campaign->id ?>;
        
        console.log('Batch ID:', batchId, 'Schedule ID:', scheduleId, 'Campaign ID:', campaignId);
        
        // Show modal
        const modal = new bootstrap.Modal(document.getElementById('batchSendsModal'));
        $('#batchSendsModalLabel').html('<i class="bi bi-bar-chart"></i> Delivery ' + batchNumber + ' - Send Statistics');
        
        // Reset content
        $('#batchSendsContent').html(`
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">Loading send data...</p>
            </div>
        `);
        
        modal.show();
        
        // Load batch sends data via AJAX
        $.ajax({
            url: '<?= base_url('user/get_batch_sends') ?>',
            type: 'POST',
            data: {
                batch_id: batchId,
                schedule_id: scheduleId,
                campaign_id: campaignId
            },
            dataType: 'json',
            success: function(response) {
                console.log('AJAX response:', response);
                if (response.success) {
                    displayBatchSends(response.data);
                } else {
                    $('#batchSendsContent').html(`
                        <div class="alert alert-warning">
                            <i class="bi bi-exclamation-triangle"></i> ${response.message || 'Unable to load send data.'}
                        </div>
                    `);
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error:', status, error);
                console.error('Response:', xhr.responseText);
                $('#batchSendsContent').html(`
                    <div class="alert alert-danger">
                        <i class="bi bi-x-circle"></i> Error loading send data. Please try again.
                    </div>
                `);
            }
        });
    });
    
    function displayBatchSends(data) {
        let html = `
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="stat-card primary">
                        <h6 class="text-muted">Total Assigned</h6>
                        <h3>${data.stats.total.toLocaleString()}</h3>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card success">
                        <h6 class="text-muted">Successfully Sent</h6>
                        <h3 class="text-success">${data.stats.sent.toLocaleString()}</h3>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card danger">
                        <h6 class="text-muted">Failed</h6>
                        <h3 class="text-danger">${data.stats.failed.toLocaleString()}</h3>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card info">
                        <h6 class="text-muted">Success Rate</h6>
                        <h3 class="text-info">${data.stats.success_rate}%</h3>
                    </div>
                </div>
            </div>
            
            <h6 class="mb-3"><i class="bi bi-people"></i> Sends by User</h6>
            <div class="table-responsive">
                <table class="table table-sm table-hover">
                    <thead>
                        <tr>
                            <th>User</th>
                            <th>Total Delivered</th>
                            <th>Successful</th>
                            <th>Failed</th>
                            <th>Success Rate</th>
                        </tr>
                    </thead>
                    <tbody>
        `;
        
        if (data.user_stats && data.user_stats.length > 0) {
            data.user_stats.forEach(function(user) {
                html += `
                    <tr>
                        <td><strong>${user.username}</strong></td>
                        <td>${user.total.toLocaleString()}</td>
                        <td><span class="badge bg-success">${user.sent.toLocaleString()}</span></td>
                        <td><span class="badge bg-danger">${user.failed.toLocaleString()}</span></td>
                        <td>${user.success_rate}%</td>
                    </tr>
                `;
            });
        } else {
            html += `
                <tr>
                    <td colspan="5" class="text-center text-muted">No send data available</td>
                </tr>
            `;
        }
        
        html += `
                    </tbody>
                </table>
            </div>
        `;
        
        $('#batchSendsContent').html(html);
    }

    // Export batch data to Excel
    window.exportBatchExcel = function(campaignId, batchId, batchNumber) {
        const btn = event.target;
        const originalHTML = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Exporting...';
        
        // Fetch data from server with proper parameters
        const url = `<?= base_url('user/get_batch_sends_data/') ?>${campaignId}/${batchId}`;
        const params = new URLSearchParams({
            start: 0,
            length: 999999,
            draw: 1
        });
        
        fetch(`${url}?${params.toString()}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(result => {
                if (!result.data || result.data.length === 0) {
                    alert('No data available to export for this delivery');
                    btn.disabled = false;
                    btn.innerHTML = originalHTML;
                    return;
                }
                
                // Prepare Excel data
                const wsData = [
                    ['#', 'Mobile', 'Name', 'Email', 'Status', 'Username']
                ];
                
                result.data.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'
                    ]);
                });
                
                // Create 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
                ];
                
                // Create workbook and save
                const wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, ws, `Delivery ${batchNumber}`);
                
                const today = new Date().toISOString().split('T')[0];
                const filename = `Delivery_${batchNumber}_${today}.xlsx`;
                XLSX.writeFile(wb, filename);
                
                btn.disabled = false;
                btn.innerHTML = originalHTML;
            })
            .catch(error => {
                console.error('Export error:', error);
                alert('Error exporting data. Please try again or contact support.');
                btn.disabled = false;
                btn.innerHTML = originalHTML;
            });
    };
        }); // End jQuery ready
    }
    initializePage();
})();
</script>
