<?php include ROOT_PATH . '/admin/templates/header.php'; ?>
<?php
$MAX_SECTIONS=4;
$currentCount=is_array($sections)?count($sections):0;
$limitReached=$currentCount>=$MAX_SECTIONS;
$reorderUrl='/admin/footer/reorder';
?>

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

<div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
    <div>
        <h3 class="mb-1 fw-bold"><i class="bi bi-layout-sidebar-reverse me-2 text-primary"></i><?= __('footer.sections','Footer Sections') ?></h3>
        <p class="text-muted mb-0 small">
            <?= __('footer.sections_limit','Maximum sections') ?>: <?= $MAX_SECTIONS ?> —
            <?= __('footer.sections_used','Used') ?>: <?= $currentCount ?>
        </p>
    </div>
    <div class="d-flex gap-2">
        <?php if(!empty($sections)): ?>
        <button id="saveOrderBtn" class="btn btn-outline-primary btn-sm" type="button">
            <i class="bi bi-save me-1"></i><?= __('footer.save_order','Save Order') ?>
        </button>
        <?php endif; ?>
        <?php if(!$limitReached): ?>
        <a href="/admin/footer/create" class="btn btn-primary btn-sm">
            <i class="bi bi-plus-lg me-1"></i><?= __('footer.create_section','Add Section') ?>
        </a>
        <?php endif; ?>
    </div>
</div>

<?php if($limitReached): ?>
<div class="alert alert-info border-0 py-2 small"><i class="bi bi-info-circle me-1"></i><?= __('footer.max_sections_info','Maximum sections reached.') ?></div>
<?php endif; ?>

<div id="orderAlert" class="alert d-none" role="alert"></div>

<?php if(!empty($sections)): ?>
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
        <h6 class="mb-0 fw-semibold"><i class="bi bi-grip-vertical me-2 text-muted"></i><?= __('footer.drag_to_reorder','Drag to reorder') ?></h6>
    </div>
    <div class="card-body p-0">
        <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th style="width:48px" class="ps-3"></th>
                    <th><?= __('footer.section_title','Title') ?></th>
                    <th><?= __('footer.section_type','Type') ?></th>
                    <th class="text-end pe-3"><?= __('actions.actions','Actions') ?></th>
                </tr>
            </thead>
            <tbody id="sectionsTbody">
            <?php
            $typeBadge=['pages'=>'bg-info','contact'=>'bg-success','social'=>'bg-warning text-dark','branding'=>'bg-primary'];
            foreach($sections as $section):
                $type=$section['type']??'links';
                $typeLabel=['pages'=>__('footer.type_pages','Pages'),'contact'=>__('footer.type_contact','Contact'),'social'=>__('footer.type_social','Social'),'branding'=>__('footer.type_branding','Branding')][$type]??__('footer.type_links','Links');
            ?>
            <tr data-id="<?= (int)$section['id'] ?>">
                <td class="ps-3 text-center" style="cursor:grab"><i class="bi bi-grip-vertical text-muted fs-5 drag-handle"></i></td>
                <td class="fw-semibold"><?= htmlspecialchars($section['title']) ?></td>
                <td><span class="badge <?= $typeBadge[$type]??'bg-secondary' ?>"><?= $typeLabel ?></span></td>
                <td class="text-end pe-3">
                    <a href="/admin/footer/edit/<?= (int)$section['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-pencil"></i></a>
                    <form method="post" action="/admin/footer/delete/<?= (int)$section['id'] ?>" class="d-inline" onsubmit="return confirm('<?= __('actions.confirm_delete','Are you sure?') ?>')">
                        <?= \Core\System\Csrf::field() ?>
                        <button type="submit" class="btn btn-sm btn-outline-danger"><i class="bi bi-trash3"></i></button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div class="card-footer bg-white border-top py-2">
        <small class="text-muted"><i class="bi bi-info-circle me-1"></i><?= __('footer.reorder_help','Drag rows to reorder, then click Save Order.') ?></small>
    </div>
</div>
<?php else: ?>
<div class="card border-0 shadow-sm">
    <div class="card-body text-center py-5 text-muted">
        <i class="bi bi-layout-sidebar-reverse display-4 d-block mb-2 opacity-50"></i>
        <p class="mb-3"><?= __('footer.no_sections','No footer sections created yet.') ?></p>
        <a href="/admin/footer/create" class="btn btn-primary btn-sm"><i class="bi bi-plus-lg me-1"></i><?= __('footer.create_section','Add Section') ?></a>
    </div>
</div>
<?php endif; ?>

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

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.2/Sortable.min.js"></script>
<script>
(function(){
    const tbody=document.getElementById('sectionsTbody'),saveBtn=document.getElementById('saveOrderBtn'),alertBox=document.getElementById('orderAlert'),reorderUrl=<?= json_encode($reorderUrl) ?>;
    function showAlert(t,m){if(!alertBox)return;alertBox.className='alert alert-'+t;alertBox.textContent=m;alertBox.classList.remove('d-none');setTimeout(()=>alertBox.classList.add('d-none'),2500);}
    function collectOrder(){if(!tbody)return[];return Array.from(tbody.querySelectorAll('tr[data-id]')).map((tr,idx)=>({id:tr.getAttribute('data-id'),position:idx+1}));}
    if(tbody&&window.Sortable)new Sortable(tbody,{handle:'.drag-handle',animation:150});
    async function saveOrder(){const order=collectOrder();if(!order.length)return;try{const res=await fetch(reorderUrl,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({order})});const data=await res.json().catch(()=>({}));if(data&&data.success)showAlert('success',<?= json_encode(__('footer.order_saved','Order saved.')) ?>);else showAlert('danger',<?= json_encode(__('footer.order_save_failed','Failed to save.')) ?>);}catch(e){showAlert('danger',<?= json_encode(__('footer.order_save_failed','Failed to save.')) ?>);}}
    if(saveBtn)saveBtn.addEventListener('click',saveOrder);
})();
</script>
<?php include ROOT_PATH . '/admin/templates/footer.php'; ?>