<div class="page-title d-flex justify-content-between align-items-center">
    <h2><i class="bi bi-megaphone"></i> <?= $campaign->name ?></h2>
    <div>
        <button onclick="exportCampaignDetails()" class="btn btn-success me-2" id="exportCampaignBtn">
            <i class="bi bi-download"></i> Export Details
        </button>
        <select class="form-select d-inline-block w-auto" id="campaignStatus" data-campaign-id="<?= $campaign->id ?>">
            <option value="active" <?= $campaign->status == 'active' ? 'selected' : '' ?>>Active</option>
            <option value="paused" <?= $campaign->status == 'paused' ? 'selected' : '' ?>>Paused</option>
            <option value="stopped" <?= $campaign->status == 'stopped' ? 'selected' : '' ?>>Stopped</option>
            <option value="completed" <?= $campaign->status == 'completed' ? 'selected' : '' ?>>Completed</option>
        </select>
        <a href="<?= base_url('admin/campaigns') ?>" class="btn btn-secondary ms-2">
            <i class="bi bi-arrow-left"></i> Back
        </a>
    </div>
</div>

<div class="row">
    <div class="col-md-3">
        <div class="stat-card primary">
            <h6 class="text-muted">Total Assigned</h6>
            <h3><?= number_format($campaign->total_assigned) ?></h3>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card success">
            <h6 class="text-muted">Total Sent</h6>
            <h3 class="text-success"><?= number_format($campaign->total_sent) ?></h3>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card danger">
            <h6 class="text-muted">Total Failed</h6>
            <h3 class="text-danger"><?= number_format($campaign->total_failed) ?></h3>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card warning">
            <h6 class="text-muted">Remaining</h6>
            <h3><?= number_format($campaign->total_remaining) ?></h3>
        </div>
    </div>
</div>

<div class="row mt-4">
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-info-circle"></i> Campaign Details</h5>
            </div>
            <div class="card-body">
                <table class="table table-borderless">
                    <tr>
                        <th width="40%">Campaign Type:</th>
                        <td><span class="badge bg-info"><?= $campaign->type ?></span></td>
                    </tr>
                    <tr>
                        <th>Fail Percentage:</th>
                        <td><?= $campaign->fail_percentage ?>%</td>
                    </tr>
                    <tr>
                        <th>Created By:</th>
                        <td><?= $campaign->creator_name ?></td>
                    </tr>
                    <tr>
                        <th>Created At:</th>
                        <td><?= date('M d, Y h:i A', strtotime($campaign->created_at)) ?></td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-people"></i> Assigned Users (<?= count($assigned_users) ?>)</h5>
                <button class="btn btn-sm btn-light" data-bs-toggle="modal" data-bs-target="#assignUsersModal">
                    <i class="bi bi-plus"></i> Assign Users
                </button>
            </div>
            <div class="card-body">
                <?php if (!empty($assigned_users)): ?>
                    <div class="list-group">
                        <?php foreach ($assigned_users as $user): ?>
                            <div class="list-group-item d-flex justify-content-between align-items-center">
                                <span><i class="bi bi-person-circle"></i> <?= $user->username ?></span>
                                <button class="btn btn-sm btn-success" onclick="showAssignDataModal(<?= $campaign->id ?>, <?= $user->id ?>, '<?= $user->username ?>')">
                                    <i class="bi bi-database-add"></i> Assign Data
                                </button>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <p class="text-muted text-center">No users assigned yet</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Assign Users Modal -->
<div class="modal fade" id="assignUsersModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Assign Users to Campaign</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <?php if (!empty($available_users)): ?>
                    <form id="assignUsersForm">
                        <input type="hidden" name="campaign_id" value="<?= $campaign->id ?>">
                        <?php foreach ($available_users as $user): ?>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="user_ids[]" value="<?= $user->id ?>" id="user_<?= $user->id ?>">
                                <label class="form-check-label" for="user_<?= $user->id ?>">
                                    <?= $user->username ?> (<?= $user->email ?>)
                                </label>
                            </div>
                        <?php endforeach; ?>
                    </form>
                <?php else: ?>
                    <p class="text-muted">All users are already assigned to this campaign.</p>
                <?php endif; ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <?php if (!empty($available_users)): ?>
                    <button type="button" class="btn btn-primary" onclick="assignUsers()">Assign Selected</button>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Assign Data Modal -->
