<!-- Main Content -->
<link rel="stylesheet" href="<?= site_url('public/assets/css/datatables-custom.css') ?>">
<style>
#docHeadsTable { table-layout: fixed; width: 100% !important; }
#docHeadsTable th, #docHeadsTable td { overflow: hidden; text-overflow: ellipsis; }
#docHeadsTable .btn-icon { padding: 4px 8px; font-size: 0.75rem; }
#docHeadsTable thead th { font-size: 0.8rem; padding: 8px 4px !important; }
#docHeadsTable tbody td { font-size: 0.8rem; padding: 6px 4px !important; vertical-align: middle; }

/* Column widths */
#docHeadsTable th:nth-child(1), #docHeadsTable td:nth-child(1) { width: 4%; }
#docHeadsTable th:nth-child(2), #docHeadsTable td:nth-child(2) { width: 13%; }
#docHeadsTable th:nth-child(3), #docHeadsTable td:nth-child(3) { width: 25%; }
#docHeadsTable th:nth-child(4), #docHeadsTable td:nth-child(4) { width: 10%; }
#docHeadsTable th:nth-child(5), #docHeadsTable td:nth-child(5) { width: 12%; }
#docHeadsTable th:nth-child(6), #docHeadsTable td:nth-child(6) { width: 12%; }
#docHeadsTable th:nth-child(7), #docHeadsTable td:nth-child(7) { width: 10%; }
#docHeadsTable th:nth-child(8), #docHeadsTable td:nth-child(8) { width: 14%; white-space: nowrap; }

