<?php
ob_start();
include 'includes.php';
include 'connection.php';
session_start();
// Check if admin is logged in
if (!isset($_SESSION['admin'])) {
    header('Location: index.php');
    exit;
}

// Bulk Delete Contact Enquiries
if (isset($_POST['bulk_delete']) && isset($_POST['selected_items']) && !empty($_POST['selected_items'])) {
    $selectedIds = $_POST['selected_items'];

    foreach ($selectedIds as $id) {
        $id = (int)$id;
        // Delete the record from database
        $conn->query("DELETE FROM contact_enquiries WHERE id=$id");
    }

    header("Location: manage_contact.php");
    exit;
}

// Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $conn->query("DELETE FROM contact_enquiries WHERE id=$id");
    header("Location: manage_contact.php");
    exit;
}

// Pagination - 10 items per page
$itemsPerPage = 10000000;
$totalItems = $conn->query("SELECT COUNT(*) as cnt FROM contact_enquiries")->fetch_assoc()['cnt'];
$totalPages = ceil($totalItems / $itemsPerPage);
$currentPage = isset($_GET['page']) ? max(1, min((int)$_GET['page'], $totalPages)) : 1;
$offset = ($currentPage - 1) * $itemsPerPage;
$result = $conn->query("SELECT * FROM contact_enquiries ORDER BY id DESC LIMIT $offset, $itemsPerPage");
?>

<!-- Add required libraries for export functionality -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<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.31/jspdf.plugin.autotable.min.js"></script>

<div class="spac-content">
    <div class="spac-management-container">
        <h1 class="spac-management-title">Contact Enquiries</h1>

        <div style="text-align: right; margin-bottom: 10px;">
            <button id="exportExcel" class="spac-btn" style="background:#28a745;  border: 2px solid #28a745;">Export Excel</button>
            <button id="exportWord" class="spac-btn" style="background:#007bff; border: 2px solid #007bff;">Export Word</button>
            <button id="bulkDeleteBtn" class="spac-btn" style="background:#dc3545;" onclick="performBulkDelete()">
                Delete Selected
            </button>
        </div>

        <div class="spac-table-container">
            <form id="enquiriesForm" method="POST">
                <input type="hidden" name="bulk_delete" value="1">
                <table id="enquiriesTable" class="spac-management-table">
                    <thead>
                        <tr>
                            <th style="width: 30px;">
                                <input type="checkbox" id="selectAll" class="checkbox">
                            </th>
                            <th>Serial No.</th>
                            <th>Name</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Subject</th>
                            <th>Message</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $serialNo = ($currentPage - 1) * $itemsPerPage + 1;
                        while ($row = $result->fetch_assoc()):
                        ?>
                            <tr>
                                <td>
                                    <input type="checkbox" name="selected_items[]" value="<?= $row['id'] ?>" class="checkbox item-checkbox">
                                </td>
                                <td style="color: brown;"><?= $serialNo++ ?></td>
                                <td><?= htmlspecialchars($row['name']) ?></td>
                                <td><?= htmlspecialchars($row['phone']) ?></td>
                                <td><?= htmlspecialchars($row['email']) ?></td>
                                <td><?= htmlspecialchars($row['subject']) ?></td>
                                <td><?= htmlspecialchars($row['message']) ?></td>
                                <td><?= ucfirst($row['status']) ?></td>
                                <td><?= date('d M Y', strtotime($row['created_at'])) ?></td>
                                <td>
                                    <a href="?delete=<?= $row['id'] ?>" onclick="return confirm('Delete this enquiry?')" class="spac-btn spac-delete-btn" title="Delete">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </form>

            <!-- Pagination -->
            <div class="spac-pagination">
                <?php if ($currentPage > 1): ?>
                    <a href="?page=<?= $currentPage - 1 ?>" class="spac-page-btn"><i class="fas fa-chevron-left"></i></a>
                <?php endif; ?>
                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                    <?php if ($i == 1 || $i == $totalPages || ($i >= $currentPage - 1 && $i <= $currentPage + 1)): ?>
                        <a href="?page=<?= $i ?>" class="spac-page-btn <?= $i == $currentPage ? 'active' : '' ?>"><?= $i ?></a>
                    <?php elseif ($i == $currentPage - 2 || $i == $currentPage + 2): ?>
                        <span class="spac-page-dots">...</span>
                    <?php endif; ?>
                <?php endfor; ?>
                <?php if ($currentPage < $totalPages): ?>
                    <a href="?page=<?= $currentPage + 1 ?>" class="spac-page-btn"><i class="fas fa-chevron-right"></i></a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<style>
    .spac-content {
        background-image: url('../assets/images/footer-bg.png');
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
    }

    body {
        background-image: url('../assets/images/footer-bg.png');
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
    }

    .spac-management-container {
        padding: 15px;
        max-width: 100%;
    }

    .spac-management-title {
        font-size: 1rem;
        margin-bottom: 15px;
        color: white;
    }

    /* Table Styles */
    .spac-table-container {
        overflow-x: auto;
    }

    .spac-management-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 0.85rem;
    }

    .spac-management-table th {
        background: brown;
        color: white;
        padding: 8px 6px;
        text-align: left;
        font-weight: 600;
    }

    .spac-management-table td {
        padding: 8px 6px;
        border-bottom: 1px solid #eee;
        vertical-align: top;
        color: brown;
        font-weight: 500;
    }

    .spac-btn {
        width: auto;
        height: 28px;
        border-radius: 4px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        color: white;
        text-decoration: none;
        margin-right: 5px;
        padding: 0 8px;
    }

    .spac-delete-btn {
        background-color: #dc3545;
    }

    /* Pagination */
    .spac-pagination {
        display: flex;
        justify-content: center;
        margin-top: 12px;
        gap: 3px;
    }

    .spac-page-btn {
        min-width: 28px;
        height: 28px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 4px;
        text-decoration: none;
        color: #494948;
        font-size: 0.8rem;
        padding: 0 6px;
    }

    .spac-page-btn.active {
        background-color: #494948;
        color: white;
    }

    .spac-page-dots {
        display: flex;
        align-items: center;
        color: #666;
        font-size: 0.8rem;
    }

    /* Export button styles */
    #exportExcel,
    #exportPDF,
    #exportWord,
    #bulkDeleteBtn {
        width: auto;
        padding: 6px 12px;
        height: auto;
        font-size: 0.8rem;
    }

    /* Checkbox styles */
    .checkbox {
        width: 16px;
        height: 16px;
        cursor: pointer;
    }
