<?php $imageExtensions = array('jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'); ?>

<div class="page-title d-flex justify-content-between align-items-center">
    <h2><i class="bi bi-envelope-open"></i> Message Scheduler</h2>
    <a href="<?= base_url('admin/campaigns') ?>" class="btn btn-secondary">
        <i class="bi bi-arrow-left"></i> Back to Campaigns
    </a>
</div>

<div class="row">
    <div class="col-lg-4">
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-plus-circle"></i> Schedule a New Message
            </div>
            <div class="card-body">
                <p class="text-muted small">
                    Enter the campaign message once. The system will automatically split it into four random parts, send the first part on the start date, and stagger the remaining parts across the following days.
                </p>
                <form method="post" action="<?= base_url('admin/message-schedules') ?>" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label class="form-label">Campaign *</label>
                        <select name="campaign_id" class="form-select" required>
                            <option value="">Select campaign</option>
                            <?php foreach ($campaigns as $campaign_option): ?>
                                <option value="<?= $campaign_option->id ?>" <?= set_value('campaign_id') == $campaign_option->id ? 'selected' : '' ?>>
                                    <?= html_escape($campaign_option->name . ' • ' . ($campaign_option->type ? $campaign_option->type : 'Custom')) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Start Date *</label>
                        <input type="date" name="start_date" class="form-control" value="<?= set_value('start_date', date('Y-m-d')) ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Sender ID *</label>
                        <input type="text" name="sender_id" class="form-control" placeholder="e.g. AurigaPORTAL" maxlength="50" value="<?= set_value('sender_id') ?>" required>
                        <small class="text-muted">Displayed on user panel so recipients know who scheduled the broadcast.</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Total Recipients *</label>
                        <input type="number" name="total_recipients" class="form-control" min="4" placeholder="e.g. 100" value="<?= set_value('total_recipients') ?>" required>
                        <small class="text-muted">Minimum 4 so each part delivers at least one recipient.</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Message Content *</label>
                        <textarea name="message_content" class="form-control" rows="4" placeholder="Type the announcement to deliver" required><?= set_value('message_content') ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Attachment (optional)</label>
                        <input type="file" name="attachment" class="form-control" accept="image/*,application/pdf">
                        <small class="text-muted">Optional image or PDF to include with the broadcast.</small>
                    </div>
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-calendar-check"></i> Create Schedule
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <div class="card">
            <div class="card-header">
                <i class="bi bi-info-circle"></i> How it Works
            </div>
            <div class="card-body">
                <ul class="mb-0 small text-muted">
                    <li>The first part is queued for the chosen start date.</li>
                    <li>Remaining parts are automatically placed 1-3 days after each other.</li>
                    <li>Batch sizes are random but always sum up to the total recipients.</li>
                    <li>Users can only view masked information and sample rows.</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">
                <i class="bi bi-clock-history"></i> Campaign Broadcast Schedules
            </div>
            <div class="card-body">
                <?php if (empty($grouped_schedules)): ?>
                    <p class="text-muted text-center mb-0">No message schedules created yet.</p>
                <?php else: ?>
                    <div class="accordion" id="campaignScheduleAccordion">
                        <?php $accordionIndex = 0; ?>
                        <?php foreach ($grouped_schedules as $campaign_id => $group): ?>
                            <?php $accordionIndex++; ?>
                            <div class="accordion-item">
                                <?php $groupMeta = campaign_type_meta(isset($group['campaign_type']) ? $group['campaign_type'] : 'Custom'); ?>
                                <h2 class="accordion-header" id="heading<?= $accordionIndex ?>">
                                    <button class="accordion-button <?= $accordionIndex === 1 ? '' : 'collapsed' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#collapse<?= $accordionIndex ?>" aria-expanded="<?= $accordionIndex === 1 ? 'true' : 'false' ?>" aria-controls="collapse<?= $accordionIndex ?>">
                                        <div class="w-100 d-flex justify-content-between align-items-center flex-wrap gap-2">
                                            <div>
                                                <span class="d-block"><strong><?= html_escape($group['campaign_name']) ?></strong></span>
                                                <span class="badge <?= $groupMeta['badge'] ?> mt-2"><i class="bi <?= $groupMeta['icon'] ?> me-1"></i><?= html_escape($groupMeta['label']) ?></span>
                                            </div>
                                            <span class="badge bg-light text-dark">Schedules: <?= count($group['schedules']) ?></span>
                                        </div>
                                    </button>
                                </h2>
                                <div id="collapse<?= $accordionIndex ?>" class="accordion-collapse collapse <?= $accordionIndex === 1 ? 'show' : '' ?>" aria-labelledby="heading<?= $accordionIndex ?>" data-bs-parent="#campaignScheduleAccordion">
                                    <div class="accordion-body">
                                        <?php foreach ($group['schedules'] as $schedule): ?>
                                            <?php
                                                $scheduleMeta = campaign_type_meta(isset($schedule->campaign_type) ? $schedule->campaign_type : 'Custom');
                                                $rawContent = trim((string) $schedule->message_content);
                                                $previewHint = $scheduleMeta['preview'];
                                                $imageUrl = null;
                                                $attachmentUrl = null;
                                                $caption = $rawContent;

                                                // If admin uploaded an attachment, build a usable URL
                                                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="card mb-4 shadow-sm">
                                                <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                                                    <div>
                                                        <div class="d-flex align-items-center gap-2 flex-wrap">
                                                            <h5 class="mb-1">Sender ID: <?= html_escape($schedule->sender_id ?: 'N/A') ?></h5>
                                                            <span class="badge <?= $scheduleMeta['badge'] ?>"><i class="bi <?= $scheduleMeta['icon'] ?> me-1"></i><?= html_escape($scheduleMeta['label']) ?></span>
                                                        </div>
                                                        <small class="text-muted">Created <?= date('M d, Y H:i', strtotime($schedule->created_at)) ?> · Total recipients <?= number_format($schedule->total_recipients) ?></small>
                                                    </div>
                                                    <div class="d-flex gap-2 align-items-center">
                                                        <span class="badge bg-info text-dark">Schedule #<?= $schedule->id ?></span>
                                                        <button type="button" class="btn btn-sm btn-danger js-delete-schedule" data-schedule-id="<?= $schedule->id ?>" data-campaign-name="<?= html_escape($group['campaign_name']) ?>" title="Delete Schedule">
                                                            <i class="bi bi-trash"></i> Delete
                                                        </button>
                                                    </div>
                                                </div>
                                                <div class="card-body">
                                                    <div class="mb-3">
                                                        <label class="form-label">Broadcast Preview</label>
                                                        <?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">
                                                                    <img src="<?= html_escape($attachmentUrl) ?>" alt="Scheduled image preview">
                                                                </div>
                                                                <div class="small mt-2">
                                                                    <i class="bi bi-link-45deg"></i> <a href="<?= html_escape($attachmentUrl) ?>" target="_blank" rel="noopener">Open attachment in new tab</a>
                                                                </div>
                                                                <?php if ($caption !== ''): ?>
                                                                    <div class="message-preview text-preview mt-3">
                                                                        <?= nl2br(html_escape($caption)) ?>
                                                                    </div>
                                                                <?php endif; ?>
                                                            <?php elseif ($attExt === 'pdf'): ?>
                                                                <div class="message-preview image-preview">
                                                                    <embed src="<?= html_escape($attachmentUrl) ?>" type="application/pdf" width="100%" height="400px" />
                                                                </div>
                                                                <div class="small mt-2">
                                                                    <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">
                                                                    <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">
                                                                <img src="<?= html_escape($imageUrl) ?>" alt="Scheduled image preview">
                                                            </div>
                                                            <div class="small mt-2">
                                                                <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 mt-3">
                                                                    <?= 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 class="table-responsive">
                                                        <table class="table table-sm table-hover message-batch-table" id="<?= $schedule->table_id ?>" data-title="<?= html_escape($group['campaign_name'] . ' - ' . ($schedule->sender_id ?: 'Schedule ' . $schedule->id)) ?>">
                                                            <thead class="table-light">
                                                                <tr>
                                                                    <th>Delivery Slot</th>
                                                                    <th>Audience Size</th>
                                                                    <th>Scheduled Date</th>
                                                                    <th>Status</th>
                                                                    <th>Actions</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <?php foreach ($schedule->batches as $batch): ?>
                                                                    <tr data-batch-id="<?= $batch->id ?>">
                                                                        <td>Delivery <?= $batch->batch_number ?></td>
                                                                        <td><?= number_format($batch->batch_size) ?></td>
                                                                        <td><?= date('M d, Y H:i', strtotime($batch->scheduled_for)) ?></td>
                                                                        <td>
                                                                            <?php if ($batch->status === 'sent'): ?>
                                                                                <span class="badge bg-success">Sent <?= $batch->sent_at ? '· ' . date('M d, Y H:i', strtotime($batch->sent_at)) : '' ?></span>
                                                                            <?php elseif ($batch->status === 'processing'): ?>
                                                                                <span class="badge bg-warning text-dark">In Progress</span>
                                                                            <?php else: ?>
                                                                                <span class="badge bg-info">Send</span>
                                                                            <?php endif; ?>
                                                                        </td>
                                                                        <td class="text-nowrap">
                                                                            <div class="btn-group btn-group-sm" role="group">
                                                                                <button type="button" class="btn btn-outline-secondary js-update-batch" data-url="<?= base_url('admin/message-batch-status/' . $batch->id) ?>" data-status="pending">Mark Pending</button>
                                                                                <button type="button" class="btn btn-outline-warning js-update-batch" data-url="<?= base_url('admin/message-batch-status/' . $batch->id) ?>" data-status="processing">Mark In Progress</button>
                                                                                <button type="button" class="btn btn-outline-success js-update-batch" data-url="<?= base_url('admin/message-batch-status/' . $batch->id) ?>" data-status="sent">Mark Sent</button>
                                                                            </div>
                                                                        </td>
                                                                    </tr>
                                                                <?php endforeach; ?>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    <p class="text-muted small">Slots move to <strong>In Progress</strong> as they reach their scheduled time and flip to <strong>Sent</strong> automatically afterward. Update them manually if you complete or postpone a send.</p>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </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;
}