/* Column Search Styles */
.column-search-row input, .column-search-row select {
    width: 100%;
    padding: 4px 6px;
    border: 1px solid #e2e8f0;
    border-radius: 4px;
    font-size: 0.7rem;
    background: #fff;
}
.column-search-row input:focus, .column-search-row select:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}
.column-search-row input::placeholder { color: #94a3b8; font-size: 0.65rem; }
.column-search-row th { background: #f8fafc !important; padding: 4px !important; }

/* Rounded corners for table header */
#docHeadsTable {
    border-collapse: separate !important;
    border-spacing: 0;
    overflow: hidden;
}
#docHeadsTable thead tr:first-child th:first-child { border-top-left-radius: 14px; }
#docHeadsTable thead tr:first-child th:last-child { border-top-right-radius: 14px; }
#docHeadsTable thead tr:first-child th {
    background: linear-gradient(135deg, #1e3a5f 0%, #2d4a6f 100%);
    color: #fff;
    border: none;
    background-clip: padding-box;
}
#docHeadsTable thead tr:first-child th a, #docHeadsTable thead tr:first-child th i { color: #fff; }

/* Hide Default Search */
.dataTables_filter, .dt-search { display: none !important; }

/* Page-length buttons */
.dt-length-buttons { display: flex; gap: 0; }
.dt-paging { display: flex; align-items: center; gap: 10px; }
.dt-info { white-space: nowrap; }
#docHeadsTable_wrapper .dt-layout-start { display: flex; align-items: center; gap: 6px; }
#docHeadsTable_wrapper .dt-layout-end { display: flex; align-items: center; justify-content: flex-end; }
#docHeadsTable_wrapper .dt-info { margin: 0; white-space: nowrap; }

/* Info tooltip */
.info-tooltip { cursor: help; }
.info-tooltip:hover { opacity: 0.8; }
</style>

<div class="content">
    <div class="card position-relative shadow-sm rounded-4">
        <div class="fab-top-group" style="display: flex; gap: 8px; position: absolute; top: 8px; right: 25px; z-index: 10;">
            <button type="button" class="btn btn-outline-info btn-sm info-tooltip" data-bs-toggle="tooltip" data-bs-html="true" data-bs-placement="bottom" title="<strong><?= isset($company) ? htmlspecialchars($company->company_name) : '' ?></strong><br>Company Start Date: <?= isset($company) ? date('d-M-Y', strtotime($company->co_start_date)) : '-' ?>" style="border-radius: 50%; width: 36px; height: 36px; padding: 0;">
                <i class="fa fa-info"></i>
            </button>
            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="resetSearch()" title="Reset Search" style="border-radius: 50%; width: 36px; height: 36px; padding: 0;">
                <i class="fa fa-undo"></i>
            </button>
            <?php if (can('company_doc_heads.add')): ?>
            <button type="button" class="btn btn-primary btn-sm" onclick="showAddDocHeadModal()" title="Add Document Head" style="border-radius: 50%; width: 36px; height: 36px; padding: 0; display: flex; align-items: center; justify-content: center;">
                <i class="fa-solid fa-plus"></i>
            </button>
            <?php endif; ?>
        </div>
        
        <div class="card-body">
            <!-- Document Heads Table -->
            <?php if (!empty($doc_heads)): ?>
            <div class="table-responsive">
                <table id="docHeadsTable" class="table align-middle text-center mb-0">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th style="text-align:left;">Authority</th>
                            <th style="text-align:left;">Document Head</th>
                            <th>Frequency</th>
                            <th>Master Start</th>
                            <th>Custom Start</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                        <tr class="column-search-row">
                            <th></th>
                            <th><input type="text" class="column-search" data-column="1" placeholder="Search..."></th>
                            <th><input type="text" class="column-search" data-column="2" placeholder="Search..."></th>
                            <th><input type="text" class="column-search" data-column="3" placeholder="Search..."></th>
                            <th></th>
                            <th></th>
                            <th><select class="column-search form-select form-select-sm" data-column="6" style="font-size:0.7rem; padding:2px;">
                                <option value="">All</option>
                                <option value="Active">Active</option>
                                <option value="Pending">Pending</option>
                                <option value="Reviewed">Reviewed</option>
                                <option value="Not Assigned">Not Assigned</option>
                            </select></th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $sr = 1; foreach ($doc_heads as $head): ?>
                        <tr data-type-id="<?= $head->type_id ?>">
                            <td><?= $sr++ ?></td>
                            <td style="text-align:left;"><?= htmlspecialchars($head->authority_name) ?></td>
                            <td style="text-align:left;">
                                <?= htmlspecialchars($head->type_name) ?>
                                <?php if ($head->alias_name): ?>
                                    <br><small class="text-muted"><?= htmlspecialchars($head->alias_name) ?></small>
                                <?php endif; ?>
                            </td>
                            <td><?= ucfirst($head->frequency) ?></td>
                            <td><?= $head->master_start_date ? date('d-M-Y', strtotime($head->master_start_date)) : '-' ?></td>
                            <td><?= $head->custom_start_date ? date('d-M-Y', strtotime($head->custom_start_date)) : '-' ?></td>
                            <td>
                                <?php
                                switch ($head->status) {
                                    case 'active':
                                        echo '<span class="badge bg-success">🟢 Active</span>';
                                        break;
                                    case 'reviewed':
                                        echo '<span class="badge bg-warning text-dark">🟡 Reviewed</span>';
                                        break;
                                    case 'pending':
                                        echo '<span class="badge bg-danger">🔴 Pending</span>';
                                        break;
                                    default:
                                        echo '<span class="badge bg-secondary">⚪ Not Assigned</span>';
                                }
                                ?>
                            </td>
                            <td style="white-space: nowrap;">
                                <?php if ($head->status == 'not_assigned'): ?>
                                    <?php if (can('company_doc_heads.add')): ?>
                                    <button class="btn btn-sm btn-outline-primary btn-icon" onclick="addDocHead(<?= $head->type_id ?>)" title="Add">
                                        <i class="fas fa-plus"></i>
                                    </button>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <a href="<?= base_url('companydocheads/edit/' . $selected_company_id . '/' . $head->type_id) ?>" 
                                       class="btn btn-sm btn-warning btn-icon" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    
                                    <?php if ($head->status == 'active'): ?>
                                        <?php if (can('company_doc_heads.activate')): ?>
                                        <button class="btn btn-sm btn-danger btn-icon" 
                                                onclick="deactivateDocHead(<?= $selected_company_id ?>, <?= $head->type_id ?>)" 
                                                title="Deactivate">
                                            <i class="fas fa-power-off"></i>
                                        </button>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <?php if (can('company_doc_heads.activate')): ?>
                                        <button class="btn btn-sm btn-success btn-icon" 
                                                onclick="showActivateModal(<?= $selected_company_id ?>, <?= $head->type_id ?>, '<?= $head->master_start_date ?>', '<?= $head->custom_start_date ?>')" 
                                                title="Activate">
                                            <i class="fas fa-check"></i>
                                        </button>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php else: ?>
            <div class="alert alert-info">
                <i class="fas fa-info-circle"></i> No document heads found for this company.
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Activate Modal -->
<div class="modal fade" id="activateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title"><i class="fas fa-check"></i> Activate Document Head</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Set the document start date for this company. This date cannot be earlier than the company start date.</p>
                
                <input type="hidden" id="activate_company_id">
                <input type="hidden" id="activate_type_id">
                
                <div class="mb-3">
                    <label class="form-label">Company Start Date</label>
                    <p class="form-control-plaintext">
                        <strong><?= isset($company) ? date('d-M-Y', strtotime($company->co_start_date)) : '-' ?></strong>
                    </p>
                </div>
                
                <div class="mb-3">
                    <label for="activate_start_date" class="form-label">Document Start Date <span class="text-danger">*</span></label>
                    <input type="date" class="form-control" id="activate_start_date" required 
                           min="<?= isset($company) ? date('Y-m-d', strtotime($company->co_start_date)) : '' ?>">
                    <small class="text-muted">Must be on or after company start date</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" onclick="confirmActivate()">
                    <i class="fas fa-check"></i> Activate
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Add Document Head Modal -->
<div class="modal fade" id="addDocHeadModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-plus"></i> Add Document Head</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="availableDocHeadsList">
                    <p class="text-center"><i class="fas fa-spinner fa-spin"></i> Loading...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script src="<?php echo site_url(); ?>public/assets/js/jquery-1.11.1.min.js"></script>
<script src="<?php echo site_url(); ?>public/assets/js/dataTables.js"></script>
<script src="<?php echo site_url(); ?>public/assets/js/dataTables.bootstrap5.js"></script>
<script src="<?php echo site_url(); ?>public/assets/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
var companyId = <?= $selected_company_id ?>;
var table;

$(document).ready(function() {
    // Initialize tooltip
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    table = $('#docHeadsTable').DataTable({
        paging: true,
        searching: true,
        ordering: true,
        info: true,
        lengthChange: true,
        pageLength: 25,
        order: [[1, 'asc'], [2, 'asc']],
        orderCellsTop: true,
        columnDefs: [
            { orderable: false, targets: [0, 7] }
        ]
    });

    // Recalculate serial numbers after sort/search/page
    table.on('draw.dt', function () {
        var start = table.page.info().start;
        table.column(0, {page:'current'}).nodes().each(function(cell, i) {
            cell.innerHTML = start + i + 1;
        });
        moveDtControls();
        replaceLengthDropdown();
    });

    // Column search
    $('.column-search').on('keyup change', function() {
        var colIdx = $(this).data('column');
        table.column(colIdx).search(this.value).draw();
    });

    function moveDtControls() {
        const $wrapper = $('#docHeadsTable_wrapper');
        const $topRow = $wrapper.children('.row').first();
        const $dtLength = $topRow.find('.dt-length');
        const $bottomRow = $wrapper.children('.row').last();
        const $bottomLeft = $bottomRow.find('.dt-layout-start');
        const $bottomRight = $bottomRow.find('.dt-layout-end');
        const $dtInfo = $bottomRow.find('.dt-info');
        if (!$bottomLeft.find('.dt-length').length) $dtLength.appendTo($bottomLeft);
        if (!$bottomRight.find('.dt-info').length) $dtInfo.prependTo($bottomRight);
    }

    function replaceLengthDropdown() {
        const $wrapper = $('#docHeadsTable_wrapper');
        const $lengthContainer = $wrapper.find('.dt-length');
        if ($lengthContainer.find('.dt-length-buttons').length) return;
        const pageLengths = [10, 25, 50, -1];
        const currentLength = table.page.len();
        $lengthContainer.find('select, label').hide();
        let html = '<ul class="pagination pagination-sm mb-0 dt-length-buttons">';
        pageLengths.forEach(len => {
            const label = len === -1 ? 'All' : len;
            const isActive = (len === -1 && currentLength === -1) || (len !== -1 && currentLength === len);
            html += `<li class="page-item ${isActive ? 'active' : ''}"><button class="page-link dt-len-btn" data-len="${len}">${label}</button></li>`;
        });
        html += '</ul>';
        $lengthContainer.append(html);
    }

    $(document).on('click', '.dt-len-btn', function () {
        const len = parseInt($(this).data('len'), 10);
        table.page.len(len).draw();
        $(this).closest('.dt-length-buttons').find('.page-item').removeClass('active');
        $(this).parent('.page-item').addClass('active');
    });

    moveDtControls();
    replaceLengthDropdown();
});

function resetSearch() {
    $('.column-search').val('');
    table.search('').columns().search('');
    table.order([[1, 'asc'], [2, 'asc']]);
    table.page('first');
    table.draw();
}

function showActivateModal(companyId, typeId, masterStart, customStart) {
    document.getElementById('activate_company_id').value = companyId;
    document.getElementById('activate_type_id').value = typeId;
    var startDate = customStart || masterStart || '';
    if (startDate) {
        document.getElementById('activate_start_date').value = startDate;
    }
    var modal = new bootstrap.Modal(document.getElementById('activateModal'));
    modal.show();
}

function confirmActivate() {
    var companyId = document.getElementById('activate_company_id').value;
    var typeId = document.getElementById('activate_type_id').value;
    var startDate = document.getElementById('activate_start_date').value;
    
    if (!startDate) {
        alert('Please enter a document start date.');
        return;
    }
    
    $.ajax({
        url: '<?= base_url('companydocheads/activate') ?>',
        type: 'POST',
        data: { company_id: companyId, type_id: typeId, custom_start_date: startDate },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                Swal.fire('Success!', response.message, 'success').then(() => location.reload());
            } else {
                Swal.fire('Error!', response.message, 'error');
            }
        },
        error: function() { Swal.fire('Error!', 'An error occurred. Please try again.', 'error'); }
    });
}

