<?php
require_once 'includes/auth.php';
requireRole('superadmin');

$currentTable = $_GET['table'] ?? 'users';
?>

<div style="display: flex; flex-direction: column; gap: 1.5rem; height: calc(100vh - 140px);">
    <!-- Header / Toolbar -->
    <div style="display: flex; justify-content: space-between; align-items: center; background: var(--bg-card); padding: 1.25rem 1.75rem; border-radius: 24px; border: 1px solid var(--border); box-shadow: var(--shadow-lg);">
        <div>
            <div style="display: flex; align-items: center; gap: 0.75rem; margin-bottom: 0.25rem;">
                <div id="table-icon-header" style="width: 32px; height: 32px; background: var(--primary)15; color: var(--primary); border-radius: 8px; display: flex; align-items: center; justify-content: center;">
                    <i class="fas fa-users"></i>
                </div>
                <h1 id="current-table-title" style="font-size: 1.5rem; font-weight: 800; color: var(--text-main); margin: 0;">Users</h1>
            </div>
            <p id="current-table-desc" style="font-size: 0.9rem; color: var(--text-muted); margin: 0;">Manage system users and access levels</p>
        </div>
        <div style="display: flex; gap: 1.25rem; align-items: center;">
            <div style="position: relative;">
                <i class="fas fa-search" style="position: absolute; left: 1.25rem; top: 50%; transform: translateY(-50%); color: var(--text-muted); opacity: 0.5;"></i>
                <input type="text" id="adminSearch" class="form-control" placeholder="Search records..." style="padding-left: 3rem; border-radius: 50px; background: var(--bg-dark); border: 1px solid var(--border); width: 320px; height: 48px;">
            </div>
            <button class="btn btn-primary" onclick="openRecordModal()" style="border-radius: 14px; padding: 0 1.75rem; height: 48px; font-weight: 700; box-shadow: 0 10px 15px -3px rgba(124, 58, 237, 0.3);">
                <i class="fas fa-plus"></i> Add New Record
            </button>
        </div>
    </div>

    <!-- Table View -->
    <div style="flex: 1; background: var(--bg-card); border-radius: 28px; border: 1px solid var(--border); overflow: hidden; box-shadow: var(--shadow-xl); display: flex; flex-direction: column; position: relative;">
        <div id="table-loader" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(255,255,255,0.7); display: none; align-items: center; justify-content: center; z-index: 10; backdrop-filter: blur(2px);">
            <div class="loader-spinner"></div>
        </div>
        <div style="overflow-x: auto; flex: 1;">
            <table class="admin-table" style="width: 100%; border-collapse: collapse;">
                <thead id="table-head">
                    <!-- Columns will be injected -->
                </thead>
                <tbody id="table-body">
                    <!-- Rows will be injected -->
                </tbody>
            </table>
        </div>
        
        <!-- Pagination Footer -->
        <div style="padding: 1.25rem 1.75rem; border-top: 1px solid var(--border); background: var(--bg-dark); display: flex; justify-content: space-between; align-items: center;">
            <div style="font-size: 0.85rem; color: var(--text-muted);">
                Showing <span id="pag-start" style="color: var(--text-main); font-weight: 700;">0</span> - <span id="pag-end" style="color: var(--text-main); font-weight: 700;">0</span> of <span id="pag-total" style="color: var(--text-main); font-weight: 700;">0</span> records
            </div>
            <div style="display: flex; gap: 0.5rem;">
                <button id="btn-prev" class="btn btn-sm" style="padding: 0.5rem 1rem; background: var(--bg-card); border: 1px solid var(--border);" onclick="changePage(-1)">
                    <i class="fas fa-chevron-left"></i> Previous
                </button>
                <div id="page-numbers" style="display: flex; gap: 0.25rem; align-items: center;">
                    <!-- Page numbers injected here -->
                </div>
                <button id="btn-next" class="btn btn-sm" style="padding: 0.5rem 1rem; background: var(--bg-card); border: 1px solid var(--border);" onclick="changePage(1)">
                    Next <i class="fas fa-chevron-right"></i>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Generic Record Modal -->
