<style>
.reminder-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
    margin-bottom: 25px;
}
.stat-card {
    background: white;
    border-radius: 10px;
    padding: 20px;
    text-align: center;
    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
    border-left: 4px solid #3b82f6;
}
.stat-card.sent { border-left-color: #10b981; }
.stat-card.pending { border-left-color: #f59e0b; }
.stat-card.failed { border-left-color: #ef4444; }
.stat-card .stat-value {
    font-size: 2rem;
    font-weight: bold;
    color: #1f2937;
}
.stat-card .stat-label {
    font-size: 0.875rem;
    color: #6b7280;
    margin-top: 5px;
}
.filter-section {
    background: white;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
}
.filter-row {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: flex-end;
}
.filter-group {
    flex: 1;
    min-width: 150px;
}
.filter-group label {
    display: block;
    font-weight: 500;
    margin-bottom: 5px;
    color: #374151;
    font-size: 0.875rem;
}
.filter-group select,
.filter-group input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #d1d5db;
    border-radius: 6px;
    font-size: 0.875rem;
}
.btn-filter {
    padding: 8px 20px;
    background: #3b82f6;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-weight: 500;
}
.btn-filter:hover {
    background: #2563eb;
}
.btn-reset {
    padding: 8px 20px;
    background: #6b7280;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
}
.reminder-table {
    width: 100%;
    background: white;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
}
.reminder-table th {
    background: #f3f4f6;
    padding: 12px 15px;
    text-align: left;
    font-weight: 600;
    color: #374151;
    font-size: 0.875rem;
}
.reminder-table td {
    padding: 12px 15px;
    border-bottom: 1px solid #e5e7eb;
    font-size: 0.875rem;
}
.reminder-table tr:hover {
    background: #f9fafb;
}
.status-badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
}
.status-badge.sent {
    background: #d1fae5;
    color: #065f46;
}
.status-badge.pending {
    background: #fef3c7;
    color: #92400e;
}
.status-badge.failed {
    background: #fee2e2;
    color: #991b1b;
}
.type-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.75rem;
    font-weight: 500;
}
.type-badge.email {
    background: #dbeafe;
    color: #1e40af;
}
.type-badge.whatsapp {
    background: #d1fae5;
    color: #065f46;
}
.empty-state {
    text-align: center;
    padding: 40px;
    color: #6b7280;
}
.empty-state i {
    font-size: 3rem;
    margin-bottom: 15px;
    color: #d1d5db;
}
.whatsapp-action {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 4px 10px;
    background: #25D366;
    color: white;
    border-radius: 4px;
    font-size: 0.75rem;
    text-decoration: none;
    cursor: pointer;
}
.whatsapp-action:hover {
    background: #128C7E;
    color: white;
}
.mark-sent-btn {
    padding: 4px 10px;
    background: #10b981;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 0.75rem;
    cursor: pointer;
}
</style>

