<!-- Reorder Documents Page - Modern UI -->
<style>
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&display=swap');

.reorder-container {
    font-family: 'Outfit', sans-serif;
    background: linear-gradient(135deg, #f5f7fa 0%, #e4e8ec 100%);
    min-height: 100vh;
    padding: 1.5rem;
}

/* Page Header */
/*.page-header {
    background: linear-gradient(135deg, #1e3a5f 0%, #2d4a6f 100%);
    color: #fff;
    padding: 1rem 1.25rem;
    border-radius: 16px 16px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0;
}*/

/* Page Header – match DataTable header size */
.page-header {
    background: linear-gradient(135deg, #1e3a5f 0%, #2d4a6f 100%);
    color: #fff;

    /* MATCH table header */
    font-size: 0.8rem;
    padding: 8px 12px;

    border-radius: 16px 16px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0;
}

.page-header h3 {
    margin: 0;
    font-size: 1rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.page-header__badge {
    background: rgba(255,255,255,0.2);
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
}

/* Main Card */
.reorder-card {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    overflow: hidden;
    margin-bottom: 1.5rem;
}

/* Filters Section */
.reorder-filters {
    background: #f8fafc;
    padding: 1rem 1.5rem;
    border-bottom: 1px solid #e2e8f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
}

.filter-group {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.filter-group label {
    font-size: 0.85rem;
    color: #64748b;
    font-weight: 500;
    margin: 0;
}

.filter-group select {
    padding: 0.5rem 0.75rem;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    font-size: 0.85rem;
    color: #334155;
    background: #fff;
    min-width: 80px;
    cursor: pointer;
    transition: all 0.2s;
}

.filter-group select:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.search-box {
    position: relative;
    max-width: 320px;
}

.search-box input {
    padding: 0.5rem 1rem 0.5rem 2.5rem;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    font-size: 0.85rem;
    width: 100%;
    transition: all 0.2s;
}

.search-box input:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.search-box i {
    position: absolute;
    left: 0.875rem;
    top: 50%;
    transform: translateY(-50%);
    color: #94a3b8;
}

/* Content Area */
.reorder-content {
    padding: 1.5rem;
    max-height: calc(100vh - 350px);
    overflow-y: auto;
}

/* Type Card (Expandable) */
.type-card {
    background: #fff;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    margin-bottom: 1rem;
    overflow: hidden;
    transition: all 0.2s;
    box-shadow: 0 2px 4px rgba(0,0,0,0.02);
}

.type-card:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

.type-card.expanded {
    border-color: #3b82f6;
}

/* Type Header */
.type-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 1.25rem;
    cursor: pointer;
    background: linear-gradient(135deg, #f8fafc 0%, #fff 100%);
    border-bottom: 1px solid transparent;
    transition: all 0.2s;
}

.type-header:hover {
    background: linear-gradient(135deg, #f1f5f9 0%, #f8fafc 100%);
}

.type-card.expanded .type-header {
    background: linear-gradient(135deg, #eff6ff 0%, #f8fafc 100%);
    border-bottom-color: #e2e8f0;
}

.type-info {
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.type-icon {
    width: 40px;
    height: 40px;
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 1rem;
}

.type-details h4 {
    margin: 0;
    font-size: 0.95rem;
    font-weight: 600;
    color: #1e293b;
}

.type-details .alias {
    font-size: 0.8rem;
    color: #64748b;
    margin-top: 2px;
}

.type-meta {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.doc-count {
    background: #dbeafe;
    color: #1d4ed8;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
}

.toggle-icon {
    width: 28px;
    height: 28px;
    background: #f1f5f9;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #64748b;
    transition: all 0.2s;
}

.type-card.expanded .toggle-icon {
    background: #3b82f6;
    color: #fff;
    transform: rotate(180deg);
}

/* Type Body (Document List) */
.type-body {
    display: none;
    padding: 1rem 1.25rem 1.25rem;
    background: #fafbfc;
}

.type-card.expanded .type-body {
    display: block;
}

/* Document List */
.doc-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.doc-item {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 8px 12px;
    background: #fff;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    margin-bottom: 0.5rem;
    cursor: move;
    transition: all 0.2s;
}

.doc-item:hover {
    border-color: #3b82f6;
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.12);
    background: #fafbff;
}

.doc-item.ui-sortable-helper {
    background: #eff6ff !important;
    border-color: #3b82f6 !important;
    box-shadow: 0 8px 20px rgba(59, 130, 246, 0.25) !important;
    transform: rotate(1deg);
}

.doc-item.ui-sortable-placeholder {
    background: #dbeafe;
    border: 2px dashed #3b82f6;
    visibility: visible !important;
    height: 40px;
}

.drag-handle {
    color: #94a3b8;
    font-size: 1rem;
    cursor: grab;
}

.doc-number {
    background: linear-gradient(135deg, #64748b 0%, #475569 100%);
    color: #fff;
    min-width: 28px;
    height: 28px;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.8rem;
    font-weight: 600;
}

.doc-name {
    flex: 1;
    font-size: 1rem;
    color: #334155;
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* Save Button */
.save-btn {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: #fff;
    border: none;
    padding: 0.625rem 1.25rem;
    border-radius: 8px;
    font-size: 0.85rem;
    font-weight: 500;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    transition: all 0.2s;
    margin-top: 0.75rem;
}

.save-btn:hover {
    background: linear-gradient(135deg, #059669 0%, #047857 100%);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.save-btn:active {
    transform: translateY(0);
}

/* Footer (Pagination) */
.reorder-footer {
    background: #f8fafc;
    padding: 1rem 1.5rem;
    border-top: 1px solid #e2e8f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
}

.page-info {
    font-size: 0.85rem;
    color: #64748b;
}

.pagination {
    display: flex;
    gap: 0.25rem;
    margin: 0;
    padding: 0;
    list-style: none;
}

.pagination .page-item .page-link {
    padding: 0.5rem 0.875rem;
    border: 1px solid #e2e8f0;
    background: #fff;
    color: #334155;
    font-size: 0.85rem;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.15s;
    text-decoration: none;
    display: block;
}

.pagination .page-item .page-link:hover {
    background: #f1f5f9;
    border-color: #cbd5e1;
}

.pagination .page-item.active .page-link {
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    border-color: #3b82f6;
    color: #fff;
}

.pagination .page-item.disabled .page-link {
    background: #f8fafc;
    color: #94a3b8;
    cursor: not-allowed;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 3rem 1rem;
    color: #94a3b8;
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 1rem;
    opacity: 0.5;
}

.empty-state p {
    font-size: 0.9rem;
    margin: 0;
}

/* Responsive */
@media (max-width: 768px) {
    .reorder-filters {
        flex-direction: column;
        align-items: stretch;
    }
    
    .search-box {
        max-width: 100%;
    }
    
    .type-meta {
        flex-wrap: wrap;
    }
    
    .reorder-footer {
        flex-direction: column;
        text-align: center;
    }
}

/* Success Toast */
.success-toast {
    position: fixed;
    bottom: 2rem;
    right: 2rem;
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: #fff;
    padding: 1rem 1.5rem;
    border-radius: 10px;
    box-shadow: 0 4px 20px rgba(16, 185, 129, 0.3);
    display: flex;
    align-items: center;
    gap: 0.75rem;
    z-index: 1000;
    animation: slideIn 0.3s ease;
}

@keyframes slideIn {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}
.empty-strip {
    background: #d9f7ff;
    border: 1px solid #a5e7ff;
    color: #0c5460;
    padding: 12px 16px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 0.9rem;
    font-weight: 500;
}

.empty-strip i {
    font-size: 1rem;
    opacity: 0.9;
}

</style>

<?php $filtered_sub_types = [];

foreach ($sub_types as $row) {
    if (count($row['documents']) > 1) {
        $filtered_sub_types[] = $row;
    }
} ?>
<div class="reorder-container content">
    <div class="reorder-card">
        <!-- Header -->
        <div class="page-header">
            <h3>
                <i class="fa fa-arrows-alt"></i>
                <span>Reorder Documents</span>
                <span class="page-header__badge" id="totalCount"><?= count($filtered_sub_types) ?> Items</span>
            </h3>
        </div>
        <?php if (!empty($filtered_sub_types)): ?>
        <!-- Filters -->
        <div class="reorder-filters">
            <div class="filter-group">
                <label>Show</label>
                <select id="perPageSelect">
                    <option value="5">5</option>
                    <option value="10" selected>10</option>
                    <option value="20">20</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                </select>
                <label>entries</label>
            </div>
            
            <div class="search-box">
                <i class="fa fa-search"></i>
                <input type="text" id="searchBox" placeholder="Search document head or document name...">
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Content -->
        <div class="reorder-content" id="typeContainer">
            <?php 
            $hasTypes = false;
            foreach ($sub_types as $row): 
                if (count($row['documents']) > 1): 
                    $hasTypes = true;
            ?>
                <div class="type-card" data-type-id="<?= $row['id'] ?>">
                    <div class="type-header" data-target="docList_<?= $row['id'] ?>">
                        <div class="type-info">
                            <div class="type-icon">
                                <i class="fa fa-folder"></i>
                            </div>
                            <div class="type-details">
                                <h4><?= htmlspecialchars($row['type_name']) ?></h4>
                                <div class="alias"><?= htmlspecialchars($row['alias_name']) ?></div>
                            </div>
                        </div>
                        <div class="type-meta">
                            <span class="doc-count">
                                <i class="fa fa-file-alt me-1"></i>
                                <?= count($row['documents']) ?> Documents
                            </span>
                            <div class="toggle-icon">
                                <i class="fa fa-chevron-down"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div class="type-body" id="docList_<?= $row['id'] ?>">
                        <ul class="doc-list <?= (isset($is_view_only) && $is_view_only) ? '' : 'sortable' ?>">
                            <?php foreach ($row['documents'] as $index => $doc): ?>
                                <li class="doc-item" data-id="<?= $doc['id'] ?>">
                                    <?php if (!(isset($is_view_only) && $is_view_only)): ?>
                                    <span class="drag-handle"><i class="fa fa-grip-vertical"></i></span>
                                    <?php else: ?>
                                    <span class="drag-handle" style="visibility: hidden;"><i class="fa fa-grip-vertical"></i></span>
                                    <?php endif; ?>
                                    <span class="doc-number"><?= $index + 1 ?></span>
                                    <span class="doc-name"><?= htmlspecialchars($doc['name']) ?></span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                        <?php if (!(isset($is_view_only) && $is_view_only)): ?>
                        <button class="save-btn saveOrderBtn" data-type="<?= $row['id'] ?>">
                            <i class="fa fa-save"></i> Save Order
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
            <?php 
                endif;
            endforeach; 
            
            if (!$hasTypes):
            ?>
                <div class="empty-strip">
                    <i class="fa fa-info-circle"></i>
                    <span>No document heads were found.</span>
                </div>
            <?php endif; ?>
        </div>
        <?php if (!empty($filtered_sub_types)): ?>
            <!-- Footer -->
            <div class="reorder-footer">
                <div class="page-info" id="pageInfo">
                    Showing 1 to 10 of <?= count($sub_types) ?> entries
                </div>
                <nav>
                    <ul class="pagination" id="pagination">
                        <!-- Pagination will be generated by JS -->
                    </ul>
                </nav>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- jQuery UI for Sortable -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.14.1/jquery-ui.min.js"></script>

<script>
$(function() {
    // Variables
    const $container = $("#typeContainer");
    const $cards = $container.find(".type-card");
    const $searchBox = $("#searchBox");
    const $perPageSelect = $("#perPageSelect");
    const $pagination = $("#pagination");
    const $pageInfo = $("#pageInfo");

    if ($cards.length === 0) {
        $pageInfo.text("No document heads found");
        $pagination.hide();
        return;
    }
    
    let filteredCards = $cards;
    let perPage = parseInt($perPageSelect.val(), 10) || 10;
    let currentPage = 1;
    
    // Initialize Sortable
    $(".sortable").sortable({
        handle: ".drag-handle",
        placeholder: "doc-item ui-sortable-placeholder",
        axis: "y",
        update: function(event, ui) {
            const $list = $(this);
            $list.find(".doc-item").each(function(i) {
                $(this).find(".doc-number").text(i + 1);
            });
        }
    });
    
    // Expand/Collapse Type Cards
    $(document).on("click", ".type-header", function() {
        const $card = $(this).closest(".type-card");
        $card.toggleClass("expanded");
    });
    
    // Save Order
    $(document).on("click", ".saveOrderBtn", function() {
        const $btn = $(this);
        const typeId = $btn.data("type");
        let ids = [];
        
        $("#docList_" + typeId + " .sortable .doc-item").each(function() {
            ids.push($(this).data("id"));
        });
        
        $btn.prop("disabled", true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');
        
        $.ajax({
            url: "<?= base_url('type/save_order') ?>",
            method: "POST",
            data: {
                type_id: typeId,
                sequence: ids
            },
            success: function(response) {
                $btn.prop("disabled", false).html('<i class="fa fa-save"></i> Save Order');
                showToast("Order saved successfully!");
            },
            error: function() {
                $btn.prop("disabled", false).html('<i class="fa fa-save"></i> Save Order');
                alert("Error saving order. Please try again.");
            }
        });
    });
    
    // Show Toast Message
    function showToast(message) {
        const $toast = $(`
            <div class="success-toast">
                <i class="fa fa-check-circle"></i>
                <span>${message}</span>
            </div>
        `);
        $("body").append($toast);
        setTimeout(() => {
            $toast.fadeOut(300, function() { $(this).remove(); });
        }, 3000);
    }
    
    // Filter and Pagination Functions
    function applyFilters() {
        const term = $searchBox.val().toLowerCase().trim();
        
        if (term === "") {
            filteredCards = $cards;
        } else {
            filteredCards = $cards.filter(function() {
                const $card = $(this);
                const headerText = $card.find(".type-details").text().toLowerCase();
                const docsText = $card.find(".doc-name").text().toLowerCase();
                return headerText.indexOf(term) !== -1 || docsText.indexOf(term) !== -1;
            });
        }
        
        currentPage = 1;
        renderPage();
    }
    
    function renderPage() {
        const totalCards = filteredCards.length;
        const totalPages = Math.max(1, Math.ceil(totalCards / perPage));
        
        if (currentPage > totalPages) currentPage = totalPages;
        
        // Hide all, show only current page
        $cards.hide();
        if (totalCards > 0) {
            const start = (currentPage - 1) * perPage;
            const end = Math.min(start + perPage, totalCards);
            filteredCards.slice(start, end).show();
            
            $pageInfo.text(`Showing ${start + 1} to ${end} of ${totalCards} entries`);
        } else {
            $pageInfo.text("No matching document heads found");
        }
        
        buildPagination(totalPages, totalCards);
    }
    
    function buildPagination(totalPages, totalCards) {
        $pagination.empty();
        
        if (totalCards === 0 || totalPages <= 1) return;
        
        // Previous
        const prevDisabled = currentPage === 1 ? "disabled" : "";
        $pagination.append(`
            <li class="page-item ${prevDisabled}">
                <a class="page-link" data-page="${currentPage - 1}">
                    <i class="fa fa-chevron-left"></i>
                </a>
            </li>
        `);
        
        // Page Numbers (show max 5)
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        if (endPage - startPage < 4) {
            startPage = Math.max(1, endPage - 4);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const active = i === currentPage ? "active" : "";
            $pagination.append(`
                <li class="page-item ${active}">
                    <a class="page-link" data-page="${i}">${i}</a>
                </li>
            `);
        }
        
        // Next
        const nextDisabled = currentPage === totalPages ? "disabled" : "";
        $pagination.append(`
            <li class="page-item ${nextDisabled}">
                <a class="page-link" data-page="${currentPage + 1}">
                    <i class="fa fa-chevron-right"></i>
                </a>
            </li>
        `);
    }
    
    // Pagination Click
    $(document).on("click", ".pagination .page-link", function(e) {
        e.preventDefault();
        const $item = $(this).closest(".page-item");
        if ($item.hasClass("disabled") || $item.hasClass("active")) return;
        
        currentPage = parseInt($(this).data("page"), 10);
        renderPage();
    });
    
    // Search Input
    $searchBox.on("input", function() {
        applyFilters();
    });
    
    // Per Page Change
    $perPageSelect.on("change", function() {
        perPage = parseInt($(this).val(), 10) || 10;
        currentPage = 1;
        renderPage();
    });
    
    // Initial Render
    applyFilters();
});
</script>