<div id="recordModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 600px; width: 90vw;">
        <div class="modal-header">
            <h2 id="modal-title">Record Details</h2>
            <button class="btn-icon" onclick="closeModal('recordModal')"><i class="fas fa-times"></i></button>
        </div>
        <form id="recordForm" onsubmit="saveRecord(event)">
            <input type="hidden" name="id" id="field-id">
            <div class="modal-body" id="modal-fields" style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
                <!-- Fields will be generated -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn" onclick="closeModal('recordModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Changes</button>
            </div>
        </form>
    </div>
</div>

<style>
    .admin-table th {
        background: var(--bg-dark);
        padding: 1.25rem 1rem;
        font-size: 0.7rem;
        font-weight: 800;
        text-transform: uppercase;
        color: var(--text-muted);
        letter-spacing: 1px;
        text-align: left;
        border-bottom: 2px solid var(--border);
        position: sticky;
        top: 0;
        z-index: 5;
    }
    .admin-table td {
        padding: 1rem;
        border-bottom: 1px solid var(--border);
        font-size: 0.875rem;
        color: var(--text-main);
        vertical-align: middle;
    }
    .admin-table tr:hover {
        background: rgba(0,0,0,0.01);
    }
    .status-badge {
        padding: 0.25rem 0.75rem;
        border-radius: 50px;
        font-size: 0.7rem;
        font-weight: 800;
        text-transform: uppercase;
    }
    .loader-spinner {
        width: 40px;
        height: 40px;
        border: 4px solid var(--border);
        border-top: 4px solid var(--primary);
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
</style>

<script>
let currentTable = '<?php echo $currentTable; ?>';
let tableData = [];
let currentPage = 1;
let totalPages = 1;

let tableMetadata = {
    users: { title: 'Users', desc: 'Manage system users and access levels', icon: 'fa-users' },
    roles: { title: 'Roles', desc: 'Define user permission groups', icon: 'fa-user-tag' },
    dashboards: { title: 'Dashboards', desc: 'Custom dashboard configurations', icon: 'fa-tachometer-alt' },
    workflow_stages: { title: 'Workflow Stages', desc: 'Production lifecycle steps', icon: 'fa-project-diagram' },
    workflow_statuses: { title: 'Workflow Statuses', desc: 'Global stage status definitions', icon: 'fa-stream' },
    task_statuses: { title: 'Task Statuses', desc: 'Individual task tracking states', icon: 'fa-tasks' },
    machinery: { title: 'Machinery', desc: 'Factory equipment registry', icon: 'fa-cog' },
    skills: { title: 'Skills', desc: 'Employee expertise tags', icon: 'fa-star' },
    units: { title: 'Units', desc: 'Measurement units for inventory', icon: 'fa-ruler-combined' },
    companies: { title: 'Companies', desc: 'Corporate entities and settings', icon: 'fa-building' }
};

function showLoader() { document.getElementById('table-loader').style.display = 'flex'; }
function hideLoader() { document.getElementById('table-loader').style.display = 'none'; }

async function loadTable(tableName, page = 1) {
    currentTable = tableName;
    currentPage = page;
    const meta = tableMetadata[tableName] || { title: tableName, desc: '', icon: 'fa-table' };
    document.getElementById('current-table-title').innerText = meta.title;
    document.getElementById('current-table-desc').innerText = meta.desc;
    document.getElementById('table-icon-header').innerHTML = `<i class="fas ${meta.icon}"></i>`;
    
    showLoader();
    try {
        const basePath = window.APP_CONFIG ? window.APP_CONFIG.BASE_PATH : '/';
        const response = await fetch(`${basePath}api/superadmin.php?action=list&table=${tableName}&page=${page}&limit=10`);
        const result = await response.json();
        if (result.success) {
            tableData = result.data;
            totalPages = result.pagination.pages;
            renderTable();
            renderPagination(result.pagination);
        } else {
            notify(result.message || 'Failed to load data', 'error');
        }
    } catch (e) {
        console.error(e);
        notify('Failed to load data', 'error');
    } finally {
        hideLoader();
    }
}

function renderPagination(pag) {
    document.getElementById('pag-total').innerText = pag.total;
    const start = pag.total === 0 ? 0 : (pag.page - 1) * pag.limit + 1;
    const end = Math.min(pag.page * pag.limit, pag.total);
    document.getElementById('pag-start').innerText = start;
    document.getElementById('pag-end').innerText = end;

    const prevBtn = document.getElementById('btn-prev');
    const nextBtn = document.getElementById('btn-next');
    
    prevBtn.disabled = pag.page <= 1;
    nextBtn.disabled = pag.page >= pag.pages;
    
    prevBtn.style.opacity = prevBtn.disabled ? '0.5' : '1';
    nextBtn.style.opacity = nextBtn.disabled ? '0.5' : '1';

    let html = '';
    // Show max 5 page buttons
    let startPage = Math.max(1, pag.page - 2);
    let endPage = Math.min(pag.pages, startPage + 4);
    if (endPage - startPage < 4) startPage = Math.max(1, endPage - 4);

    for (let i = startPage; i <= endPage; i++) {
        html += `
            <button class="btn btn-sm" onclick="loadTable('${currentTable}', ${i})" 
                style="min-width: 36px; height: 36px; padding: 0; background: ${i === pag.page ? 'var(--primary)' : 'var(--bg-card)'}; 
                color: ${i === pag.page ? 'white' : 'var(--text-main)'}; border: 1px solid ${i === pag.page ? 'var(--primary)' : 'var(--border)'};">
                ${i}
            </button>
        `;
    }
    document.getElementById('page-numbers').innerHTML = html;
}

function changePage(delta) {
    const nextPage = currentPage + delta;
    if (nextPage > 0 && nextPage <= totalPages) {
        loadTable(currentTable, nextPage);
    }
}

function renderTable() {
    const head = document.getElementById('table-head');
    const body = document.getElementById('table-body');
    
    if (!tableData || !tableData.length) {
        head.innerHTML = '';
        body.innerHTML = '<tr><td colspan="100" style="text-align: center; padding: 4rem; color: var(--text-muted);">No records found in this table.</td></tr>';
        return;
    }

    const columns = Object.keys(tableData[0]).filter(c => !['id', 'created_at', 'updated_at'].includes(c));
    let headHtml = `<tr><th style="width: 50px;">ID</th>`;
    columns.forEach(col => { headHtml += `<th>${col.replace(/_/g, ' ')}</th>`; });
    headHtml += `<th style="text-align: right; width: 120px;">Actions</th></tr>`;
    head.innerHTML = headHtml;

    let bodyHtml = tableData.map(row => {
        let cells = `<td style="font-weight: 800; color: var(--primary);">#${row.id}</td>`;
        columns.forEach(col => {
            let val = row[col];
            if (col.includes('color_code') && val) {
                cells += `<td><div style="display: flex; align-items: center; gap: 0.5rem;"><div style="width: 14px; height: 14px; background: ${val}; border-radius: 3px; border: 1px solid rgba(0,0,0,0.1);"></div> ${val}</div></td>`;
            } else if (col === 'is_active') {
                cells += `<td><span class="status-badge" style="background: ${val == 1 ? 'rgba(34, 197, 94, 0.1)' : 'rgba(239, 68, 68, 0.1)'}; color: ${val == 1 ? 'var(--success)' : 'var(--danger)'};">${val == 1 ? 'Active' : 'Inactive'}</span></td>`;
            } else {
                cells += `<td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${val === null ? '-' : val}</td>`;
            }
        });
        cells += `
            <td style="text-align: right;">
                <div style="display: flex; justify-content: flex-end; gap: 0.5rem;">
                    <button class="btn-icon btn-sm" onclick='editRecord(${JSON.stringify(row).replace(/'/g, "&apos;")})' style="background: var(--bg-dark); color: var(--primary);"><i class="fas fa-edit"></i></button>
                    <button class="btn-icon btn-sm" onclick="deleteRecord(${row.id})" style="background: rgba(239, 68, 68, 0.1); color: var(--danger);"><i class="fas fa-trash"></i></button>
                </div>
            </td>
        `;
        return `<tr>${cells}</tr>`;
    }).join('');
    body.innerHTML = bodyHtml;
}

function openRecordModal() {
    document.getElementById('modal-title').innerText = `Add New ${tableMetadata[currentTable].title.replace(/s$/, '')}`;
    document.getElementById('recordForm').reset();
    document.getElementById('field-id').value = '';
    generateFields();
    openModal('recordModal');
}

function editRecord(row) {
    document.getElementById('modal-title').innerText = `Edit ${tableMetadata[currentTable].title.replace(/s$/, '')}`;
    generateFields();
    document.getElementById('field-id').value = row.id;
    const form = document.getElementById('recordForm');
    Object.keys(row).forEach(key => {
        const field = form.querySelector(`[name="${key}"]`);
        if (field) {
            if (field.type === 'checkbox') field.checked = row[key] == 1;
            else field.value = row[key] === null ? '' : row[key];
        }
    });
    openModal('recordModal');
}

function generateFields() {
    let columns = tableData.length ? Object.keys(tableData[0]) : [];
    // If table is empty, we need to fetch schema or hardcode? 
    // For now, let's assume we have at least one record or use a fallback.
    if (!columns.length) {
        // Fallback for empty tables - we could use DESCRIBE in API to get this
        columns = ['name']; // Minimum fallback
    }
    columns = columns.filter(c => !['id', 'created_at', 'updated_at', 'email_verified_at', 'remember_token'].includes(c));
    
    let html = '';
    columns.forEach(col => {
        let label = col.replace(/_/g, ' ').toUpperCase();
        let type = 'text';
        if (col.includes('password')) type = 'password';
        else if (col.includes('email')) type = 'email';
        else if (col.includes('is_active')) type = 'checkbox';
        else if (col.includes('id') && col !== 'id') type = 'number';
        
        if (type === 'checkbox') {
            html += `<div class="form-group" style="grid-column: span 2; display: flex; align-items: center; gap: 0.75rem;"><input type="checkbox" name="${col}" id="field-${col}" style="width: 18px; height: 18px; cursor: pointer;"><label class="form-label" for="field-${col}" style="margin: 0; cursor: pointer;">${label}</label></div>`;
        } else {
            html += `<div class="form-group"><label class="form-label">${label}</label><input type="${type}" name="${col}" class="form-control" placeholder="Enter ${label.toLowerCase()}..."></div>`;
        }
    });
    document.getElementById('modal-fields').innerHTML = html;
}

async function saveRecord(e) {
    e.preventDefault();
    const data = {};
    
    // Use elements to iterate so we catch unchecked checkboxes
    Array.from(e.target.elements).forEach(el => {
        if (!el.name || el.disabled) return;
        
        if (el.type === 'checkbox') {
            data[el.name] = el.checked ? 1 : 0;
        } else if (el.tagName !== 'BUTTON' && el.name !== 'id') {
            data[el.name] = el.value;
        }
    });

    const id = document.getElementById('field-id').value;
    if (id) data.id = id;

    const btn = e.target.querySelector('button[type="submit"]');
    btn.classList.add('btn-loading');
    try {
        const basePath = window.APP_CONFIG ? window.APP_CONFIG.BASE_PATH : '/';
        const response = await fetch(`${basePath}api/superadmin.php`, { 
            method: 'POST', 
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ action: 'save', table: currentTable, data: data }) 
        });
        const result = await response.json();
        if (result.success) { notify(result.message, 'success'); closeModal('recordModal'); loadTable(currentTable); }
        else { notify(result.message || 'Save failed', 'error'); }
    } catch (e) { notify('Save failed', 'error'); }
    finally { btn.classList.remove('btn-loading'); }
}