<div class="modal fade" id="assignDataModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Assign Data to User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" id="assignDataCloseBtn"></button>
            </div>
            <div class="modal-body">
                <form id="assignDataForm">
                    <input type="hidden" name="campaign_id" id="assign_campaign_id">
                    <input type="hidden" name="user_id" id="assign_user_id">
                    
                    <div class="mb-3">
                        <label class="form-label"><strong>User:</strong></label>
                        <p class="form-control-plaintext" id="assign_username"></p>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Total Number of Records *</label>
                        <input type="number" class="form-control" name="count" id="assign_count" min="1" required>
                        <small class="text-muted">
                            Note: System will auto-add extra records based on fail percentage (<?= $campaign->fail_percentage ?>%)
                        </small>
                    </div>
                </form>
                
                <!-- Progress Section (hidden initially) -->
                <div id="assignProgressSection" style="display: none;">
                    <hr>
                    <h6><i class="bi bi-hourglass-split"></i> Processing Large Dataset...</h6>
                    <div class="progress mb-2" style="height: 25px;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" id="assignProgressBar" role="progressbar" style="width: 0%">0%</div>
                    </div>
                    <div class="d-flex justify-content-between small text-muted">
                        <span id="assignProgressText">Starting...</span>
                        <span id="assignProgressCount">0 / 0 records</span>
                    </div>
                    <div class="alert alert-info mt-3 small">
                        <i class="bi bi-info-circle"></i> Please do not close this window. Large datasets are processed in batches of 10,000 records to prevent timeouts.
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="assignCancelBtn">Close</button>
                <button type="button" class="btn btn-primary" onclick="assignData()" id="assignDataBtn">Assign Data</button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Update campaign status
    document.getElementById('campaignStatus').addEventListener('change', function() {
        const status = this.value;
        const campaignId = this.getAttribute('data-campaign-id');
        
        $.ajax({
            url: '<?= base_url('admin/campaign_update_status/') ?>' + campaignId,
            method: 'POST',
            data: { status: status },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    alert('Campaign status updated successfully');
                    location.reload();
                } else {
                    alert('Failed to update status: ' + response.message);
                }
            }
        });
    });
});

// Assign users to campaign
function assignUsers() {
    const formData = $('#assignUsersForm').serialize();
    const campaignId = <?= $campaign->id ?>;
    
    $.ajax({
        url: '<?= base_url('admin/campaign_assign_users/') ?>' + campaignId,
        method: 'POST',
        data: formData,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                alert(response.message);
                location.reload();
            } else {
                alert('Error: ' + response.message);
            }
        }
    });
}

// Show assign data modal
function showAssignDataModal(campaignId, userId, username) {
    $('#assign_campaign_id').val(campaignId);
    $('#assign_user_id').val(userId);
    $('#assign_username').text(username);
    $('#assign_count').val('');
    $('#assignProgressSection').hide();
    $('#assignDataForm').show();
    $('#assignDataBtn').show().prop('disabled', false).html('Assign Data');
    $('#assignCancelBtn').prop('disabled', false);
    $('#assignDataCloseBtn').show();
    $('#assignDataModal').modal('show');
}

// Batch processing state
let batchState = {
    inProgress: false,
    campaign_id: null,
    user_id: null,
    batch_size: 10000,
    offset: 0,
    total_count: 0,
    original_count: 0,
    fail_count: 0
};

