<div class="container mt-4">
    <div class="card shadow-sm rounded-3 border-0">
        <div class="card-header bg-warning bg-gradient text-dark d-flex align-items-center">
            <i class="bi bi-pencil-square me-2 fs-5"></i>
            <h5 class="mb-0">Edit Task</h5>
        </div>

        <div class="card-body">
            <?php if (!empty($error)): ?>
                <div class="alert alert-danger shadow-sm rounded"><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <form method="post" action="">
                <div class="mb-3">
                    <label class="form-label fw-semibold">Task Title</label>
                    <input type="text" name="title" class="form-control shadow-sm" value="<?= htmlspecialchars($task['title']) ?>" required>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-semibold">Due Date</label>
                    <input type="datetime-local" name="due_date" class="form-control shadow-sm" value="<?= date('Y-m-d\TH:i', strtotime($task['due_date'])) ?>" required>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-semibold">Status</label>
                    <select name="status" class="form-select shadow-sm">
                        

                        <option value="pending" <?= $task['status'] === 'pending' ? 'selected' : '' ?>>Pending</option>
                        <option value="completed" <?= $task['status'] === 'completed' ? 'selected' : '' ?>>Completed</option>
                    </select>
                </div>

                <div class="d-flex gap-2">
                    <button type="submit" class="btn btn-success shadow-sm">
                        <i class="bi bi-check-circle me-1"></i> Update Task
                    </button>
                    <a href="<?= BASE_URL ?>/TaskController/index/<?= $task['contact_id'] ?>" class="btn btn-outline-secondary shadow-sm">
                        <i class="bi bi-x-circle me-1"></i> Cancel
                    </a>
                </div>
            </form>
            <div id="noResults" class="alert alert-warning small d-none mt-4">
    <i class="bi bi-exclamation-triangle me-1"></i> No matching logs found.
</div>

<div class="card mt-4 shadow-sm border-0">
    <div class="card-header bg-light d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-clock-history me-2"></i> Task History</h5>
    </div>

    <div class="card-body">
        <!-- Tabs -->
        <ul class="nav nav-tabs mb-3" id="taskHistoryTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="updates-tab" data-bs-toggle="tab" data-bs-target="#updates" type="button" role="tab">
                    <i class="bi bi-pencil-square me-1"></i> Update History
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="reminders-tab" data-bs-toggle="tab" data-bs-target="#reminders" type="button" role="tab">
                    <i class="bi bi-envelope-paper-fill me-1"></i> Reminder Log
                </button>
            </li>
        </ul>

        <div class="tab-content" id="taskHistoryTabsContent">
            <!-- 🔄 Update History Tab -->
            <div class="tab-pane fade show active" id="updates" role="tabpanel">
               <?php if (!empty($logs)): ?>
<div class="card shadow-sm rounded-3 border-0 mt-4">
    <div class="card-header bg-light d-flex flex-wrap justify-content-between align-items-center gap-2">
        <h5 class="mb-0 text-dark d-flex align-items-center">
            <i class="bi bi-clock-history me-2 fs-5"></i> Update History
        </h5>
        <div class="d-flex flex-wrap gap-2 align-items-center">
            <input type="text" id="logSearch" class="form-control form-control-sm" placeholder="Search logs..." style="width: 200px;">
            <select id="fieldFilter" class="form-select form-select-sm" style="width: 150px;">
                <option value="">All Fields</option>
                <?php
                $fields = array_unique(array_column($logs, 'field_changed'));
                foreach ($fields as $field): ?>
                    <option value="<?= strtolower($field) ?>"><?= ucfirst($field) ?></option>
                <?php endforeach; ?>
            </select>
            <button id="exportLogs" class="btn btn-outline-secondary btn-sm" title="Export CSV">
                <i class="bi bi-file-earmark-spreadsheet"></i>
            </button>
            <button id="exportLogsPDF" class="btn btn-outline-danger btn-sm" title="Export PDF">
                <i class="bi bi-file-earmark-pdf"></i>
            </button>
        </div>
    </div>

    <div class="card-body">
        <?php
        $groupedLogs = [];
        foreach ($logs as $log) {
            $date = date('Y-m-d', strtotime($log['updated_at']));
            $groupedLogs[$date][] = $log;
        }
        ?>

        <?php foreach ($groupedLogs as $date => $dailyLogs): ?>
            <div class="mb-4">
                <div class="border-start ps-3">
                    <div class="mb-3">
                        <span class="text-muted small"><i class="bi bi-calendar-event me-1"></i><?= date('l, j F Y', strtotime($date)) ?></span>
                    </div>

                    <?php foreach ($dailyLogs as $log): ?>
                        <div class="log-item position-relative ps-3 mb-4" data-field="<?= strtolower($log['field_changed']) ?>">
                            <div class="position-absolute top-0 start-0 translate-middle bg-warning rounded-circle" style="width: 10px; height: 10px;"></div>
                            <div class="d-flex flex-column flex-md-row justify-content-between gap-2">
                                <div>
                                    <div class="fw-semibold text-capitalize"><?= htmlspecialchars($log['field_changed']) ?></div>
                                    <div class="text-muted small">
                                        <span class="me-1">Changed by</span>
                                        <strong><?= htmlspecialchars($log['updated_by_name'] ?? 'Unknown') ?></strong>
                                        <span class="ms-2">at <?= date('H:i:s', strtotime($log['updated_at'])) ?></span>
                                    </div>
                                </div>
                                <div class="text-md-end">
                                    <div class="small text-muted">From → To</div>
                                    <div>
                                        <span class="text-danger-emphasis">"<?= htmlspecialchars($log['old_value']) ?>"</span>
                                        <i class="bi bi-arrow-right mx-1 text-muted"></i>
                                        <span class="text-success-emphasis">"<?= htmlspecialchars($log['new_value']) ?>"</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endforeach; ?>
        
        <?php if (isset($totalPages) && $totalPages > 1): ?>
            <nav>
                <ul class="pagination justify-content-center mt-4">
                    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                        <li class="page-item <?= $i == $currentPage ? 'active' : '' ?>">
                            <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
            <?php endif; ?>
            </div>
            
            

    </div>