async function deleteRecord(id) {
    const confirmed = await confirmAction({
        title: `Delete ${tableMetadata[currentTable].title.replace(/s$/, '')}`,
        message: 'Are you sure you want to delete this record? This action is irreversible and may affect related data across the system.',
        confirmText: 'Yes, Delete',
        confirmClass: 'var(--danger)'
    });

    if (!confirmed) return;
    
    try {
        const basePath = window.APP_CONFIG ? window.APP_CONFIG.BASE_PATH : '/';
        const response = await fetch(`${basePath}api/superadmin.php`, { 
            method: 'POST', 
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ action: 'delete', table: currentTable, id: id }) 
        });
        const result = await response.json();
        if (result.success) { notify(result.message, 'success'); loadTable(currentTable); }
        else { notify(result.message || 'Delete failed', 'error'); }
    } catch (e) { notify('Delete failed', 'error'); }
}

document.addEventListener('DOMContentLoaded', () => loadTable(currentTable));

document.getElementById('adminSearch').oninput = function(e) {
    const term = e.target.value.toLowerCase();
    const filtered = tableData.filter(row => Object.values(row).some(val => String(val).toLowerCase().includes(term)));
    const originalData = tableData;
    tableData = filtered;
    renderTable();
    tableData = originalData;
};
</script>