// Assign data to user
function assignData() {
    const formData = $('#assignDataForm').serialize();
    const btn = $('#assignDataBtn');
    const count = parseInt($('#assign_count').val());
    
    if (!count || count < 1) {
        alert('Please enter a valid number of records.');
        return;
    }
    
    // Disable button and show loading
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Processing...');
    $('#assignCancelBtn').prop('disabled', true);
    $('#assignDataCloseBtn').hide();
    
    console.log('Assigning data with:', formData);
    
    $.ajax({
        url: '<?= base_url('admin/campaign_assign_data') ?>',
        method: 'POST',
        data: formData,
        dataType: 'json',
        timeout: 120000, // 2 minute timeout
        success: function(response) {
            console.log('Response:', response);
            
            if (response.success) {
                // Check if batch processing is required
                if (response.batch_required) {
                    startBatchProcessing(response.data);
                } else {
                    showCompletionSummary(response.data);
                }
            } else {
                resetAssignModal();
                alert('Error: ' + (response.message || 'Unknown error'));
            }
        },
        error: function(xhr, status, error) {
            resetAssignModal();
            console.error('AJAX Error:', xhr.responseText);
            alert('An error occurred while assigning data.\n\nStatus: ' + status + '\nError: ' + error + '\n\nCheck console for details.');
        }
    });
}

// Start batch processing for large datasets
function startBatchProcessing(data) {
    batchState = {
        inProgress: true,
        campaign_id: $('#assign_campaign_id').val(),
        user_id: $('#assign_user_id').val(),
        batch_size: data.batch_size || 10000,
        offset: 0,
        total_count: data.total_count,
        original_count: data.original_count,
        fail_count: data.fail_count
    };
    
    // Show progress UI
    $('#assignDataForm').hide();
    $('#assignDataBtn').hide();
    $('#assignProgressSection').show();
    
    updateProgressUI(0, batchState.total_count, 0);
    
    // Start processing batches
    processBatch();
}

// Process a single batch
function processBatch() {
    if (!batchState.inProgress) {
        return;
    }
    
    $.ajax({
        url: '<?= base_url('admin/campaign_assign_data_batch') ?>',
        method: 'POST',
        data: {
            campaign_id: batchState.campaign_id,
            user_id: batchState.user_id,
            batch_size: batchState.batch_size,
            offset: batchState.offset,
            total_count: batchState.total_count,
            original_count: batchState.original_count,
            fail_count: batchState.fail_count
        },
        dataType: 'json',
        timeout: 180000, // 3 minute timeout per batch
        success: function(response) {
            console.log('Batch response:', response);
            
            if (response.success) {
                batchState.offset = response.total_processed;
                updateProgressUI(response.total_processed, batchState.total_count, response.progress);
                
                if (response.completed) {
                    // All done!
                    batchState.inProgress = false;
                    showCompletionSummary({
                        assigned_count: response.total_processed,
                        original_count: response.original_count || batchState.original_count,
                        fail_count: response.fail_count || batchState.fail_count
                    });
                } else {
                    // Process next batch with small delay
                    setTimeout(processBatch, 500);
                }
            } else {
                batchState.inProgress = false;
                alert('Batch processing error: ' + (response.message || 'Unknown error') + '\n\nProcessed so far: ' + batchState.offset);
                resetAssignModal();
            }
        },
        error: function(xhr, status, error) {
            batchState.inProgress = false;
            console.error('Batch AJAX Error:', xhr.responseText);
            alert('Batch processing failed.\n\nStatus: ' + status + '\nError: ' + error + '\n\nProcessed so far: ' + batchState.offset + ' records');
            resetAssignModal();
        }
    });
}

// Update progress UI
function updateProgressUI(processed, total, percent) {
    $('#assignProgressBar').css('width', percent + '%').text(percent + '%');
    $('#assignProgressText').text(processed >= total ? 'Completing...' : 'Processing batch...');
    $('#assignProgressCount').text(numberFormat(processed) + ' / ' + numberFormat(total) + ' records');
}

// Show completion summary
function showCompletionSummary(data) {
    const summary = 'Data Assigned Successfully!\n\n' +
        'Total Assigned: ' + numberFormat(data.assigned_count) + '\n' +
        'Original Records: ' + numberFormat(data.original_count) + '\n' +
        'Auto-added (Fail Buffer): ' + numberFormat(data.fail_count);
    alert(summary);
    location.reload();
}