<div class="content">
    

    <!-- Statistics -->
    <div class="reminder-stats">
        <div class="stat-card">
            <div class="stat-value"><?= number_format($stats['total'] ?? 0) ?></div>
            <div class="stat-label">Total Reminders</div>
        </div>
        <div class="stat-card sent">
            <div class="stat-value"><?= number_format($stats['sent'] ?? 0) ?></div>
            <div class="stat-label">Sent</div>
        </div>
        <div class="stat-card pending">
            <div class="stat-value"><?= number_format($stats['pending'] ?? 0) ?></div>
            <div class="stat-label">Pending</div>
        </div>
        <div class="stat-card failed">
            <div class="stat-value"><?= number_format($stats['failed'] ?? 0) ?></div>
            <div class="stat-label">Failed</div>
        </div>
        <div class="stat-card" style="border-left-color: #3b82f6;">
            <div class="stat-value"><?= number_format($stats['email_count'] ?? 0) ?></div>
            <div class="stat-label">Email</div>
        </div>
        <div class="stat-card" style="border-left-color: #25D366;">
            <div class="stat-value"><?= number_format($stats['whatsapp_count'] ?? 0) ?></div>
            <div class="stat-label">WhatsApp</div>
        </div>
    </div>

    <!-- Filters -->
    <div class="filter-section">
        <form method="get" action="<?= base_url('reminder/report') ?>">
            <div class="filter-row">
                <div class="filter-group">
                    <label>Company</label>
                    <select name="company_id">
                        <option value="">All Companies</option>
                        <?php foreach ($companies as $company): ?>
                        <option value="<?= $company['id'] ?>" <?= ($filters['company_id'] == $company['id']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($company['company_name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Document Head</label>
                    <select name="type_id">
                        <option value="">All Document Heads</option>
                        <?php foreach ($document_heads as $dh): ?>
                        <option value="<?= $dh['id'] ?>" <?= ($filters['type_id'] == $dh['id']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($dh['type_name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Year</label>
                    <select name="year">
                        <option value="">All Years</option>
                        <?php for ($y = $current_year; $y >= $current_year - 5; $y--): ?>
                        <option value="<?= $y ?>" <?= ($filters['year'] == $y) ? 'selected' : '' ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Month</label>
                    <select name="month">
                        <option value="">All Months</option>
                        <?php 
                        $months = ['January', 'February', 'March', 'April', 'May', 'June', 
                                   'July', 'August', 'September', 'October', 'November', 'December'];
                        foreach ($months as $i => $m): 
                        ?>
                        <option value="<?= $i + 1 ?>" <?= ($filters['month'] == ($i + 1)) ? 'selected' : '' ?>><?= $m ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Status</label>
                    <select name="status">
                        <option value="">All Status</option>
                        <option value="sent" <?= ($filters['status'] == 'sent') ? 'selected' : '' ?>>Sent</option>
                        <option value="pending" <?= ($filters['status'] == 'pending') ? 'selected' : '' ?>>Pending</option>
                        <option value="failed" <?= ($filters['status'] == 'failed') ? 'selected' : '' ?>>Failed</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Type</label>
                    <select name="reminder_type">
                        <option value="">All Types</option>
                        <option value="email" <?= ($filters['reminder_type'] == 'email') ? 'selected' : '' ?>>Email</option>
                        <option value="whatsapp" <?= ($filters['reminder_type'] == 'whatsapp') ? 'selected' : '' ?>>WhatsApp</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Date From</label>
                    <input type="date" name="date_from" value="<?= $filters['date_from'] ?>">
                </div>
                <div class="filter-group">
                    <label>Date To</label>
                    <input type="date" name="date_to" value="<?= $filters['date_to'] ?>">
                </div>
                <div class="filter-group" style="flex: 0;">
                    <button type="submit" class="btn-filter"><i class="fa fa-search"></i> Filter</button>
                </div>
                <div class="filter-group" style="flex: 0;">
                    <a href="<?= base_url('reminder/report') ?>" class="btn-reset"><i class="fa fa-refresh"></i> Reset</a>
                </div>
            </div>
        </form>
    </div>

    <!-- Reminder Table -->
    <table class="reminder-table">
        <thead>
            <tr>
                <th>#</th>
                <th>Company</th>
                <th>Document Head</th>
                <th>Period</th>
                <th>Due Date</th>
                <th>Days Before</th>
                <th>Recipient</th>
                <th>Type</th>
                <th>Status</th>
                <th>Sent At</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!empty($reminders)): ?>
                <?php 
                $monthNames = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                $i = 1;
                foreach ($reminders as $reminder): 
                ?>
                <tr>
                    <td><?= $i++ ?></td>
                    <td><?= htmlspecialchars($reminder['company_name'] ?? '-') ?></td>
                    <td><?= htmlspecialchars($reminder['type_name'] ?? '-') ?></td>
                    <td><?= $monthNames[$reminder['document_month']] ?> <?= $reminder['document_year'] ?></td>
                    <td><?= date('d M Y', strtotime($reminder['due_date'])) ?></td>
                    <td>
                        <?php 
                        $days = $reminder['days_before_due'];
                        if ($days > 0) {
                            echo "{$days} days before";
                        } elseif ($days == 0) {
                            echo "On due date";
                        } else {
                            echo abs($days) . " day after";
                        }
                        ?>
                    </td>
                    <td>
                        <div><?= htmlspecialchars($reminder['recipient_name'] ?? '-') ?></div>
                        <small class="text-muted">
                            <?= $reminder['reminder_type'] == 'email' 
                                ? htmlspecialchars($reminder['recipient_email'] ?? '')
                                : htmlspecialchars($reminder['recipient_phone'] ?? '') ?>
                        </small>
                    </td>
                    <td>
                        <span class="type-badge <?= $reminder['reminder_type'] ?>">
                            <?php if ($reminder['reminder_type'] == 'email'): ?>
                                <i class="fa fa-envelope"></i>
                            <?php else: ?>
                                <i class="fab fa-whatsapp"></i>
                            <?php endif; ?>
                            <?= ucfirst($reminder['reminder_type']) ?>
                        </span>
                    </td>
                    <td>
                        <span class="status-badge <?= $reminder['status'] ?>">
                            <?= ucfirst($reminder['status']) ?>
                        </span>
                        <?php if (!empty($reminder['error_message']) && $reminder['status'] == 'failed'): ?>
                            <i class="fa fa-info-circle text-danger" title="<?= htmlspecialchars($reminder['error_message']) ?>"></i>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?= $reminder['sent_at'] ? date('d M Y H:i', strtotime($reminder['sent_at'])) : '-' ?>
                    </td>
                    <td>
                        <?php if ($reminder['reminder_type'] == 'whatsapp' && $reminder['status'] == 'pending'): ?>
                            <?php
                            $whatsappMsg = "Reminder: Document Due - {$reminder['type_name']}\nCompany: {$reminder['company_name']}\nPeriod: {$monthNames[$reminder['document_month']]} {$reminder['document_year']}\nDue Date: " . date('d M Y', strtotime($reminder['due_date']));
                            $whatsappUrl = 'https://wa.me/' . preg_replace('/[^0-9]/', '', $reminder['recipient_phone']) . '?text=' . urlencode($whatsappMsg);
                            ?>
                            <a href="<?= $whatsappUrl ?>" target="_blank" class="whatsapp-action" title="Send WhatsApp">
                                <i class="fab fa-whatsapp"></i> Send
                            </a>
                            <button class="mark-sent-btn" onclick="markAsSent(<?= $reminder['id'] ?>)" title="Mark as Sent">
                                <i class="fa fa-check"></i>
                            </button>
                        <?php elseif ($reminder['reminder_type'] == 'email' && $reminder['status'] == 'failed'): ?>
                            <button class="btn-filter" style="padding: 4px 10px; font-size: 0.75rem;" onclick="retryEmail(<?= $reminder['id'] ?>)">
                                <i class="fa fa-refresh"></i> Retry
                            </button>
                        <?php else: ?>
                            -
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="11">
                        <div class="empty-state">
                            <i class="fa fa-bell-slash"></i>
                            <p>No reminders found matching your filters.</p>
                        </div>
                    </td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function markAsSent(id) {
    Swal.fire({
        title: 'Mark as Sent?',
        text: 'Confirm that you have sent this WhatsApp message manually.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#10b981',
        confirmButtonText: 'Yes, Mark as Sent'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: '<?= base_url("reminder/markWhatsAppSent") ?>',
                type: 'POST',
                data: { id: id },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire('Success', 'Marked as sent', 'success').then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                }
            });
        }
    });
}

function retryEmail(id) {
    Swal.fire({
        title: 'Retry Email?',
        text: 'This will attempt to resend the email.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3b82f6',
        confirmButtonText: 'Yes, Retry'
    }).then((result) => {
        if (result.isConfirmed) {
            // TODO: Implement retry logic
            Swal.fire('Info', 'Retry feature coming soon', 'info');
        }
    });
}
</script>