<?php endif; ?>
            </div>

            <!-- 📧 Reminder Log Tab -->
            <div class="tab-pane fade" id="reminders" role="tabpanel">
                <?php if (!empty($reminderLogs)): ?>
                    <?php
// Group logs by date
$groupedReminders = [];
$senders = [];

foreach ($reminderLogs as $log) {
    $date = date('Y-m-d', strtotime($log['sent_at']));
    $groupedReminders[$date][] = $log;
    $senders[] = $log['sender_name'] ?? 'Unknown';
}

$uniqueSenders = array_unique($senders);
?>

<div class="card shadow-sm rounded-3 border-0 mt-4">
    <div class="card-header bg-light d-flex flex-wrap justify-content-between align-items-center gap-2">
        <h5 class="mb-0 text-dark d-flex align-items-center">
            <i class="bi bi-envelope-paper-fill me-2 fs-5"></i> Reminder Log
        </h5>
        <div class="d-flex flex-wrap gap-2 align-items-center">
            <input type="text" id="reminderSearch" class="form-control form-control-sm" placeholder="Search reminders..." style="width: 200px;">
            <select id="senderFilter" class="form-select form-select-sm" style="width: 160px;">
                <option value="">All Senders</option>
                <?php foreach ($uniqueSenders as $sender): ?>
                    <option value="<?= htmlspecialchars(strtolower($sender)) ?>"><?= htmlspecialchars($sender) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>

    <div class="card-body">
        <?php foreach ($groupedReminders as $date => $logsForDay): ?>
            <div class="mb-4">
                <div class="border-start ps-3">
                    <div class="mb-2 text-muted small">
                        <i class="bi bi-calendar-event me-1"></i><?= date('l, j F Y', strtotime($date)) ?>
                    </div>

                    <?php foreach ($logsForDay as $log): ?>
                        <div class="reminder-item position-relative ps-3 mb-4"
                             data-sender="<?= strtolower($log['sender_name'] ?? 'unknown') ?>">
                            <div class="position-absolute top-0 start-0 translate-middle bg-primary rounded-circle" style="width: 10px; height: 10px;"></div>
                            <div class="d-flex flex-column flex-md-row justify-content-between gap-2">
                                <div>
                                    <div class="fw-semibold">Reminder Sent</div>
                                    <div class="text-muted small">
                                        By <strong><?= htmlspecialchars($log['sender_name'] ?? 'Unknown') ?></strong>
                                        at <?= date('H:i:s', strtotime($log['sent_at'])) ?>
                                    </div>
                                </div>
                                <div class="text-md-end small">
                                    <?php if (!empty($log['cc_emails'])): ?>
                                        <div class="text-muted">
                                            <i class="bi bi-people-fill me-1"></i>CC:
                                            <span class="text-dark"><?= htmlspecialchars($log['cc_emails']) ?></span>
                                        </div>
                                    <?php else: ?>
                                        <div class="text-muted">
                                            <i class="bi bi-envelope-check me-1"></i>No CC
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

                <?php else: ?>
                    <p class="text-muted">No reminders have been sent yet.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>


        </div>
    </div>
</div>

<!-- ðŸ“¦ JS Export Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js"></script>

<script>


