<div class="page-title d-flex justify-content-between align-items-center">
    <h2><i class="bi bi-megaphone"></i> Campaign Management</h2>
    <div>
        <button onclick="exportCampaigns()" class="btn btn-success me-2" id="exportCampaignsBtn">
            <i class="bi bi-download"></i> Export List
        </button>
        <a href="<?= base_url('admin/campaign_create') ?>" class="btn btn-primary">
            <i class="bi bi-plus-circle"></i> Create New Campaign
        </a>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Type</th>
                        <th>Fail %</th>
                        <th>Assigned</th>
                        <th>Sent</th>
                        <th>Failed</th>
                        <th>Remaining</th>
                        <th>Status</th>
                        <th>Created By</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($campaigns)): ?>
                        <?php foreach ($campaigns as $campaign): ?>
                            <tr>
                                <td><?= $campaign->id ?></td>
                                <td><strong><?= $campaign->name ?></strong></td>
                                <td><span class="badge bg-info"><?= $campaign->type ?></span></td>
                                <td><?= $campaign->fail_percentage ?>%</td>
                                <td><?= number_format($campaign->total_assigned) ?></td>
                                <td><span class="text-success"><?= number_format($campaign->total_sent) ?></span></td>
                                <td><span class="text-danger"><?= number_format($campaign->total_failed) ?></span></td>
                                <td><?= number_format($campaign->total_remaining) ?></td>
                                <td>
                                    <?php
                                    $badge_class = [
                                        'active' => 'bg-success',
                                        'paused' => 'bg-warning',
                                        'stopped' => 'bg-danger',
                                        'completed' => 'bg-secondary'
                                    ];
                                    ?>
                                    <span class="badge <?= $badge_class[$campaign->status] ?>"><?= ucfirst($campaign->status) ?></span>
                                </td>
                                <td><?= $campaign->creator_name ?></td>
                                <td>
                                    <a href="<?= base_url('admin/campaign_view/' . $campaign->id) ?>" class="btn btn-sm btn-primary" title="View Details">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                    <a href="<?= base_url('admin/campaign_edit/' . $campaign->id) ?>" class="btn btn-sm btn-warning" title="Edit">
                                        <i class="bi bi-pencil"></i>
                                    </a>
                                    <a href="<?= base_url('admin/campaign_delete/' . $campaign->id) ?>" class="btn btn-sm btn-danger" title="Delete" onclick="return confirm('Are you sure you want to delete this campaign? This will also remove all associated data.')">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="11" class="text-center">No campaigns found</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($pagination['total_pages'] > 1): ?>
            <nav>
                <ul class="pagination justify-content-center">
                    <?php for ($i = 1; $i <= $pagination['total_pages']; $i++): ?>
                        <li class="page-item <?= $i == $pagination['current_page'] ? 'active' : '' ?>">
                            <a class="page-link" href="<?= $pagination['base_url'] ?>?page=<?= $i ?>"><?= $i ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
        <?php endif; ?>
    </div>
</div>

<!-- Include XLSX library for Excel export -->
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>

<script>
function exportCampaigns() {
    const btn = document.getElementById('exportCampaignsBtn');
    const originalHTML = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Exporting...';
    
    try {
        // Prepare data from table
        const campaigns = <?= json_encode(array_map(function($c) {
            return [
                'ID' => $c->id,
                'Name' => $c->name,
                'Type' => $c->type,
                'Fail %' => $c->fail_percentage,
                'Total Assigned' => $c->total_assigned,
                'Total Sent' => $c->total_sent,
                'Total Failed' => $c->total_failed,
                'Total Remaining' => $c->total_remaining,
                'Success Rate' => $c->total_assigned > 0 ? round(($c->total_sent / $c->total_assigned) * 100, 2) . '%' : '0%',
                'Status' => ucfirst($c->status),
                'Created By' => $c->creator_name,
                'Created At' => date('Y-m-d H:i:s', strtotime($c->created_at))
            ];
        }, $campaigns ?? [])) ?>;
        
        if (campaigns.length === 0) {
            alert('No campaigns to export');
            btn.disabled = false;
            btn.innerHTML = originalHTML;
            return;
        }
        
        // Create worksheet data
        const wsData = [
            ['ID', 'Name', 'Type', 'Fail %', 'Total Assigned', 'Total Sent', 'Total Failed', 'Total Remaining', 'Success Rate', 'Status', 'Created By', 'Created At']
        ];
        
        campaigns.forEach(campaign => {
            wsData.push([
                campaign['ID'],
                campaign['Name'],
                campaign['Type'],
                campaign['Fail %'],
                campaign['Total Assigned'],
                campaign['Total Sent'],
                campaign['Total Failed'],
                campaign['Total Remaining'],
                campaign['Success Rate'],
                campaign['Status'],
                campaign['Created By'],
                campaign['Created At']
            ]);
        });
        
        // Create worksheet
        const ws = XLSX.utils.aoa_to_sheet(wsData);
        
        // Set column widths
        ws['!cols'] = [
            {wch: 5},   // ID
            {wch: 30},  // Name
            {wch: 12},  // Type
            {wch: 8},   // Fail %
            {wch: 15},  // Total Assigned
            {wch: 15},  // Total Sent
            {wch: 15},  // Total Failed
            {wch: 15},  // Total Remaining
            {wch: 13},  // Success Rate
            {wch: 10},  // Status
            {wch: 20},  // Created By
            {wch: 20}   // Created At
        ];
        
        // Create workbook
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Campaigns');
        
        // Generate filename with timestamp
        const timestamp = new Date().toISOString().split('T')[0];
        const filename = `campaigns_list_${timestamp}.xlsx`;
        
        // Download
        XLSX.writeFile(wb, filename);
        
        btn.disabled = false;
        btn.innerHTML = originalHTML;
        
    } catch (error) {
        console.error('Export error:', error);
        alert('Error exporting campaigns: ' + error.message);
        btn.disabled = false;
        btn.innerHTML = originalHTML;
    }
}
</script>