</style>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Select all functionality
        const selectAllCheckbox = document.getElementById('selectAll');
        const itemCheckboxes = document.querySelectorAll('.item-checkbox');

        if (selectAllCheckbox) {
            selectAllCheckbox.addEventListener('change', function() {
                itemCheckboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
            });
        }

        // Update select all checkbox when individual checkboxes are changed
        itemCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                if (selectAllCheckbox) {
                    const allChecked = Array.from(itemCheckboxes).every(cb => cb.checked);
                    selectAllCheckbox.checked = allChecked;
                }
            });
        });
    });

    // Function to handle bulk delete
    function performBulkDelete() {
        const selectedItems = document.querySelectorAll('.item-checkbox:checked');

        if (selectedItems.length === 0) {
            alert('Please select at least one enquiry to delete.');
            return;
        }

        if (confirm('Are you sure you want to delete ' + selectedItems.length + ' selected enquiries?')) {
            document.getElementById('enquiriesForm').submit();
        }
    }

    document.getElementById('exportExcel').addEventListener('click', function() {
        // Get the table
        let table = document.getElementById('enquiriesTable');

        // Create a copy of the table to modify
        let tableCopy = table.cloneNode(true);

        // Remove the checkbox column and Actions column from the copy
        let rows = tableCopy.querySelectorAll('tr');
        rows.forEach(row => {
            if (row.cells.length > 0) {
                // Remove Actions column (last column)
                row.deleteCell(-1);
                // Remove checkbox column (first column)
                row.deleteCell(0);
            }
        });

        // Convert to workbook and export
        let wb = XLSX.utils.table_to_book(tableCopy, {
            sheet: "Contact Enquiries"
        });
        XLSX.writeFile(wb, 'Contact_Enquiries.xlsx');
    });

    document.getElementById('exportWord').addEventListener('click', function() {
        // Get the table
        let table = document.getElementById('enquiriesTable');

        // Create a copy of the table to modify
        let tableCopy = table.cloneNode(true);

        // Remove the checkbox column and Actions column from the copy
        let rows = tableCopy.querySelectorAll('tr');
        rows.forEach(row => {
            if (row.cells.length > 0) {
                // Remove Actions column (last column)
                row.deleteCell(-1);
                // Remove checkbox column (first column)
                row.deleteCell(0);
            }
        });

        // Create HTML document
        let html = `
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>Contact Enquiries</title>
            <style>
                table {
                    border-collapse: collapse;
                    width: 100%;
                }
                th, td {
                    border: 1px solid #ddd;
                    padding: 8px;
                    text-align: left;
                }
                th {
                    background-color: #494948;
                    color: white;
                }
                h1 {
                    text-align: center;
                }
            </style>
        </head>
        <body>
            <h1>Contact Enquiries</h1>
            ${tableCopy.outerHTML}
        </body>
        </html>
    `;

        // Create blob and download
        let blob = new Blob([html], {
            type: "application/msword"
        });
        let url = URL.createObjectURL(blob);
        let a = document.createElement('a');
        a.href = url;
        a.download = 'Contact_Enquiries.doc';
        a.click();
        URL.revokeObjectURL(url);
    });
</script>