document.addEventListener('DOMContentLoaded', function () {
    const logItems = document.querySelectorAll('.log-item');
    const logSearch = document.getElementById('logSearch');
    const fieldFilter = document.getElementById('fieldFilter');
    const pagination = document.querySelector('.pagination');
    const noResults = document.getElementById('noResults');
    const logsPerPage = <?= $logsPerPage ?? 10 ?>;

    function filterLogs() {
        const searchTerm = logSearch.value.trim().toLowerCase();
        const selectedField = fieldFilter.value.trim().toLowerCase();
        let visibleCount = 0;

        logItems.forEach(item => {
            const field = item.dataset.field?.toLowerCase() || '';
            const text = item.innerText?.toLowerCase() || ''; // 🔥 Use innerText instead of textContent

            const matchesField = !selectedField || field === selectedField;
            const matchesSearch = !searchTerm || text.includes(searchTerm);

            const isVisible = matchesField && matchesSearch;
            item.style.display = isVisible ? 'block' : 'none';
            if (isVisible) visibleCount++;
        });

        // Hide pagination if filtered logs are less than logsPerPage
        if (pagination) {
            pagination.style.display = (searchTerm || selectedField) && visibleCount < logsPerPage ? 'none' : 'flex';
        }

        // Show or hide the "No Results" alert
        if (noResults) {
            noResults.classList.toggle('d-none', visibleCount > 0);
        }
    }

    if (logSearch) logSearch.addEventListener('input', filterLogs);
    if (fieldFilter) fieldFilter.addEventListener('change', filterLogs);
});





document.getElementById('exportLogs').addEventListener('click', function () {
    let csv = "Date,Time,Field,Old Value,New Value,Updated By\n";
    document.querySelectorAll('.log-item').forEach(item => {
        // Get date from nearest date container
        const date = item.closest('div.mb-4')?.querySelector('span.text-muted small')?.textContent.trim() || '';

        const field = item.querySelector('.fw-semibold.text-capitalize')?.textContent.trim() || '';
        const updatedBy = item.querySelector('div.text-muted small strong')?.textContent.trim() || 'Unknown';
        const updatedAtText = item.querySelector('div.text-muted small')?.textContent || '';
        // Extract time from updatedAtText e.g. "Changed by X at HH:mm:ss"
        const timeMatch = updatedAtText.match(/at (\d{2}:\d{2}:\d{2})/);
        const time = timeMatch ? timeMatch[1] : '';

        const oldValue = item.querySelector('.text-danger-emphasis')?.textContent.replace(/"/g, '').trim() || '';
        const newValue = item.querySelector('.text-success-emphasis')?.textContent.replace(/"/g, '').trim() || '';

        csv += `"${date}","${time}","${field}","${oldValue}","${newValue}","${updatedBy}"\n`;
    });

    const blob = new Blob([csv], { type: "text/csv" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = "task_update_logs.csv";
    link.click();
});


document.getElementById('exportLogsPDF').addEventListener('click', function () {
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF();
    const rows = [];

    document.querySelectorAll('.log-item').forEach(item => {
        const date = item.closest('div.mb-4')?.querySelector('span.text-muted small')?.textContent.trim() || '';

        const field = item.querySelector('.fw-semibold.text-capitalize')?.textContent.trim() || '';
        const updatedBy = item.querySelector('div.text-muted small strong')?.textContent.trim() || 'Unknown';
        const updatedAtText = item.querySelector('div.text-muted small')?.textContent || '';
        const timeMatch = updatedAtText.match(/at (\d{2}:\d{2}:\d{2})/);
        const time = timeMatch ? timeMatch[1] : '';

        const oldValue = item.querySelector('.text-danger-emphasis')?.textContent.replace(/"/g, '').trim() || '';
        const newValue = item.querySelector('.text-success-emphasis')?.textContent.replace(/"/g, '').trim() || '';

        rows.push([date, time, field, oldValue, newValue, updatedBy]);
    });

    doc.text("Task Update Logs", 14, 14);
    doc.autoTable({
        head: [["Date", "Time", "Field", "Old Value", "New Value", "Updated By"]],
        body: rows,
        startY: 20,
        styles: { fontSize: 9 },
        theme: 'grid'
    });

    doc.save("task_update_logs.pdf");
});



    const searchInput = document.getElementById('reminderSearch');
    const senderFilter = document.getElementById('senderFilter');
    const logItems = document.querySelectorAll('.reminder-item');

    function filterReminders() {
        const query = searchInput.value.toLowerCase();
        const sender = senderFilter.value;

        logItems.forEach(item => {
            const text = item.textContent.toLowerCase();
            const itemSender = item.getAttribute('data-sender');

            const matchesQuery = text.includes(query);
            const matchesSender = !sender || itemSender === sender;

            item.style.display = (matchesQuery && matchesSender) ? '' : 'none';
        });
    }

    searchInput.addEventListener('input', filterReminders);
    senderFilter.addEventListener('change', filterReminders);



</script>
