<?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 Applications
if (isset($_POST['bulk_delete']) && isset($_POST['selected_items']) && !empty($_POST['selected_items'])) {
    $selectedIds = $_POST['selected_items'];
    foreach ($selectedIds as $id) {
        $id = (int)$id;
        $conn->query("DELETE FROM career_applications WHERE id=$id");
    }
    header("Location: manage_applications.php");
    exit;
}

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

// Update Application Status
if (isset($_POST['update_status']) && isset($_POST['application_id']) && isset($_POST['status'])) {
    $id = (int)$_POST['application_id'];
    $status = $_POST['status'];

    $stmt = $conn->prepare("UPDATE career_applications SET status = ? WHERE id = ?");
    $stmt->bind_param("si", $status, $id);
    $stmt->execute();

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

// Pagination - 20 items per page
$itemsPerPage = 20;
$totalItems = $conn->query("SELECT COUNT(*) as cnt FROM career_applications")->fetch_assoc()['cnt'];
$totalPages = ceil($totalItems / $itemsPerPage);
$currentPage = isset($_GET['page']) ? max(1, min((int)$_GET['page'], $totalPages)) : 1;
$offset = ($currentPage - 1) * $itemsPerPage;

// Query updated to match your provided table structure (no join, using 'position' column)
$result = $conn->query("SELECT * FROM career_applications 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">Career Applications</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="applicationsForm" method="POST">
                <input type="hidden" name="bulk_delete" value="1">
                <table id="applicationsTable" 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>Email</th>
                            <th>Phone</th>
                            <th>Position</th>
                            <th>Resume</th>
                            <th>Status</th> <!-- Added Status Header -->
                            <th>Applied Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $serialNo = ($currentPage - 1) * $itemsPerPage + 1;
                        while ($row = $result->fetch_assoc()):
                            // Determine status class for styling
                            $statusClass = '';
                            $currentStatus = isset($row['status']) ? $row['status'] : 'Pending';
                            if ($currentStatus == 'Approved' || $currentStatus == 'Shortlisted') $statusClass = 'active';
                            elseif ($currentStatus == 'Rejected') $statusClass = 'inactive';
                            else $statusClass = 'inactive';
                        ?>
                            <tr>
                                <td>
                                    <input type="checkbox" name="selected_items[]" value="<?= $row['id'] ?>" class="checkbox item-checkbox">
                                </td>
                                <td style="color: white;"><?= $serialNo++ ?></td>
                                <td><?= htmlspecialchars($row['name']) ?></td>
                                <td><?= htmlspecialchars($row['email']) ?></td>
                                <td><?= htmlspecialchars($row['phone']) ?></td>
                                <td><?= htmlspecialchars($row['position']) ?></td>
                                <td>
                                    <?php if (!empty($row['resume'])): ?>
                                        <a href="../<?= htmlspecialchars($row['resume']) ?>" target="_blank" class="spac-btn spac-view-btn" title="View Resume">
                                            <i class="fas fa-file-pdf"></i>
                                        </a>
                                    <?php else: ?>
                                        <span style="color: #999;">No Resume</span>
                                    <?php endif; ?>
                                </td>
                                <!-- Added Status Column Display -->
                                <td>
                                    <div class="status-container">
                                        <span class="spac-status <?= $statusClass ?>"><?= $currentStatus ?></span>
                                        <button type="button" class="status-btn" onclick="showStatusModal(<?= $row['id'] ?>, '<?= $currentStatus ?>')">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                    </div>
                                </td>
                                <td><?= date('d M Y', strtotime($row['applied_at'])) ?></td>
                                <td>
                                    <a href="?delete=<?= $row['id'] ?>" onclick="return confirm('Delete this application?')" 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>

<!-- Status Update Modal -->
<div id="statusModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeStatusModal()">&times;</span>
        <h3>Update Application Status</h3>
        <form id="statusForm" method="POST">
            <input type="hidden" id="application_id" name="application_id">
            <div class="form-group">
                <label for="status">Status:</label>
                <select id="status" name="status" class="form-control">
                    <option value="Pending">Pending</option>
                    <option value="Under Review">Under Review</option>
                    <option value="Shortlisted">Shortlisted</option>
                    <option value="Rejected">Rejected</option>
                    <option value="Approved">Approved</option>
                </select>
            </div>
            <button type="submit" name="update_status" class="btn btn-primary">Update Status</button>
        </form>
    </div>
</div>

<style>
    /* Your original CSS remains the same */
    .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;
    }

    .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: 600;
    }

    .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;
        font-weight: 600;
    }

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

    .spac-view-btn {
        background-color: #17a2b8;
    }

    /* Status Styles */
    .status-container {
        display: flex;
        align-items: center;
        gap: 5px;
    }

    .status-btn {
        background: transparent;
        border: none;
        color: #fff;
        cursor: pointer;
        font-size: 12px;
    }

    .spac-status {
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 600;
        display: inline-block;
    }

    .spac-status.active {
        background-color: #d4edda;
        color: #155724;
    }

    .spac-status.inactive {
        background-color: #fff3cd;
        color: #856404;
    }

    /* 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 {
        width: 16px;
        height: 16px;
        cursor: pointer;
    }

    /* Modal Styles */
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0, 0, 0, 0.4);
    }

    .modal-content {
        background-color: #f8f9fa;
        margin: 15% auto;
        padding: 20px;
        border: 1px solid #888;
        width: 40%;
        border-radius: 5px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    .close {
        color: #aaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
    }

    .close:hover,
    .close:focus {
        color: black;
        text-decoration: none;
        cursor: pointer;
    }

    .form-group {
        margin-bottom: 15px;
    }

    .form-group label {
        display: block;
        margin-bottom: 5px;
        font-weight: bold;
    }

    .form-control {
        width: 100%;
        padding: 8px;
        border: 1px solid #ccc;
        border-radius: 4px;
    }

    .btn {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }

    .btn-primary {
        background-color: #2c5b80;
        color: white;
    }
</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;
                });
            });
        }

        itemCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                if (selectAllCheckbox) {
                    const allChecked = Array.from(itemCheckboxes).every(cb => cb.checked);
                    selectAllCheckbox.checked = allChecked;
                }
            });
        });
    });

    function performBulkDelete() {
        const selectedItems = document.querySelectorAll('.item-checkbox:checked');
        if (selectedItems.length === 0) {
            alert('Please select at least one application to delete.');
            return;
        }
        if (confirm('Are you sure you want to delete ' + selectedItems.length + ' selected applications?')) {
            document.getElementById('applicationsForm').submit();
        }
    }

    function showStatusModal(applicationId, currentStatus) {
        document.getElementById('application_id').value = applicationId;
        document.getElementById('status').value = currentStatus;
        document.getElementById('statusModal').style.display = 'block';
    }

    function closeStatusModal() {
        document.getElementById('statusModal').style.display = 'none';
    }

    window.onclick = function(event) {
        const modal = document.getElementById('statusModal');
        if (event.target == modal) {
            modal.style.display = 'none';
        }
    }

    document.getElementById('exportExcel').addEventListener('click', function() {
        let table = document.getElementById('applicationsTable');
        let tableCopy = table.cloneNode(true);
        let rows = tableCopy.querySelectorAll('tr');
        rows.forEach(row => {
            if (row.cells.length > 0) {
                row.deleteCell(-1); // Actions
                row.deleteCell(-1); // Status (Remove for cleaner export, or keep if needed. Let's remove Status column which is 2nd from last now? No, Status is before Date. Actions is last.)
                // Wait, current table order: Checkbox, Serial, Name, Email, Phone, Position, Resume, Status, Date, Actions.
                // Let's just remove Checkbox (0), Resume (5? No indices shift when deleted), Actions (Last).
            }
        });

        // Better approach for export cleaning:
        // Indices based on header: 0:Checkbox, 1:Serial, 2:Name, 3:Email, 4:Phone, 5:Position, 6:Resume, 7:Status, 8:Date, 9:Actions
        // We want to remove: Checkbox(0), Resume(6), Status(7), Actions(9).
        // Delete from highest index to lowest to avoid shifting issues.

        rows.forEach(row => {
            // Check length to avoid errors
            if (row.cells.length >= 10) {
                row.deleteCell(9); // Actions
                row.deleteCell(7); // Status
                row.deleteCell(6); // Resume
                row.deleteCell(0); // Checkbox
            }
        });

        let wb = XLSX.utils.table_to_book(tableCopy, {
            sheet: "Career Applications"
        });
        XLSX.writeFile(wb, 'Career_Applications.xlsx');
    });

    document.getElementById('exportWord').addEventListener('click', function() {
        let table = document.getElementById('applicationsTable');
        let tableCopy = table.cloneNode(true);
        let rows = tableCopy.querySelectorAll('tr');

        rows.forEach(row => {
            if (row.cells.length >= 10) {
                row.deleteCell(9); // Actions
                row.deleteCell(7); // Status
                row.deleteCell(6); // Resume
                row.deleteCell(0); // Checkbox
            }
        });

        let html = `
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>Career Applications</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>Career Applications</h1>
            ${tableCopy.outerHTML}
        </body>
        </html>`;

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