// Reset modal to initial state
function resetAssignModal() {
    $('#assignDataBtn').show().prop('disabled', false).html('Assign Data');
    $('#assignCancelBtn').prop('disabled', false);
    $('#assignDataCloseBtn').show();
    $('#assignProgressSection').hide();
    $('#assignDataForm').show();
    batchState.inProgress = false;
}

// Format number with commas
function numberFormat(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

// Export campaign details with user assignments
function exportCampaignDetails() {
    const btn = document.getElementById('exportCampaignBtn');
    const originalHTML = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Exporting...';
    
    try {
        // Prepare campaign data
        const campaignData = {
            'ID': <?= $campaign->id ?>,
            'Name': '<?= addslashes($campaign->name) ?>',
            'Type': '<?= $campaign->type ?>',
            'Fail Percentage': <?= $campaign->fail_percentage ?>,
            'Status': '<?= ucfirst($campaign->status) ?>',
            'Created By': '<?= addslashes($campaign->creator_name) ?>',
            'Created At': '<?= date('Y-m-d H:i:s', strtotime($campaign->created_at)) ?>',
            'Total Assigned': <?= $campaign->total_assigned ?>,
            'Total Sent': <?= $campaign->total_sent ?>,
            'Total Failed': <?= $campaign->total_failed ?>,
            'Total Remaining': <?= $campaign->total_remaining ?>,
            'Success Rate': '<?= $campaign->total_assigned > 0 ? round(($campaign->total_sent / $campaign->total_assigned) * 100, 2) : 0 ?>%'
        };
        
        // Prepare users data
        const usersData = <?= json_encode(array_map(function($u) {
            return [
                'User ID' => $u->id,
                'Username' => $u->username,
                'Email' => $u->email,
                'Assigned Count' => $u->assigned_count ?? 0,
                'Sent Count' => $u->sent_count ?? 0,
                'Failed Count' => $u->failed_count ?? 0,
                'Remaining' => ($u->assigned_count ?? 0) - ($u->sent_count ?? 0) - ($u->failed_count ?? 0)
            ];
        }, $assigned_users ?? [])) ?>;
        
        // Create workbook
        const wb = XLSX.utils.book_new();
        
        // Sheet 1: Campaign Summary
        const summaryData = [['Campaign Summary', '']];
        Object.keys(campaignData).forEach(key => {
            summaryData.push([key, campaignData[key]]);
        });
        const wsSummary = XLSX.utils.aoa_to_sheet(summaryData);
        wsSummary['!cols'] = [{wch: 20}, {wch: 40}];
        XLSX.utils.book_append_sheet(wb, wsSummary, 'Campaign Summary');
        
        // Sheet 2: User Assignments
        if (usersData.length > 0) {
            const userHeaders = Object.keys(usersData[0]);
            const userData = [userHeaders];
            usersData.forEach(user => {
                userData.push(userHeaders.map(h => user[h]));
            });
            const wsUsers = XLSX.utils.aoa_to_sheet(userData);
            wsUsers['!cols'] = [
                {wch: 10},  // User ID
                {wch: 20},  // Username
                {wch: 30},  // Email
                {wch: 15},  // Assigned Count
                {wch: 15},  // Sent Count
                {wch: 15},  // Failed Count
                {wch: 15}   // Remaining
            ];
            XLSX.utils.book_append_sheet(wb, wsUsers, 'User Assignments');
        }
        
        // Generate filename
        const timestamp = new Date().toISOString().split('T')[0];
        const campaignName = '<?= preg_replace('/[^a-zA-Z0-9_]/', '_', $campaign->name) ?>';
        const filename = `campaign_${campaignName}_${timestamp}.xlsx`;
        
        // Download
        XLSX.writeFile(wb, filename);
        
        btn.disabled = false;
        btn.innerHTML = originalHTML;
        
    } catch (error) {
        console.error('Export error:', error);
        alert('Error exporting campaign details: ' + error.message);
        btn.disabled = false;
        btn.innerHTML = originalHTML;
    }
}
</script>