function deactivateDocHead(companyId, typeId) {
    Swal.fire({
        title: 'Deactivate?',
        text: 'This will hide the document head from uploads and reports.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        confirmButtonText: 'Yes, deactivate'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: '<?= base_url('companydocheads/deactivate') ?>',
                type: 'POST',
                data: { company_id: companyId, type_id: typeId },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire('Deactivated!', response.message, 'success').then(() => location.reload());
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                },
                error: function() { Swal.fire('Error!', 'An error occurred. Please try again.', 'error'); }
            });
        }
    });
}

function addDocHead(typeId) {
    $.ajax({
        url: '<?= base_url('companydocheads/add') ?>',
        type: 'POST',
        data: { company_id: companyId, type_id: typeId },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                Swal.fire('Added!', response.message, 'success').then(() => location.reload());
            } else {
                Swal.fire('Error!', response.message, 'error');
            }
        },
        error: function() { Swal.fire('Error!', 'An error occurred. Please try again.', 'error'); }
    });
}

function showAddDocHeadModal() {
    $.ajax({
        url: '<?= base_url('companydocheads/getAvailable') ?>',
        type: 'POST',
        data: { company_id: companyId },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                var html = '<table class="table table-sm table-hover"><thead><tr><th>Authority</th><th>Document Head</th><th>Action</th></tr></thead><tbody>';
                if (response.data.length === 0) {
                    html = '<div class="alert alert-info">All document heads are already assigned to this company.</div>';
                } else {
                    response.data.forEach(function(item) {
                        html += '<tr>';
                        html += '<td>' + (item.authority_name || '-') + '</td>';
                        html += '<td>' + item.type_name + (item.alias_name ? '<br><small class="text-muted">' + item.alias_name + '</small>' : '') + '</td>';
                        html += '<td><button class="btn btn-sm btn-primary" onclick="addDocHead(' + item.id + ')"><i class="fas fa-plus"></i> Add</button></td>';
                        html += '</tr>';
                    });
                    html += '</tbody></table>';
                }
                document.getElementById('availableDocHeadsList').innerHTML = html;
            } else {
                document.getElementById('availableDocHeadsList').innerHTML = '<div class="alert alert-danger">' + response.message + '</div>';
            }
        },
        error: function() {
            document.getElementById('availableDocHeadsList').innerHTML = '<div class="alert alert-danger">Failed to load available document heads.</div>';
        }
    });
    var modal = new bootstrap.Modal(document.getElementById('addDocHeadModal'));
    modal.show();
}
</script>