</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
    $('.message-batch-table').each(function () {
        const $table = $(this);
        const title = $table.data('title') || 'Message Schedule';

        $table.DataTable({
            dom: 'Bfrtip',
            pageLength: 10,
            buttons: [
                { extend: 'excelHtml5', title: title },
                { extend: 'pdfHtml5', title: title, orientation: 'landscape', pageSize: 'A4' },
                { extend: 'print', title: title }
            ],
            order: [[2, 'asc']]
        });
    });

    $('.js-update-batch').on('click', function () {
        const $btn = $(this);
        const url = $btn.data('url');
        const status = $btn.data('status');

        $btn.prop('disabled', true).addClass('loading');

        $.ajax({
            url: url,
            method: 'POST',
            dataType: 'json',
            data: { status: status },
            success: function (response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.message || 'Failed to update batch status.');
                }
            },
            error: function () {
                alert('Unexpected error while updating batch status.');
            },
            complete: function () {
                $btn.prop('disabled', false).removeClass('loading');
            }
        });
    });
    
    $(document).on('click', '.js-delete-schedule', function (e) {
        e.preventDefault();
        e.stopPropagation();
        
        const $btn = $(this);
        const scheduleId = $btn.data('schedule-id');
        const campaignName = $btn.data('campaign-name');
        
        if (!confirm(`Are you sure you want to delete Schedule #${scheduleId} from campaign "${campaignName}"?\n\nThis will also delete all associated batches and cannot be undone.`)) {
            return;
        }
        
        $btn.prop('disabled', true).html('<i class="bi bi-hourglass-split"></i> Deleting...');
        
        $.ajax({
            url: '<?= base_url('admin/delete-schedule/') ?>' + scheduleId,
            method: 'POST',
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    alert('Schedule deleted successfully!');
                    location.reload();
                } else {
                    alert(response.message || 'Failed to delete schedule.');
                    $btn.prop('disabled', false).html('<i class="bi bi-trash"></i> Delete');
                }
            },
            error: function () {
                alert('Unexpected error while deleting schedule.');
                $btn.prop('disabled', false).html('<i class="bi bi-trash"></i> Delete');
            }
        });
    });
});
</script>
