<?= $this->extend('layouts/admin') ?>

<?= $this->section('content') ?>
<?php 
    $settingsModel = new \App\Models\SettingsModel();
    $siteLogo = $settingsModel->getSetting('site_logo');
    $grouped_sheets = [];
    foreach ($all_sheets as $s) {
        $folder = (isset($s['folder_name']) && trim($s['folder_name']) !== '') ? $s['folder_name'] : 'Main';
        $grouped_sheets[$folder][] = $s;
    }
?>
<style>
    .table-container {
        background: #fff;
        border-radius: 12px;
        border: 1px solid var(--border);
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }
    .table-header-top {
        padding: 15px 25px;
        border-bottom: 1px solid var(--border);
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: #fff;
    }
    .table-title {
        display: flex;
        align-items: center;
        gap: 10px;
        font-weight: 600;
        color: var(--text-admin-main);
    }
    .table-actions {
        display: flex;
        align-items: center;
        gap: 15px;
    }
    .search-input-group {
        position: relative;
        width: 250px;
    }
    .search-input-group input {
        width: 100%;
        padding: 8px 15px 8px 35px;
        border-radius: 8px;
        border: 1px solid var(--border);
        background: #f8fafc;
        font-size: 0.85rem;
    }
    .search-input-group i {
        position: absolute;
        left: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: var(--text-admin-muted);
    }
    .admin-table thead th {
        background: #fff !important;
        border-bottom: 1px solid var(--border) !important;
        padding: 12px 20px !important;
        text-transform: none !important;
        letter-spacing: normal !important;
        font-size: 0.9rem !important;
        color: var(--text-admin-main) !important;
    }
    .col-header-content {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .col-icon {
        color: var(--text-admin-muted);
        font-size: 0.9rem;
    }
    .empty-state {
        padding: 100px 0;
        text-align: center;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    .empty-icon {
        font-size: 4rem;
        color: var(--text-admin-main);
        margin-bottom: 20px;
        opacity: 0.8;
    }
    .empty-title {
        font-size: 1.5rem;
        font-weight: 700;
        margin-bottom: 8px;
    }
    .empty-subtitle {
        color: var(--text-admin-muted);
        margin-bottom: 30px;
    }

    /* Custom Scrollbar for Spreadsheet */
    .spreadsheet-container::-webkit-scrollbar {
        height: 10px;
        background-color: #f1f5f9;
    }
    .spreadsheet-container::-webkit-scrollbar-thumb {
        background-color: #cbd5e1;
        border-radius: 20px;
        border: 2px solid #f1f5f9;
    }
    .spreadsheet-container::-webkit-scrollbar-thumb:hover {
        background-color: #94a3b8;
    }
    .spreadsheet-container {
        scrollbar-width: thin;
        scrollbar-color: #cbd5e1 #f1f5f9;
        overflow-x: auto;
        position: relative;
    }

    /* Sticky Columns Logic */
    .admin-table {
        border-collapse: separate !important;
        border-spacing: 0;
    }
    .admin-table th:first-child, 
    .admin-table td:first-child {
        position: sticky;
        left: 0;
        z-index: 20;
        background: #fff;
        border-right: 2px solid #e2e8f0 !important;
        box-shadow: 2px 0 5px rgba(0,0,0,0.02);
    }
    .admin-table th:last-child, 
    .admin-table td:last-child {
        position: sticky;
        right: 0;
        z-index: 20;
        background: #fff;
        border-left: 2px solid #e2e8f0 !important;
        box-shadow: -2px 0 5px rgba(0,0,0,0.02);
    }
    /* Headers must be above the sticky cells */
    .admin-table thead th {
        position: sticky;
        top: 0;
        z-index: 30;
        background: #fff !important;
    }
    /* Corners must be highest priority */
    .admin-table thead th:first-child { z-index: 40; }
    .admin-table thead th:last-child { z-index: 40; }

    /* Maintain row background on sticky cells */
    .admin-table tr:hover td:first-child,
    .admin-table tr:hover td:last-child {
        background: #f8fafc;
    }
    
    .file-cell-ui {
        display: flex;
        align-items: center;
        gap: 10px;
        cursor: pointer;
        background: #f1f5f9;
        padding: 4px;
        border-radius: 8px;
        border: 1px dashed #cbd5e1;
        transition: all 0.2s;
        min-width: 40px;
        width: fit-content;
    }
    .file-cell-ui:hover {
        background: #e2e8f0;
        border-color: #94a3b8;
    }
    .file-indicator {
        width: 32px;
        height: 32px;
        background: #fff;
        border: 1px solid #e2e8f0;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #4285f4;
        font-size: 1.2rem;
    }
    .file-cell-ui.has-file {
        background: rgba(66, 133, 244, 0.05);
        border: 1px solid #4285f4;
        border-style: solid;
        padding-right: 12px;
    }
    .file-cell-ui.has-file .file-indicator {
        background: #4285f4;
        color: #fff;
    }
    .file-name-label {
        font-size: 0.8rem;
        color: #64748b;
        max-width: 120px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    /* Media Upload Modal */
    .media-modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 10000;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s;
    }
    .media-modal.active {
        opacity: 1;
        visibility: visible;
    }
    .media-modal-content {
        background: #fff;
        width: 90%;
        max-width: 500px;
        border-radius: 16px;
        padding: 40px;
        text-align: center;
        transform: translateY(20px);
        transition: all 0.3s;
    }
    .media-modal.active .media-modal-content {
        transform: translateY(0);
    }
    .upload-cloud-icon {
        font-size: 3.5rem;
        color: #4285f4;
        margin-bottom: 20px;
        display: inline-block;
    }
    .upload-title {
        font-size: 1.1rem;
        color: var(--text-admin-main);
        margin-bottom: 25px;
    }
    .upload-title span {
        color: #4285f4;
        cursor: pointer;
        font-weight: 600;
        text-decoration: underline;
    }
    .media-actions {
        display: flex;
        justify-content: center;
        gap: 15px;
        margin-top: 20px;
    }
    .media-action-btn {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 10px;
        border: 1px solid #4285f4;
        border-radius: 8px;
        background: #fff;
        color: #4285f4;
        font-size: 0.85rem;
        cursor: pointer;
        transition: all 0.2s;
    }
    .media-action-btn:hover {
        background: rgba(66, 133, 244, 0.05);
    }
    .media-action-btn i {
        font-size: 1.1rem;
    }

    /* Live Camera Preview */
    #camera-preview-container {
        width: 100%;
        max-width: 400px;
        aspect-ratio: 4/3;
        background: #000;
        border-radius: 12px;
        margin: 20px auto;
        overflow: hidden;
        display: none;
        position: relative;
    }
    #camera-video {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    /* Signature Pad Styles */
    .signature-modal {
        position: fixed;
        top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(15, 23, 42, 0.6);
        backdrop-filter: blur(8px);
        display: none;
        align-items: center;
        justify-content: center;
        z-index: 11000;
        opacity: 0;
        transition: all 0.3s;
    }
    .signature-modal.active {
        display: flex;
        opacity: 1;
    }
    .signature-pad-container {
        background: #fff;
        width: 95%;
        max-width: 600px;
        border-radius: 20px;
        overflow: hidden;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
    }
    .signature-header {
        padding: 20px 25px;
        border-bottom: 1px solid #f1f5f9;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: #f8fafc;
    }
    .signature-body {
        padding: 25px;
        text-align: center;
    }
    .signature-canvas-wrapper {
        border: 2px solid #e2e8f0;
        border-radius: 12px;
        background: #fff;
        position: relative;
        overflow: hidden;
        margin-bottom: 20px;
        touch-action: none;
    }
    #signature-canvas {
        width: 100%;
        height: 300px;
        cursor: crosshair;
        display: block;
    }
    .signature-footer {
        padding: 20px 25px;
        border-top: 1px solid #f1f5f9;
        display: flex;
        gap: 15px;
        background: #f8fafc;
    }
    .signature-btn {
        flex: 1;
        padding: 12px;
        border-radius: 10px;
        font-weight: 700;
        font-size: 0.9rem;
        cursor: pointer;
        transition: all 0.2s;
        border: none;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
    }
    .signature-btn-clear {
        background: #f1f5f9;
        color: #64748b;
    }
    .signature-btn-save {
        background: #10b981;
        color: #fff;
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);
    }
    .signature-btn-save:hover {
        background: #059669;
        transform: translateY(-1px);
    }

    .table-footer {
        padding: 10px 25px;
        background: #f8fafc;
        border-top: 1px solid var(--border);
        font-size: 0.85rem;
        color: var(--text-admin-muted);
        display: flex;
        align-items: center;
    }
    .record-sidebar {
        position: fixed;
        top: 0;
        right: -450px;
        width: 450px;
        height: 100vh;
        background: #fff;
        z-index: 2000;
        box-shadow: -10px 0 30px rgba(0,0,0,0.1);
        transition: all 0.4s cubic-bezier(0.23, 1, 0.32, 1);
        display: flex;
        flex-direction: column;
    }
    .record-sidebar.active {
        right: 0;
    }
    .sidebar-overlay {
        position: fixed;
        inset: 0;
        background: rgba(15, 23, 42, 0.4);
        backdrop-filter: blur(4px);
        z-index: 1999;
        display: none;
        opacity: 0;
        transition: opacity 0.3s ease;
    }
    .sidebar-overlay.active {
        display: block;
        opacity: 1;
    }
    .sidebar-header {
        padding: 25px 30px;
        border-bottom: 1px solid rgba(0,0,0,0.05);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .sidebar-header h3 {
        font-size: 1.5rem;
        margin: 0;
        font-weight: 700;
    }
    .sidebar-body {
        padding: 30px;
        overflow-y: auto;
        flex-grow: 1;
    }
    .sidebar-footer {
        padding: 25px 30px;
        border-top: 1px solid rgba(0,0,0,0.05);
    }
    .sidebar-field {
        margin-bottom: 25px;
    }
    .sidebar-field label {
        display: flex;
        align-items: center;
        gap: 10px;
        font-weight: 700;
        font-size: 0.9rem;
        color: var(--text-admin-main);
        margin-bottom: 12px;
    }
    .sidebar-field label i {
        font-size: 1.1rem;
        color: var(--text-admin-muted);
    }
    .close-btn {
        background: none;
        border: none;
        font-size: 1.2rem;
        color: var(--text-admin-muted);
        cursor: pointer;
        transition: color 0.2s;
    }
    .close-btn:hover {
        color: var(--primary);
    }
    .col-modal {
        position: fixed;
        inset: 0;
        background: rgba(15, 23, 42, 0.4);
        backdrop-filter: blur(4px);
        z-index: 3000;
        display: none;
        align-items: center;
        justify-content: center;
    }
    .col-modal.active {
        display: flex;
    }
    .col-modal-content {
        background: #fff;
        width: 100%;
        max-width: 480px;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.15);
        animation: modalFadeIn 0.3s cubic-bezier(0.16, 1, 0.3, 1);
    }
    @keyframes modalFadeIn {
        from { opacity: 0; transform: scale(0.95) translateY(10px); }
        to { opacity: 1; transform: scale(1) translateY(0); }
    }
    .col-modal-header {
        padding: 20px 24px;
        border-bottom: 1px solid #f1f5f9;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .col-modal-body {
        padding: 24px;
    }
    .modal-field {
        margin-bottom: 24px;
    }
    .modal-field label {
        display: block;
        font-weight: 500;
        font-size: 0.85rem;
        color: #64748b;
        margin-bottom: 10px;
    }
    .modal-field select, .modal-field input {
        width: 100%;
        padding: 14px 16px;
        border-radius: 12px;
        border: 1px solid #e2e8f0;
        font-size: 0.95rem;
        color: #1e293b;
        outline: none;
        transition: all 0.2s;
        background: #fff;
    }
    .modal-field select:focus, .modal-field input:focus {
        border-color: #3b82f6;
        box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
    }
    .custom-select-wrapper {
        position: relative;
    }
    .select-icon {
        position: absolute;
        left: 16px;
        top: 50%;
        transform: translateY(-50%);
        color: #1e293b;
        font-size: 1.1rem;
        pointer-events: none;
    }
    .custom-select-wrapper select {
        padding-left: 48px !important;
        cursor: pointer;
    }
    .dropdown-option-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 8px;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        margin-bottom: 10px;
        background: #fff;
    }
    .option-color-box {
        width: 32px;
        height: 32px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 0.9rem;
        flex-shrink: 0;
    }
    .option-input-wrapper {
        flex-grow: 1;
        position: relative;
    }
    .option-input-wrapper input {
        padding: 8px 35px 8px 12px !important;
        font-weight: 500;
        border: 1px solid transparent !important;
        background: #f8fafc !important;
    }
    .option-input-wrapper input:focus {
        background: #fff !important;
        border-color: #3b82f6 !important;
    }
    .option-check {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: #64748b;
    }
    .remove-option-btn {
        color: #94a3b8;
        cursor: pointer;
        padding: 4px;
        transition: color 0.2s;
    }
    .remove-option-btn:hover {
        color: #ef4444;
    }
    .advanced-settings-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        cursor: pointer;
        padding: 16px 0;
        color: #1e293b;
        font-weight: 600;
        font-size: 0.9rem;
        border-top: 1px solid #f1f5f9;
        margin-top: 8px;
    }
    .advanced-settings-header i:first-child {
        font-size: 1.1rem;
        color: #64748b;
    }
    .col-options-menu {
        position: fixed;
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.15);
        border: 1px solid #f1f5f9;
        min-width: 200px;
        z-index: 9999;
        display: none;
        padding: 8px 0;
        animation: menuFadeIn 0.2s cubic-bezier(0.16, 1, 0.3, 1);
    }
    @keyframes menuFadeIn {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .col-options-menu.active {
        display: block;
    }
    .col-option-item {
        padding: 10px 15px;
        display: flex;
        align-items: center;
        gap: 12px;
        color: var(--text-admin-main);
        font-size: 0.85rem;
        cursor: pointer;
        transition: background 0.2s;
    }
    .col-option-item:hover {
        background: #f8fafc;
    }
    .col-option-item.delete {
        color: #ff4757;
        border-top: 1px solid var(--border);
        margin-top: 5px;
    }
    .col-option-item i {
        font-size: 1rem;
        color: var(--text-admin-muted);
    }
    .col-option-item.delete i {
        color: #ff4757;
    }
    .row-options-menu {
        position: fixed;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        border: 1px solid var(--border);
        min-width: 220px;
        z-index: 10000;
        display: none;
        padding: 8px 0;
        text-align: left;
    }
    .row-options-menu.active {
        display: block;
    }
    .row-option-item {
        padding: 10px 15px;
        display: flex;
        align-items: center;
        gap: 12px;
        color: var(--text-admin-main);
        font-size: 0.85rem;
        cursor: pointer;
        transition: background 0.2s;
    }
    .row-option-item:hover {
        background: #f8fafc;
    }
    .row-option-item.delete {
        color: #ff4757;
        border-top: 1px solid var(--border);
        margin-top: 5px;
    }
    .row-option-item i {
        font-size: 1rem;
        color: var(--text-admin-muted);
    }
    .row-option-item.delete i {
        color: #ff4757;
    }
    .row-option-subtext {
        display: block;
        font-size: 0.7rem;
        color: var(--text-admin-muted);
        margin-top: 2px;
    }
    .folder-dropdown {
        position: relative;
        display: inline-block;
    }
    .folder-dropdown-menu {
        position: absolute;
        top: 100%;
        left: 0;
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 15px 35px rgba(0,0,0,0.15);
        border: 1px solid var(--border);
        min-width: 200px;
        z-index: 2000;
        display: none;
        padding: 8px;
        margin-top: 5px;
        animation: dropdownSlide 0.2s ease;
    }
    @keyframes dropdownSlide {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .folder-dropdown-menu.active {
        display: block;
    }
    .folder-dropdown-item {
        padding: 10px 15px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: var(--text-admin-main);
        text-decoration: none;
        font-weight: 500;
        font-size: 0.9rem;
        transition: background 0.2s;
    }
    .folder-dropdown-item:hover {
        background: #f1f5f9;
    }
    .folder-dropdown-item.active {
        background: rgba(var(--primary-rgb), 0.1);
        color: var(--primary);
    }
    .modal-overlay {
        position: fixed;
        top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0,0,0,0.5);
        backdrop-filter: blur(4px);
        display: none;
        align-items: center;
        justify-content: center;
        z-index: 3000;
        padding: 20px;
    }
    .modal-overlay.active {
        display: flex;
    }
    .modal-content {
        background: #fff;
        border-radius: 16px;
        width: 100%;
        box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
    }
    .modal-header {
        padding: 20px;
        border-bottom: 1px solid var(--border);
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .folder-tab-hover:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    .folder-dropdown-menu {
        position: absolute;
        top: 110%;
        left: 0;
        background: #ffffff;
        border-radius: 12px;
        box-shadow: 0 10px 25px rgba(0,0,0,0.2), 0 0 1px rgba(0,0,0,0.1);
        border: 1px solid var(--border);
        min-width: 200px;
        z-index: 9999 !important;
        display: none;
        padding: 8px;
        margin-top: 5px;
        animation: dropdownSlide 0.2s ease;
    }
    .folder-dropdown-menu.active {
        display: block !important;
    }
    .table-options-menu {
        position: absolute;
        top: 100%;
        left: 0;
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 15px 35px rgba(0,0,0,0.2);
        border: 1px solid var(--border);
        min-width: 220px;
        z-index: 10000;
        display: none;
        padding: 8px;
        margin-top: 5px;
    }
    .table-options-menu.active {
        display: block;
    }
    .table-option-item {
        padding: 10px 15px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        gap: 12px;
        color: var(--text-admin-main);
        text-decoration: none;
        font-weight: 500;
        font-size: 0.9rem;
        cursor: pointer;
        transition: background 0.2s;
        white-space: nowrap;
    }
    .table-option-item:hover {
        background: #f1f5f9;
    }
    .table-option-item i {
        font-size: 1.1rem;
        color: #64748b;
    }
    .table-option-item.delete {
        color: #ff4757;
    }
    .table-option-item.delete i {
        color: #ff4757;
    }
    .permission-card {
        flex: 1;
        padding: 15px;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        cursor: pointer;
        transition: all 0.2s;
    }
    .permission-card:hover {
        border-color: #4285f4;
        background: #f8fbff;
    }
    .permission-card.active {
        border-color: #4285f4;
        background: #f0f7ff;
        box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.1);
    }
    .action-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 15px;
        background: #f8fafc;
        padding: 20px;
        border-radius: 12px;
    }
    .action-item {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 0.85rem;
        font-weight: 500;
        color: #475569;
    }
</style>

<div class="animate-up">
    <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 30px;">
        <div>
            <a href="<?= base_url('admin/projects') ?>" style="color: var(--primary); text-decoration: none; display: flex; align-items: center; gap: 5px; margin-bottom: 10px;">
                <i class="bi bi-arrow-left"></i> Back to Projects
            </a>
            <h1>Dynamic Project Sheet: <span style="color: var(--primary);"><?= $project['title'] ?></span></h1>
            <p style="color: var(--text-muted);">Build custom data tables with dynamic columns, types, and automated row management.</p>
        </div>
        <button type="button" class="btn btn-primary" onclick="toggleSidebar(true)" style="padding: 12px 25px; border-radius: 12px; box-shadow: 0 10px 20px rgba(229, 45, 39, 0.2);">
            <i class="bi bi-plus-lg"></i> Add Record
        </button>
    </div>

    <div id="sidebar-overlay" class="sidebar-overlay" onclick="toggleSidebar(false)"></div>

    <!-- Add Table Modal -->
    <div id="table-modal" class="modal-overlay">
        <div class="modal-content animate-up" style="max-width: 450px;">
            <div class="modal-header">
                <h3 style="margin: 0; display: flex; align-items: center; gap: 10px; font-size: 1.2rem; font-weight: 700;">
                    <i class="bi bi-plus-square-fill" style="color: var(--primary);"></i> 
                    Create New Table
                </h3>
                <button type="button" onclick="toggleModal('table-modal', false)" style="background: none; border: none; font-size: 1.5rem; cursor: pointer;">&times;</button>
            </div>
            <div class="modal-body" style="padding: 20px;">
                <form id="new-table-form" action="<?= base_url('admin/create_table/' . $project['id']) ?>" method="POST">
                    <input type="hidden" name="folder_name" id="modal-table-folder">
                    <div style="margin-bottom: 20px;">
                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-admin-main);">Table Name</label>
                        <input type="text" name="table_name" placeholder="e.g. June Expenses" required
                               style="width: 100%; padding: 12px; border-radius: 8px; border: 1px solid var(--border); outline: none; transition: border-color 0.3s;">
                        <span id="target-folder-label" style="display: block; font-size: 0.75rem; color: var(--text-admin-muted); margin-top: 5px;"></span>
                    </div>
                    <div style="display: flex; gap: 10px;">
                        <button type="submit" class="btn btn-primary" style="flex: 1; padding: 12px; border-radius: 8px;">Create Table</button>
                        <button type="button" onclick="toggleModal('table-modal', false)" style="flex: 1; background: #f1f5f9; border: none; padding: 12px; border-radius: 8px; color: #64748b; font-weight: 600;">Cancel</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Folder Modal -->
    <div id="folder-modal" class="modal-overlay">
        <div class="modal-content animate-up" style="max-width: 450px;">
            <div class="modal-header">
                <h3 style="margin: 0; display: flex; align-items: center; gap: 10px; font-size: 1.2rem; font-weight: 700;">
                    <i class="bi bi-folder-plus" style="color: var(--primary);"></i> 
                    Create New Folder
                </h3>
                <button type="button" onclick="toggleModal('folder-modal', false)" style="background: none; border: none; font-size: 1.5rem; cursor: pointer;">&times;</button>
            </div>
            <div class="modal-body" style="padding: 20px;">
                <form id="new-folder-form" action="<?= base_url('admin/create_table/' . $project['id']) ?>" method="POST">
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-admin-main);">Folder Name</label>
                        <input type="text" name="folder_name" placeholder="e.g. 2026 Registers" required
                               style="width: 100%; padding: 12px; border-radius: 8px; border: 1px solid var(--border); outline: none;">
                    </div>
                    <div style="margin-bottom: 20px;">
                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-admin-main);">Initial Table Name</label>
                        <input type="text" name="table_name" placeholder="e.g. Overview" value="Overview" required
                               style="width: 100%; padding: 12px; border-radius: 8px; border: 1px solid var(--border); outline: none;">
                    </div>
                    <div style="display: flex; gap: 10px;">
                        <button type="submit" class="btn btn-primary" style="flex: 1; padding: 12px; border-radius: 8px;">Create Folder</button>
                        <button type="button" onclick="toggleModal('folder-modal', false)" style="flex: 1; background: #f1f5f9; border: none; padding: 12px; border-radius: 8px; color: #64748b; font-weight: 600;">Cancel</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Rename Table Modal -->
    <div id="rename-modal" class="modal-overlay">
        <div class="modal-content animate-up" style="max-width: 400px;">
            <div class="modal-header">
                <h3 style="margin: 0; font-size: 1.1rem; font-weight: 700;"><i class="bi bi-pencil" style="color: var(--primary);"></i> Rename Table</h3>
                <button type="button" onclick="toggleModal('rename-modal', false)" style="background: none; border: none; font-size: 1.5rem; cursor: pointer;">&times;</button>
            </div>
            <div class="modal-body" style="padding: 20px;">
                <form id="rename-table-form" action="<?= base_url('admin/rename_table/' . $project['id']) ?>" method="POST">
                    <input type="hidden" name="table_id" id="rename-table-id">
                    <div style="margin-bottom: 20px;">
                        <label style="display: block; font-weight: 600; margin-bottom: 8px;">New Table Name</label>
                        <input type="text" name="table_name" id="rename-table-name" required
                               style="width: 100%; padding: 12px; border-radius: 8px; border: 1px solid var(--border); outline: none;">
                    </div>
                    <button type="submit" class="btn btn-primary" style="width: 100%; padding: 12px; border-radius: 8px;">Update Name</button>
                </form>
            </div>
        </div>
    </div>

    <!-- Move to Folder Modal -->
    <div id="move-modal" class="modal-overlay">
        <div class="modal-content animate-up" style="max-width: 400px;">
            <div class="modal-header">
                <h3 style="margin: 0; font-size: 1.1rem; font-weight: 700;"><i class="bi bi-folder-symlink" style="color: var(--primary);"></i> Move to Folder</h3>
                <button type="button" onclick="toggleModal('move-modal', false)" style="background: none; border: none; font-size: 1.5rem; cursor: pointer;">&times;</button>
            </div>
            <div class="modal-body" style="padding: 20px;">
                <form id="move-table-form" action="<?= base_url('admin/move_table/' . $project['id']) ?>" method="POST">
                    <input type="hidden" name="table_id" id="move-table-id">
                    <div style="margin-bottom: 20px;">
                        <label style="display: block; font-weight: 600; margin-bottom: 8px;">Select Folder</label>
                        <select name="folder_name" style="width: 100%; padding: 12px; border-radius: 8px; border: 1px solid var(--border); outline: none;">
                            <option value="">Main (No Folder)</option>
                            <?php foreach (array_keys($grouped_sheets) as $folder_key): ?>
                                <?php if ($folder_key !== 'Main'): ?>
                                    <option value="<?= $folder_key ?>"><?= $folder_key ?></option>
                                <?php endif; ?>
                            <?php endforeach; ?>
                            <option value="__new__">+ Create New Folder...</option>
                        </select>
                    </div>
                    <div id="new-folder-input-div" style="margin-bottom: 20px; display: none;">
                        <label style="display: block; font-weight: 600; margin-bottom: 8px;">New Folder Name</label>
                        <input type="text" name="new_folder_name" placeholder="Enter folder name..."
                               style="width: 100%; padding: 12px; border-radius: 8px; border: 1px solid var(--border); outline: none;">
                    </div>
                    <button type="submit" class="btn btn-primary" style="width: 100%; padding: 12px; border-radius: 8px;">Move Table</button>
                </form>
            </div>
        </div>
    </div>

    <!-- Sharing Modal -->
    <div id="sharing-modal" class="modal-overlay">
        <div class="modal-content animate-up" style="max-width: 600px; height: 80vh; display: flex; flex-direction: column;">
            <div class="modal-header" style="border-bottom: 2px solid #f8fafc; padding: 15px 25px;">
                <h3 style="margin: 0; font-size: 1.1rem; font-weight: 700; display: flex; align-items: center; gap: 10px;">
                    <div style="width: 32px; height: 32px; background: #64748b; border-radius: 6px; display: flex; align-items: center; justify-content: center; color: #fff;">
                        <i class="bi bi-table" style="font-size: 1rem;"></i>
                    </div>
                    <span id="sharing-table-title">Table Name</span>
                </h3>
                <button type="button" onclick="toggleModal('sharing-modal', false)" style="background: none; border: none; font-size: 1.8rem; cursor: pointer; color: #64748b;">&times;</button>
            </div>
            
            <div class="modal-body" style="padding: 25px; flex: 1; overflow-y: auto;">
                <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 20px;">
                    <div style="width: 8px; height: 8px; background: #4285f4; border-radius: 50%;"></div>
                    <span style="font-size: 0.75rem; font-weight: 800; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.05em;">Add People</span>
                    <div style="flex: 1; height: 1px; background: #f1f5f9; margin-left: 10px;"></div>
                </div>

                <div style="display: flex; gap: 10px; margin-bottom: 40px;">
                    <div style="display: flex; border: 1px solid #e2e8f0; border-radius: 8px; flex: 1; overflow: hidden;">
                        <div style="padding: 0 15px; display: flex; align-items: center; border-right: 1px solid #e2e8f0; background: #f8fafc;">
                            <i class="bi bi-envelope" style="color: #4285f4;"></i>
                        </div>
                        <input type="text" placeholder="name@company.com" style="flex: 1; padding: 12px; border: none; outline: none; font-size: 0.9rem;">
                        <div style="display: flex; align-items: center; padding-right: 10px; background: #fff;">
                            <select onchange="if(this.value === 'custom') openCustomPermissions('New Member')" style="border: none; background: #f1f5f9; padding: 6px 12px; border-radius: 6px; font-size: 0.8rem; font-weight: 600; color: #64748b; outline: none; cursor: pointer;">
                                <option value="viewer">Viewer</option>
                                <option value="editor">Editor</option>
                                <option value="admin">Admin</option>
                                <option value="custom" style="font-weight: 700; color: #4285f4;">Custom...</option>
                            </select>
                        </div>
                    </div>
                    <button class="btn" style="background: #a5c6ff; color: #fff; border: none; padding: 0 25px; border-radius: 8px; font-weight: 700; display: flex; align-items: center; gap: 8px; cursor: not-allowed;">
                        <i class="bi bi-share-fill"></i> Share
                    </button>
                </div>

                <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 60px 0;">
                    <div style="width: 80px; height: 80px; background: #f8fafc; border-radius: 20px; display: flex; align-items: center; justify-content: center; margin-bottom: 20px;">
                        <i class="bi bi-people" style="font-size: 2.5rem; color: #cbd5e1;"></i>
                    </div>
                    <h4 style="margin: 0 0 10px 0; font-size: 1.1rem; font-weight: 700; color: #475569;">No one has access yet</h4>
                    <p style="margin: 0; font-size: 0.9rem; color: #94a3b8; text-align: center; max-width: 300px;">Invite members or guests to collaborate on this table</p>
                </div>

                <!-- Assigned Members List (Collapsible) -->
                <div style="margin-top: 20px;">
                    <div style="font-size: 0.75rem; font-weight: 800; color: #94a3b8; text-transform: uppercase; margin-bottom: 15px;">Project Members</div>
                    <?php foreach ($employees as $emp): ?>
                        <div style="display: flex; align-items: center; justify-content: space-between; padding: 10px 0; border-top: 1px solid #f8fafc;">
                            <div style="display: flex; align-items: center; gap: 12px;">
                                <div style="width: 36px; height: 36px; border-radius: 50%; background: #4285f4; color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 0.8rem;">
                                    <?= substr($emp['name'], 0, 1) ?>
                                </div>
                                <div>
                                    <div style="font-weight: 600; font-size: 0.9rem; color: #1e293b;"><?= $emp['name'] ?></div>
                                    <div style="font-size: 0.75rem; color: #64748b;"><?= $emp['role'] ?></div>
                                </div>
                            </div>
                            <div style="display: flex; align-items: center; gap: 15px;">
                                <button type="button" class="btn" style="padding: 4px 12px; font-size: 0.75rem; border: 1px solid #e2e8f0; color: #4285f4; font-weight: 600; border-radius: 6px;" onclick="openCustomPermissions('<?= addslashes($emp['name']) ?>')">Custom</button>
                                <div style="display: flex; gap: 10px;">
                                    <label style="display: flex; align-items: center; gap: 5px; font-size: 0.8rem; cursor: pointer; color: #64748b;">
                                        <input type="checkbox" checked> View
                                    </label>
                                    <label style="display: flex; align-items: center; gap: 5px; font-size: 0.8rem; cursor: pointer; color: #64748b;">
                                        <input type="checkbox"> Edit
                                    </label>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <div style="padding: 20px 25px; border-top: 1px solid #f1f5f9; display: flex; justify-content: flex-end; background: #f8fafc; border-bottom-left-radius: 16px; border-bottom-right-radius: 16px;">
                <button type="button" class="btn" style="background: #fff; border: 1px solid #e2e8f0; padding: 10px 25px; border-radius: 8px; color: #64748b; font-weight: 600;" onclick="toggleModal('sharing-modal', false)">Done</button>
            </div>
        </div>
    </div>

    <!-- Advanced Permissions Modal -->
    <div id="custom-perms-modal" class="modal-overlay">
        <div class="modal-content animate-up" style="max-width: 700px; height: 90vh; display: flex; flex-direction: column;">
            <div class="modal-header" style="border-bottom: 1px solid #f1f5f9; padding: 15px 25px;">
                <h3 style="margin: 0; font-size: 1.1rem; font-weight: 700; display: flex; align-items: center; gap: 10px;">
                    <div style="width: 32px; height: 32px; background: #e0f2fe; color: #0ea5e9; border-radius: 6px; display: flex; align-items: center; justify-content: center;">
                        <i class="bi bi-shield-lock" style="font-size: 1rem;"></i>
                    </div>
                    <span id="perm-user-title">User</span> &mdash; Permissions
                </h3>
                <button type="button" onclick="toggleModal('custom-perms-modal', false)" style="background: none; border: none; font-size: 1.8rem; cursor: pointer; color: #64748b;">&times;</button>
            </div>
            <div class="modal-body" style="padding: 25px; flex: 1; overflow-y: auto;">
                <p style="font-size: 0.9rem; color: #64748b; margin-bottom: 25px;">Control what this member can see and do in this table.</p>

                <div style="font-size: 0.7rem; font-weight: 800; color: #94a3b8; text-transform: uppercase; margin-bottom: 15px; letter-spacing: 0.05em;">Quick Roles</div>
                <div style="display: flex; gap: 15px; margin-bottom: 35px;">
                    <div class="permission-card active" onclick="selectQuickRole(this, 'editor')">
                        <div style="width: 32px; height: 32px; background: #eef2ff; color: #4285f4; border-radius: 8px; display: flex; align-items: center; justify-content: center; margin-bottom: 10px;">
                            <i class="bi bi-pencil-square"></i>
                        </div>
                        <div style="font-weight: 700; font-size: 0.9rem; color: #1e293b;">Editor</div>
                        <div style="font-size: 0.75rem; color: #94a3b8;">Full access, with messages</div>
                    </div>
                    <div class="permission-card" onclick="selectQuickRole(this, 'viewer')">
                        <div style="width: 32px; height: 32px; background: #f0fdf4; color: #16a34a; border-radius: 8px; display: flex; align-items: center; justify-content: center; margin-bottom: 10px;">
                            <i class="bi bi-eye"></i>
                        </div>
                        <div style="font-weight: 700; font-size: 0.9rem; color: #1e293b;">Viewer</div>
                        <div style="font-size: 0.75rem; color: #94a3b8;">Read-only access</div>
                    </div>
                    <div class="permission-card" onclick="selectQuickRole(this, 'add_only')">
                        <div style="width: 32px; height: 32px; background: #fff7ed; color: #ea580c; border-radius: 8px; display: flex; align-items: center; justify-content: center; margin-bottom: 10px;">
                            <i class="bi bi-plus-circle"></i>
                        </div>
                        <div style="font-weight: 700; font-size: 0.9rem; color: #1e293b;">Add Only</div>
                        <div style="font-size: 0.75rem; color: #94a3b8;">Only add new records</div>
                    </div>
                </div>

                <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 15px;">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <i class="bi bi-list-task" style="color: #64748b;"></i>
                        <span style="font-weight: 700; font-size: 0.9rem; color: #1e293b;">Table Actions</span>
                    </div>
                    <label style="display: flex; align-items: center; gap: 8px; font-size: 0.8rem; font-weight: 700; color: #4285f4; cursor: pointer;">
                        <input type="checkbox" checked id="toggle-all-actions" style="width: 16px; height: 16px;" onclick="toggleAllActions(this)"> ALL
                    </label>
                </div>
                <div class="action-grid" style="margin-bottom: 40px;">
                    <div class="action-item"><input type="checkbox" checked style="width: 16px; height: 16px;"> View Records</div>
                    <div class="action-item"><input type="checkbox" checked style="width: 16px; height: 16px;"> Create Record</div>
                    <div class="action-item"><input type="checkbox" checked style="width: 16px; height: 16px;"> Edit Record</div>
                    <div class="action-item"><input type="checkbox" checked style="width: 16px; height: 16px;"> Delete Record</div>
                    <div class="action-item"><input type="checkbox" checked style="width: 16px; height: 16px;"> Add Comment</div>
                    <div class="action-item"><input type="checkbox" checked style="width: 16px; height: 16px;"> Move Rows</div>
                </div>

                <div style="margin-top: 20px;">
                    <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px;">
                        <i class="bi bi-layout-three-columns" style="color: #64748b;"></i>
                        <span style="font-weight: 700; font-size: 0.9rem; color: #1e293b;">Columns</span>
                    </div>
                    <table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">
                        <thead>
                            <tr style="text-align: left; color: #94a3b8; border-bottom: 1px solid #f1f5f9; font-weight: 800;">
                                <th style="padding: 10px 0; font-size: 0.7rem; letter-spacing: 0.05em;">COLUMN NAME</th>
                                <th style="padding: 10px; text-align: center; font-size: 0.7rem; letter-spacing: 0.05em;">VIEW</th>
                                <th style="padding: 10px; text-align: center; font-size: 0.7rem; letter-spacing: 0.05em;">EDIT</th>
                                <th style="padding: 10px; text-align: center; font-size: 0.7rem; letter-spacing: 0.05em;">ADD</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($config as $col): ?>
                                <tr style="border-bottom: 1px solid #f8fafc;">
                                    <td style="padding: 12px 0; font-weight: 600; color: #475569; display: flex; align-items: center; gap: 8px;">
                                        <i class="bi bi-type" style="color: #cbd5e1;"></i>
                                        <?= $col['name'] ?>
                                    </td>
                                    <td style="padding: 10px; text-align: center;"><input type="checkbox" checked style="width: 16px; height: 16px;"></td>
                                    <td style="padding: 10px; text-align: center;"><input type="checkbox" checked style="width: 16px; height: 16px;"></td>
                                    <td style="padding: 10px; text-align: center;"><input type="checkbox" checked style="width: 16px; height: 16px;"></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div style="padding: 20px 25px; border-top: 1px solid #f1f5f9; display: flex; justify-content: flex-end; background: #f8fafc; border-bottom-left-radius: 16px; border-bottom-right-radius: 16px;">
                <button type="button" class="btn btn-primary" style="padding: 12px 35px; border-radius: 8px; font-weight: 700; background: #4285f4;" onclick="toggleModal('custom-perms-modal', false)">Apply Permissions</button>
            </div>
        </div>
    </div>

    <!-- Create Column Modal -->
    <div id="col-modal" class="col-modal">
        <div class="col-modal-content">
            <div class="col-modal-header">
                <h3 style="margin: 0; font-size: 1.1rem; font-weight: 700; color: #1e293b;">Create Column</h3>
                <button type="button" class="close-btn" onclick="toggleColModal(false)">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
            <div class="col-modal-body">
                <div class="modal-field">
                    <label>Type</label>
                    <div class="custom-select-wrapper">
                        <i class="bi bi-list-ul select-icon"></i>
                        <select id="modal-col-type" onchange="handleModalTypeChange()">
                            <option value="" disabled selected>Select Attribute Type</option>
                            <option value="text">Text</option>
                            <option value="number">Number</option>
                            <option value="percentage">Percentage</option>
                            <option value="amount">Amount</option>
                            <option value="unit">Unit</option>
                            <option value="phone">Phone Number</option>
                            <option value="email">Email</option>
                            <option value="location">Location</option>
                            <option value="date">Date</option>
                            <option value="time">Time</option>
                            <option value="dropdown">Dropdown</option>
                            <option value="yesno">Yes / No</option>
                            <option value="status">Status</option>
                            <option value="file">Photo & File</option>
                            <option value="label">Label</option>
                            <option value="signature">Signature</option>
                            <option value="formula">Formula</option>
                        </select>
                    </div>
                </div>
                <div class="modal-field">
                    <label>Name</label>
                    <input type="text" id="modal-col-name" placeholder="Enter attribute name">
                </div>
                <div class="modal-field">
                    <label>Description (Optional)</label>
                    <input type="text" id="modal-col-desc" placeholder="Enter attribute description">
                </div>

                <!-- Formula Section -->
                <div id="formula-section" style="display: none; margin-bottom: 24px;">
                    <label style="display: block; font-weight: 500; font-size: 0.85rem; color: #64748b; margin-bottom: 12px;">Formula Definition</label>
                    <div style="background: rgba(52, 152, 219, 0.05); border: 1px solid #3498db; border-radius: 12px; padding: 15px;">
                        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
                            <i class="bi bi-calculator" style="color: #3498db; font-size: 1.2rem;"></i>
                            <span style="font-size: 0.8rem; font-weight: 600; color: #3498db;">Column Calculation</span>
                        </div>
                        <input type="text" id="modal-col-formula" placeholder="e.g. = {Price} * {Quantity}" 
                               style="width: 100%; padding: 12px; border-radius: 8px; border: 1px solid #3498db; outline: none; background: #fff; font-family: monospace; font-weight: 600; color: #3498db;">
                        <p style="margin: 10px 0 0; font-size: 0.75rem; color: #64748b;">
                            Use <span style="background: #e2e8f0; padding: 2px 5px; border-radius: 4px; font-weight: 600;">{Column Name}</span> to reference other columns.
                        </p>
                    </div>
                </div>

                <!-- Dropdown Options Section -->
                <div id="dropdown-options-section" style="display: none; margin-bottom: 24px;">
                    <label style="display: block; font-weight: 500; font-size: 0.85rem; color: #64748b; margin-bottom: 12px;">Dropdown Options</label>
                    <div id="dropdown-options-list"></div>
                    <div style="border: 1px dashed #cbd5e1; border-radius: 12px; padding: 12px; text-align: center; color: #94a3b8; font-size: 0.85rem; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; transition: all 0.2s;" 
                         onmouseover="this.style.borderColor='#3b82f6'; this.style.color='#3b82f6'" 
                         onmouseout="this.style.borderColor='#cbd5e1'; this.style.color='#94a3b8'"
                         onclick="addNewOption()">
                        <i class="bi bi-plus"></i> Add New Option
                    </div>
                </div>

                <div class="advanced-settings-header" onclick="toggleAdvancedSettings()">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <i class="bi bi-sliders"></i> Advanced Settings
                    </div>
                    <i class="bi bi-chevron-down" id="adv-chevron"></i>
                </div>

                <div id="advanced-settings-body" style="display: none; padding-top: 15px;">
                    <div class="modal-field">
                        <label>Allow input on condition</label>
                        <div style="display: flex; align-items: center; justify-content: center; border: 1px solid #e2e8f0; padding: 12px; border-radius: 12px; color: #64748b; cursor: pointer; background: #f8fafc; font-size: 0.9rem; font-weight: 500;">
                            <i class="bi bi-filter-left" style="margin-right: 10px; font-size: 1.1rem;"></i> Filter
                        </div>
                    </div>
                    <div class="modal-field">
                        <label>Help Text</label>
                        <input type="text" id="modal-col-help" placeholder="Enter help text">
                    </div>
                </div>

                <div style="margin-top: 32px;">
                    <button type="button" class="btn btn-primary" style="width: 100%; padding: 14px; border-radius: 12px; font-weight: 700; font-size: 1rem; background: #ef4444; border: none; box-shadow: 0 4px 6px -1px rgba(239, 68, 68, 0.2);" onclick="confirmAddColumn()">
                        CREATE COLUMN
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div style="display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; align-items: center; position: relative; z-index: 2500;">
        <?php foreach ($grouped_sheets as $folder => $sheets): ?>
            <?php if ($folder !== 'Main'): ?>
                <?php 
                    $is_folder_active = false;
                    $active_table_name = '';
                    foreach ($sheets as $s) {
                        if ($current_sheet && $current_sheet['id'] == $s['id']) {
                            $is_folder_active = true;
                            $active_table_name = $s['table_name'];
                        }
                    }
                ?>
                <div class="folder-dropdown" onclick="toggleFolderDropdown(event, '<?= md5($folder) ?>')">
                    <div style="display: flex; align-items: center; background: <?= $is_folder_active ? 'var(--primary)' : '#f1f5f9' ?>; border-radius: 8px; padding: 2px; border: 1px solid <?= $is_folder_active ? 'var(--primary)' : 'var(--border)' ?>; cursor: pointer; transition: transform 0.2s, box-shadow 0.2s;" class="folder-tab-hover">
                        <div onclick="toggleFolderDropdown(event, '<?= md5($folder) ?>')" 
                                style="padding: 8px 15px; font-weight: 700; font-size: 0.9rem; color: <?= $is_folder_active ? '#fff' : 'var(--text-admin-main)' ?>; display: flex; align-items: center; gap: 8px;">
                            <i class="bi bi-folder2-open"></i> 
                            <?= $folder ?><?= ($is_folder_active && $active_table_name) ? ' / ' . $active_table_name : '' ?>
                            <i class="bi bi-chevron-down" style="font-size: 0.7rem;"></i>
                        </div>
                        <i class="bi bi-plus-circle-fill" style="cursor: pointer; color: <?= $is_folder_active ? '#fff' : 'var(--primary)' ?>; font-size: 1rem; margin-right: 5px;" onclick="event.stopPropagation(); createNewTable('<?= addslashes($folder) ?>')"></i>
                        <i class="bi bi-trash3" style="cursor: pointer; color: <?= $is_folder_active ? '#fff' : '#ff4757' ?>; font-size: 0.9rem; margin-right: 8px; opacity: 0.8;" onclick="event.stopPropagation(); deleteFolder('<?= addslashes($folder) ?>')"></i>
                    </div>
                    
                    <div class="folder-dropdown-menu" id="folder-menu-<?= md5($folder) ?>">
                        <?php foreach ($sheets as $s): ?>
                            <div style="position: relative; display: flex; align-items: center; justify-content: space-between;" class="folder-dropdown-item <?= ($current_sheet && $current_sheet['id'] == $s['id']) ? 'active' : '' ?>">
                                <a href="<?= base_url('admin/project_sheet/' . $project['id'] . '/' . $s['id']) ?>" style="flex: 1; text-decoration: none; color: inherit; display: flex; align-items: center; gap: 8px;">
                                    <span><?= $s['table_name'] ?></span>
                                </a>
                                <i class="bi bi-three-dots-vertical" onclick="event.preventDefault(); event.stopPropagation(); toggleTableOptions(event, <?= $s['id'] ?>)" style="cursor: pointer; opacity: 0.6; padding: 5px;"></i>
                                
                                <div class="table-options-menu" id="table-options-<?= $s['id'] ?>">
                                    <div class="table-option-item" onclick="openSharing(<?= $s['id'] ?>, '<?= addslashes($s['table_name']) ?>')"><i class="bi bi-share"></i> Sharing & Permissions</div>
                                    <div class="table-option-item" onclick="renameTable(<?= $s['id'] ?>, '<?= addslashes($s['table_name']) ?>')"><i class="bi bi-pencil"></i> Rename Table</div>
                                    <div class="table-option-item" onclick="duplicateTable(<?= $s['id'] ?>)"><i class="bi bi-files"></i> Duplicate Table</div>
                                    <div class="table-option-item" onclick="moveToFolder(<?= $s['id'] ?>)"><i class="bi bi-folder-symlink"></i> Move to Folder</div>
                                    <div class="table-option-item delete" onclick="deleteTable(<?= $s['id'] ?>)"><i class="bi bi-trash"></i> Delete Table</div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($sheets as $s): ?>
                    <div style="position: relative; display: flex; align-items: center;">
                        <a href="<?= base_url('admin/project_sheet/' . $project['id'] . '/' . $s['id']) ?>" 
                           style="padding: 10px 20px; border-radius: 8px; background: <?= ($current_sheet && $current_sheet['id'] == $s['id']) ? 'var(--primary)' : '#fff' ?>; color: <?= ($current_sheet && $current_sheet['id'] == $s['id']) ? '#fff' : 'var(--text-admin-muted)' ?>; text-decoration: none; font-weight: 600; border: 1px solid <?= ($current_sheet && $current_sheet['id'] == $s['id']) ? 'var(--primary)' : 'var(--border)' ?>; white-space: nowrap; display: flex; align-items: center; gap: 8px; padding-right: 40px;">
                            <i class="bi bi-table"></i> <?= $s['table_name'] ?? 'All' ?>
                        </a>
                        <i class="bi bi-three-dots-vertical" onclick="event.preventDefault(); toggleTableOptions(event, <?= $s['id'] ?>)" 
                           style="position: absolute; right: 8px; cursor: pointer; color: <?= ($current_sheet && $current_sheet['id'] == $s['id']) ? '#fff' : '#cbd5e1' ?>; font-size: 1rem;"></i>
                        
                        <div class="table-options-menu" id="table-options-<?= $s['id'] ?>">
                            <div class="table-option-item" onclick="openSharing(<?= $s['id'] ?>, '<?= addslashes($s['table_name']) ?>')"><i class="bi bi-share"></i> Sharing & Permissions</div>
                            <div class="table-option-item" onclick="renameTable(<?= $s['id'] ?>, '<?= addslashes($s['table_name']) ?>')"><i class="bi bi-pencil"></i> Rename Table</div>
                            <div class="table-option-item" onclick="duplicateTable(<?= $s['id'] ?>)"><i class="bi bi-files"></i> Duplicate Table</div>
                            <div class="table-option-item" onclick="moveToFolder(<?= $s['id'] ?>)"><i class="bi bi-folder-symlink"></i> Move to Folder</div>
                            <div class="table-option-item delete" onclick="deleteTable(<?= $s['id'] ?>)"><i class="bi bi-trash"></i> Delete Table</div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        <?php endforeach; ?>

        <button type="button" onclick="createNewTable()" style="padding: 10px 20px; border-radius: 8px; background: #fff; color: var(--primary); border: 1px dashed var(--primary); font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 8px;">
            <i class="bi bi-plus-lg"></i> New Table
        </button>
        <button type="button" onclick="createNewFolder()" style="padding: 10px 20px; border-radius: 8px; background: #fff; color: #64748b; border: 1px dashed #cbd5e1; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 8px;">
            <i class="bi bi-folder-plus"></i> New Folder
        </button>
    </div>

    <div class="table-header-top" style="margin-bottom: 20px; border-radius: 12px; border: 1px solid var(--border);">
        <div class="table-title">
            <i class="bi bi-grid-3x3" style="color: var(--primary);"></i>
            <span><?= $table_name ?> / All</span>
        </div>
        <div class="table-actions">
            <div class="search-input-group">
                <i class="bi bi-search"></i>
                <input type="text" placeholder="Search Records...">
            </div>
            <button type="button" class="btn btn-primary" onclick="toggleSidebar(true)" style="padding: 8px 20px; border-radius: 8px;">
                <i class="bi bi-plus-lg"></i> Add Records
            </button>
        </div>
    </div>

    <form action="<?= base_url('admin/save_sheet/' . $project['id'] . ($current_sheet ? '/' . $current_sheet['id'] : '')) ?>" method="post" enctype="multipart/form-data" id="sheet-form" onsubmit="prepareData()">
        <input type="hidden" name="table_name" value="<?= $table_name ?>">
        <input type="hidden" name="folder_name" value="<?= isset($current_sheet['folder_name']) ? $current_sheet['folder_name'] : 'Main' ?>">
        <input type="hidden" name="json_data" id="json_data">
        <div class="admin-card spreadsheet-container" style="padding: 0;">
            <table class="admin-table" id="dynamic-sheet" style="min-width: 1500px; margin-bottom: 0; table-layout: fixed;">
                <thead>
                    <tr id="header-row">
                        <th style="width: 50px; text-align: center;">
                            <input type="checkbox" id="select-all-checkbox" onchange="toggleSelectAll(this)" style="width: 16px; height: 16px; border-radius: 4px; border: 1px solid var(--border);">
                        </th>
                        <?php foreach ($config as $idx => $col): ?>
                             <th style="min-width: 200px; position: relative;">
                                <div class="col-header-content">
                                    <?php 
                                        $icon = 'bi-type';
                                        if ($col['type'] == 'number') $icon = 'bi-hash';
                                        if ($col['type'] == 'date') $icon = 'bi-calendar3';
                                        if ($col['type'] == 'amount') $icon = 'bi-currency-rupee';
                                        
                                        $col_options = $col['options'] ?? [];
                                    ?>
                                    <i class="bi <?= $icon ?> col-icon"></i>
                                    <input type="text" name="col_name[]" value="<?= $col['name'] ?>" placeholder="Column..." style="border: none; background: none; font-weight: 600; width: 100%; outline: none;">
                                    
                                    <input type="hidden" name="col_options[]" value="<?= htmlspecialchars(json_encode($col_options)) ?>">
                                    
                                    <div style="display: none;">
                                        <select name="col_type[]" onchange="updateCellTypes(<?= $idx ?>, this.value)">
                                            <option value="text" <?= $col['type'] == 'text' ? 'selected' : '' ?>>Text</option>
                                            <option value="number" <?= $col['type'] == 'number' ? 'selected' : '' ?>>Number</option>
                                            <option value="percentage" <?= $col['type'] == 'percentage' ? 'selected' : '' ?>>Percentage</option>
                                            <option value="amount" <?= $col['type'] == 'amount' ? 'selected' : '' ?>>Amount</option>
                                            <option value="unit" <?= $col['type'] == 'unit' ? 'selected' : '' ?>>Unit</option>
                                            <option value="phone" <?= $col['type'] == 'phone' ? 'selected' : '' ?>>Phone Number</option>
                                            <option value="email" <?= $col['type'] == 'email' ? 'selected' : '' ?>>Email</option>
                                            <option value="location" <?= $col['type'] == 'location' ? 'selected' : '' ?>>Location</option>
                                            <option value="date" <?= $col['type'] == 'date' ? 'selected' : '' ?>>Date</option>
                                            <option value="time" <?= $col['type'] == 'time' ? 'selected' : '' ?>>Time</option>
                                            <option value="dropdown" <?= $col['type'] == 'dropdown' ? 'selected' : '' ?>>Dropdown</option>
                                            <option value="yesno" <?= $col['type'] == 'yesno' ? 'selected' : '' ?>>Yes / No</option>
                                            <option value="status" <?= $col['type'] == 'status' ? 'selected' : '' ?>>Status</option>
                                            <option value="file" <?= $col['type'] == 'file' ? 'selected' : '' ?>>Photo & File</option>
                                            <option value="label" <?= $col['type'] == 'label' ? 'selected' : '' ?>>Label</option>
                                            <option value="signature" <?= $col['type'] == 'signature' ? 'selected' : '' ?>>Signature</option>
                                            <option value="formula" <?= $col['type'] == 'formula' ? 'selected' : '' ?>>Formula</option>
                                        </select>
                                    </div>
                                    <script>
                                         document.getElementsByName('col_name[]')[<?= $idx ?>].addEventListener('change', autoSave);
                                         document.getElementsByName('col_type[]')[<?= $idx ?>].addEventListener('change', autoSave);
                                     </script>

                                    <i class="bi bi-three-dots-vertical" style="cursor: pointer; color: var(--text-admin-muted);" onclick="toggleColMenu(event, <?= $idx ?>)"></i>
                                    
                                    <div class="col-options-menu" id="col-menu-<?= $idx ?>">
                                        <div class="col-option-item"><i class="bi bi-dash"></i> Sort</div>
                                        <div class="col-option-item" onclick="toggleColMenu(event, <?= $idx ?>); toggleColModal(true, <?= $idx ?>)"><i class="bi bi-pencil"></i> Edit Column</div>
                                        <div class="col-option-item"><i class="bi bi-eye-slash"></i> Hide Column</div>
                                        <div class="col-option-item"><i class="bi bi-pin"></i> Freeze column</div>
                                        <div class="col-option-item delete" onclick="removeColumn(<?= $idx ?>)"><i class="bi bi-trash"></i> Delete Column</div>
                                    </div>
                                </div>
                            </th>
                        <?php endforeach; ?>
                        <th style="width: 50px; text-align: center;"><i class="bi bi-plus-lg" style="cursor: pointer;" onclick="toggleColModal(true)"></i></th>
                    </tr>
                </thead>
                <tbody id="sheet-body">
                    <?php if (empty($sheet_data)): ?>
                        <tr>
                            <td colspan="<?= count($config) + 2 ?>" style="padding: 0;">
                                <div class="empty-state">
                                    <div class="empty-icon" style="margin-bottom: 25px;">
                                        <i class="bi bi-box-seam" style="font-size: 3.5rem;"></i>
                                    </div>
                                    <h3 class="empty-title" style="font-size: 1.3rem;">No Records yet</h3>
                                    <p class="empty-subtitle" style="font-size: 0.9rem;">Add your first Record to get started.</p>
                                    <div style="display: flex; gap: 12px;">
                                        <button type="button" class="btn btn-primary" onclick="toggleSidebar(true)" style="padding: 8px 20px; border-radius: 6px; background: #4285f4; border: none;">
                                            <i class="bi bi-plus-lg"></i> Add Records
                                        </button>
                                        <button type="button" class="btn" style="background: #fff; border: 1px solid var(--border); padding: 8px 20px; border-radius: 6px; color: var(--text-admin-muted); font-size: 0.85rem;" onclick="toggleColModal(true)">
                                            <i class="bi bi-layout-three-columns"></i> Add Column
                                        </button>
                                        <button type="button" class="btn" style="background: #fff; border: 1px solid var(--border); padding: 8px 20px; border-radius: 6px; color: var(--text-admin-muted); font-size: 0.85rem;">
                                            <i class="bi bi-upload"></i> Import
                                        </button>
                                    </div>
                                    <a href="#" style="margin-top: 20px; color: #4285f4; font-size: 0.85rem; text-decoration: none; display: flex; align-items: center; gap: 5px;">
                                        <i class="bi bi-play-circle"></i> Learn more
                                    </a>
                                </div>
                            </td>
                        </tr>
<?php else: ?>
    <?php foreach ($sheet_data as $r_idx => $row): ?>
        <tr class="data-row">
            <td style="text-align: center;"><input type="checkbox" class="row-checkbox"></td>
            <?php foreach ($config as $c_idx => $col): ?>
                <td>
                                        <?php if ($col['type'] == 'file' || $col['type'] == 'signature'): ?>
                                            <div class="file-cell-ui <?= !empty($row[$c_idx]) ? 'has-file' : '' ?>" onclick="openMediaModal(this)">
                                                <div class="file-indicator">
                                                    <i class="bi <?= !empty($row[$c_idx]) ? 'bi-check-lg' : 'bi-plus' ?>"></i>
                                                </div>
                                                <?php if (!empty($row[$c_idx])): ?>
                                                    <span class="file-name-label"><?= basename($row[$c_idx]) ?></span>
                                                    <input type="hidden" name="cell[<?= $r_idx ?>][<?= $c_idx ?>]" value="<?= $row[$c_idx] ?>">
                                                <?php endif; ?>
                                                <input type="file" name="cell_files[<?= $r_idx ?>][<?= $c_idx ?>]" style="display: none;" onchange="handleFileChange(this)">
                                            </div>
                                        <?php elseif ($col['type'] == 'dropdown' || $col['type'] == 'status'): ?>
                                            <select name="cell[<?= $r_idx ?>][<?= $c_idx ?>]" class="form-control" onchange="autoSave()" style="background: var(--bg-admin-card); border: 1px solid var(--border-admin); color: var(--text-admin-main); width: 100%; padding: 8px; border-radius: 6px;">
                                                <option value="">-- Select --</option>
                                                <?php 
                                                    $opts = $col['options'] ?? [];
                                                    if (empty($opts)) {
                                                        if ($col['type'] == 'status') {
                                                            $opts = ['Pending', 'In Progress', 'Completed', 'On Hold'];
                                                        } else {
                                                            $opts = array_column($employees, 'name');
                                                        }
                                                    }
                                                ?>
                                                <?php foreach ($opts as $opt): ?>
                                                    <option value="<?= $opt ?>" <?= ($row[$c_idx] ?? '') == $opt ? 'selected' : '' ?>><?= $opt ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        <?php elseif ($col['type'] == 'yesno'): ?>
                                            <select name="cell[<?= $r_idx ?>][<?= $c_idx ?>]" class="form-control" onchange="autoSave()" style="background: var(--bg-admin-card); border: 1px solid var(--border-admin); color: var(--text-admin-main); width: 100%; padding: 8px; border-radius: 6px;">
                                                <option value="Yes" <?= ($row[$c_idx] ?? '') == 'Yes' ? 'selected' : '' ?>>Yes</option>
                                                <option value="No" <?= ($row[$c_idx] ?? '') == 'No' ? 'selected' : '' ?>>No</option>
                                            </select>
                                        <?php elseif ($col['type'] == 'percentage'): ?>
                                            <div style="position: relative;">
                                                <input type="number" name="cell[<?= $r_idx ?>][<?= $c_idx ?>]" value="<?= $row[$c_idx] ?? '' ?>" class="form-control" onchange="autoSave()" style="background: var(--bg-admin-card); border: 1px solid var(--border-admin); color: var(--text-admin-main); width: 100%; padding: 8px 25px 8px 8px; border-radius: 6px;">
                                                <span style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); color: var(--text-admin-muted);">%</span>
                                            </div>
                                        <?php elseif ($col['type'] == 'amount'): ?>
                                            <div style="position: relative;">
                                                <span style="position: absolute; left: 10px; top: 50%; transform: translateY(-50%); color: var(--text-admin-muted);">₹</span>
                                                <input type="number" name="cell[<?= $r_idx ?>][<?= $c_idx ?>]" value="<?= $row[$c_idx] ?? '' ?>" class="form-control" onchange="autoSave()" style="background: var(--bg-admin-card); border: 1px solid var(--border-admin); color: var(--text-admin-main); width: 100%; padding: 8px 8px 8px 25px; border-radius: 6px;">
                                            </div>
                                        <?php elseif ($col['type'] == 'formula'): ?>
                                            <?php $formula = $col['options']['formula'] ?? ''; ?>
                                            <input type="text" name="cell[<?= $r_idx ?>][<?= $c_idx ?>]" value="<?= !empty($row[$c_idx]) ? $row[$c_idx] : $formula ?>" class="form-control formula-input" data-formula="<?= $formula ?>" onchange="autoSave()" onfocus="showFormula(this)" onblur="hideFormula(this)" placeholder="e.g. = {A} + {B}" style="background: rgba(52, 152, 219, 0.05); border: 1px solid #3498db; color: #3498db; width: 100%; padding: 8px; border-radius: 6px; font-weight: 600;">
                                        <?php else: ?>
                                            <input type="<?= ($col['type'] == 'phone') ? 'tel' : (($col['type'] == 'unit' || $col['type'] == 'location' || $col['type'] == 'label') ? 'text' : $col['type']) ?>" name="cell[<?= $r_idx ?>][<?= $c_idx ?>]" value="<?= $row[$c_idx] ?? '' ?>" class="form-control" onchange="autoSave()" style="background: var(--bg-admin-card); border: 1px solid var(--border-admin); color: var(--text-admin-main); width: 100%; padding: 8px; border-radius: 6px;">
                                        <?php endif; ?>
                                    </td>
                                <?php endforeach; ?>
                                <td style="text-align: center; position: relative; width: 50px;">
                                    <button type="button" class="btn-action-trigger" style="background: rgba(0,0,0,0.03); border: none; padding: 5px 10px; border-radius: 4px; color: var(--text-admin-muted);">
                                        <i class="bi bi-three-dots-vertical"></i>
                                    </button>
                                    <div class="row-options-menu"></div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>

            <div class="table-footer">
                <i class="bi bi-list-nested" style="margin-right: 10px;"></i>
                <span><?= count($sheet_data) ?> Records</span>
            </div>
        </div>

        <div style="margin-top: 30px; display: flex; justify-content: flex-end; display: none;">
            <button type="submit" class="btn btn-primary" style="padding: 12px 40px; border-radius: 8px;" id="manual-save-btn">
                <i class="bi bi-cloud-check"></i> Save Sheet Data
            </button>
        </div>
    </form>
    
    <div id="save-status-indicator" style="position: fixed; bottom: 20px; right: 20px; background: #1e293b; color: #fff; padding: 10px 20px; border-radius: 30px; font-size: 0.85rem; display: flex; align-items: center; gap: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); z-index: 9999; opacity: 0; transition: opacity 0.3s; pointer-events: none;">
        <i class="bi bi-cloud-check" id="status-icon"></i>
        <span id="status-text">All changes saved</span>
    </div>

    <!-- Media Upload Modal -->
    <div id="media-upload-modal" class="media-modal" onclick="closeMediaModal(event)">
        <div class="media-modal-content" onclick="event.stopPropagation()">
            <div class="upload-cloud-icon">
                <i class="bi bi-cloud-arrow-up"></i>
            </div>
            <div class="upload-title">
                Drop files here or <span onclick="document.getElementById('hidden-media-input').click()">browse</span>
            </div>
            <div class="media-actions">
                <button type="button" class="media-action-btn" onclick="startCamera()">
                    <i class="bi bi-camera"></i> Take photo
                </button>
                <button type="button" class="media-action-btn" id="audio-record-btn" onclick="toggleAudioRecording()">
                    <i class="bi bi-mic"></i> Record audio
                </button>
            </div>
            <div id="camera-preview-container">
                <video id="camera-video" autoplay playsinline></video>
            </div>
            <div class="camera-controls" id="camera-controls">
                <button type="button" class="btn btn-primary" onclick="capturePhoto()">
                    <i class="bi bi-camera-fill"></i> Capture
                </button>
                <button type="button" class="btn" style="background: #f1f5f9;" onclick="stopCamera()">
                    Retake
                </button>
            </div>
            
            <button type="button" class="btn" style="margin-top: 30px; color: var(--text-admin-muted);" onclick="closeMediaModal()">Cancel</button>
        </div>
    </div>

    <!-- Signature Pad Modal -->
    <div id="signature-modal" class="signature-modal">
        <div class="signature-pad-container">
            <div class="signature-header">
                <h3 style="margin: 0; font-size: 1.1rem; font-weight: 700; color: #1e293b; display: flex; align-items: center; gap: 10px;">
                    <i class="bi bi-pencil-fill" style="color: #4285f4;"></i> Digital Signature
                </h3>
                <button type="button" class="close-btn" onclick="closeSignatureModal()">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
            <div class="signature-body">
                <p style="font-size: 0.85rem; color: #64748b; margin-bottom: 20px;">Please sign within the box below.</p>
                <div class="signature-canvas-wrapper">
                    <canvas id="signature-canvas"></canvas>
                </div>
            </div>
            <div class="signature-footer">
                <button type="button" class="signature-btn signature-btn-clear" onclick="clearSignature()">
                    <i class="bi bi-eraser-fill"></i> Clear
                </button>
                <button type="button" class="signature-btn signature-btn-save" onclick="saveSignature()">
                    <i class="bi bi-check-circle-fill"></i> Apply Signature
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Create Record Sidebar (Moved outside the animate-up for cleaner nesting) -->
<div id="record-sidebar" class="record-sidebar">
    <div class="sidebar-header">
        <h3>Create Record</h3>
        <button type="button" class="close-btn" onclick="toggleSidebar(false)">
            <i class="bi bi-x-lg"></i>
        </button>
    </div>
    <div class="sidebar-body" id="sidebar-form-container">
        <!-- Dynamic form fields will be injected here -->
    </div>
    <div class="sidebar-footer">
        <button type="button" class="btn btn-primary" style="width: 100%; padding: 15px; border-radius: 12px;" onclick="addRecordFromSidebar()">
            Create Record
        </button>
    </div>
</div>

<!-- Record Details Modal -->
<div id="details-modal" class="modal-overlay">
    <div class="modal-content" style="max-width: 900px; width: 95%;">
        <div class="modal-header" style="background: var(--primary); color: #fff; padding: 20px 30px;">
            <h3 style="margin:0; font-weight:700;"><i class="bi bi-info-circle" style="margin-right:10px;"></i> Master Record View</h3>
            <button type="button" class="close-btn" onclick="toggleModal('details-modal', false)" style="color: #fff;"><i class="bi bi-x-lg"></i></button>
        </div>
        <div class="modal-body" id="details-modal-body" style="padding:40px; background: #f8fafc; max-height: 80vh; overflow-y: auto;">
            <!-- Content injected via JS -->
        </div>
        <div class="modal-footer" style="padding:20px; border-top:1px solid var(--border); text-align:right;">
            <button type="button" class="btn btn-primary" onclick="toggleModal('details-modal', false)">Close Details</button>
        </div>
    </div>
</div>
<script>
    function toggleSidebar(show) {
        const sidebar = document.getElementById('record-sidebar');
        const overlay = document.getElementById('sidebar-overlay');
        const container = document.getElementById('sidebar-form-container');
        
        if (show) {
            // Generate form fields dynamically based on header
            container.innerHTML = '';
            const colNames = document.getElementsByName('col_name[]');
            const colTypes = document.getElementsByName('col_type[]');
            
            for (let i = 0; i < colNames.length; i++) {
                const name = colNames[i].value || `Column ${i + 1}`;
                const type = colTypes[i].value;
                
                let icon = 'bi-type';
                if (type === 'date') icon = 'bi-calendar';
                if (type === 'number') icon = 'bi-hash';
                if (type === 'amount') icon = 'bi-currency-rupee';
                if (type === 'dropdown' || type === 'status' || type === 'yesno') icon = 'bi-list-ul';
                if (type === 'file') icon = 'bi-image';
                if (type === 'phone') icon = 'bi-telephone';
                if (type === 'email') icon = 'bi-envelope';
                if (type === 'location') icon = 'bi-geo-alt';
                if (type === 'formula') icon = 'bi-calculator';
                if (type === 'percentage') icon = 'bi-percent';
                if (type === 'signature') icon = 'bi-pencil-fill';

                let inputHtml = '';
                if (type === 'dropdown') {
                    inputHtml = `
                        <select class="form-control sidebar-input" style="width: 100%; padding: 12px; border-radius: 8px; background: #f8fafc; border: 1px solid rgba(0,0,0,0.05);">
                            <option value="">Select ${name}</option>
                            <?php foreach ($employees as $emp): ?>
                                <option value="<?= $emp['name'] ?>"><?= $emp['name'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    `;
                } else if (type === 'yesno') {
                    inputHtml = `
                        <select class="form-control sidebar-input" style="width: 100%; padding: 12px; border-radius: 8px; background: #f8fafc; border: 1px solid rgba(0,0,0,0.05);">
                            <option value="Yes">Yes</option>
                            <option value="No">No</option>
                        </select>
                    `;
                } else if (type === 'status') {
                    inputHtml = `
                        <select class="form-control sidebar-input" style="width: 100%; padding: 12px; border-radius: 8px; background: #f8fafc; border: 1px solid rgba(0,0,0,0.05);">
                            <option value="Pending">Pending</option>
                            <option value="In Progress">In Progress</option>
                            <option value="Completed">Completed</option>
                        </select>
                    `;
                } else if (type === 'file' || type === 'signature') {
                    const uploadIcon = type === 'signature' ? 'bi-pencil' : 'bi-cloud-arrow-up';
                    const uploadText = type === 'signature' ? 'Click to sign' : 'Click to upload';
                    const uploadAction = type === 'signature' ? 'openSignatureModal(this)' : 'this.querySelector(\'input\').click()';
                    
                    inputHtml = `
                        <div class="file-cell-ui" style="border: 2px dashed rgba(0,0,0,0.05); border-radius: 12px; padding: 20px; text-align: center; background: #f8fafc; cursor: pointer; display: flex; flex-direction: column; align-items: center; width: 100%;" onclick="${uploadAction}">
                            <div class="file-indicator" style="margin-bottom: 10px;">
                                <i class="bi ${uploadIcon}" style="font-size: 1.5rem; color: var(--primary);"></i>
                            </div>
                            <p class="file-name-label" style="margin: 0; font-size: 0.8rem; color: var(--text-admin-muted);">${uploadText}</p>
                            <input type="file" class="sidebar-input" style="display: none;">
                        </div>
                    `;
                } else {
                    let inputType = type;
                    if (type === 'phone') inputType = 'tel';
                    if (['unit', 'location', 'label', 'formula', 'percentage', 'amount'].includes(type)) inputType = 'text';
                    if (['number'].includes(type)) inputType = 'number';
                    
                    inputHtml = `<input type="${inputType}" class="form-control sidebar-input" placeholder="Enter ${name}" style="width: 100%; padding: 12px; border-radius: 8px; background: #f8fafc; border: 1px solid rgba(0,0,0,0.05);">`;
                }

                container.innerHTML += `
                    <div class="sidebar-field">
                        <label><i class="bi ${icon}"></i> ${name}</label>
                        ${inputHtml}
                    </div>
                `;
            }

            sidebar.classList.add('active');
            overlay.classList.add('active');
        } else {
            sidebar.classList.remove('active');
            overlay.classList.remove('active');
        }
    }

    function addRecordFromSidebar() {
        // Add a new row to the table
        addRow();
        
        // Get the last row added
        const body = document.getElementById('sheet-body');
        const lastRow = body.rows[body.rows.length - 1];
        const sidebarInputs = document.querySelectorAll('.sidebar-input');
        
        sidebarInputs.forEach((input, i) => {
            const tableCell = lastRow.cells[i + 1]; // Offset by 1 for checkbox column
            const tableInput = tableCell.querySelector('input, select');
            
            if (tableInput) {
                if (input.type === 'file') {
                    // We can't easily programmatically set file input value due to security
                    // But we can clone the file input if needed
                    if (input.files.length > 0) {
                        const dt = new DataTransfer();
                        dt.items.add(input.files[0]);
                        tableInput.files = dt.files;
                    }
                } else {
                    tableInput.value = input.value;
                }
            }
        });
        
        toggleSidebar(false);
        
        // Auto-submit the form to save the new record to the database immediately
        document.getElementById('sheet-form').submit();
    }

    // Old addColumn removed to favor addColumnFromModal


    function toggleColMenu(event, idx) {
        event.stopPropagation();
        const trigger = event.currentTarget;
        const menu = document.getElementById(`col-menu-${idx}`);
        
        if (!menu) return;

        // Close other col menus
        document.querySelectorAll('.col-options-menu').forEach(m => {
            if (m.id !== `col-menu-${idx}`) m.classList.remove('active');
        });

        const isActive = menu.classList.toggle('active');
        
        if (isActive) {
            const rect = trigger.getBoundingClientRect();
            const menuHeight = menu.offsetHeight || 250;
            const spaceBelow = window.innerHeight - rect.bottom;
            
            // Position relative to viewport
            menu.style.right = (window.innerWidth - rect.right) + 'px';
            menu.style.left = 'auto';
            
            if (spaceBelow < menuHeight) {
                menu.style.top = 'auto';
                menu.style.bottom = (window.innerHeight - rect.top) + 'px';
            } else {
                menu.style.top = rect.bottom + 'px';
                menu.style.bottom = 'auto';
            }
        }
    }

    function toggleRowMenu(event, idx) {
        event.stopPropagation();
        const trigger = event.currentTarget;
        const menu = document.getElementById(`row-menu-${idx}`);
        
        if (!menu) return;

        // Close other menus
        document.querySelectorAll('.row-options-menu').forEach(m => {
            if (m.id !== `row-menu-${idx}`) m.classList.remove('active');
        });

        const isActive = menu.classList.toggle('active');
        
        if (isActive) {
            // Use fixed positioning to escape overflow: auto containers
            const rect = trigger.getBoundingClientRect();
            const menuHeight = menu.offsetHeight || 350;
            const spaceBelow = window.innerHeight - rect.bottom;
            
            menu.style.right = (window.innerWidth - rect.right) + 'px';
            
            if (spaceBelow < menuHeight) {
                menu.style.top = 'auto';
                menu.style.bottom = (window.innerHeight - rect.top) + 'px';
            } else {
                menu.style.top = rect.bottom + 'px';
                menu.style.bottom = 'auto';
            }
        }
    }

    document.addEventListener('click', function() {
        document.querySelectorAll('.col-options-menu').forEach(menu => menu.classList.remove('active'));
        document.querySelectorAll('.row-options-menu').forEach(menu => menu.classList.remove('active'));
    });

    function removeColumn(idx) {
        if (confirm('Delete this entire column and all its data?')) {
            const headerRow = document.getElementById('header-row');
            headerRow.deleteCell(idx + 1); // +1 because of checkbox column
            document.querySelectorAll('.data-row').forEach(row => row.deleteCell(idx + 1));
            reindexCells();
        }
    }

    function removeRowByIdx(idx) {
        if (confirm('Delete this record?')) {
            const body = document.getElementById('sheet-body');
            body.deleteRow(idx);
            reindexCells();
        }
    }

    function insertRowAbove(idx) {
        addRow(idx);
    }

    function insertRowBelow(idx) {
        addRow(idx + 1);
    }

    function duplicateRow(idx) {
        const body = document.getElementById('sheet-body');
        const sourceRow = body.rows[idx];
        const newRow = addRow(idx + 1);
        
        // Copy values
        const sourceInputs = sourceRow.querySelectorAll('input, select');
        const targetInputs = newRow.querySelectorAll('input, select');
        
        sourceInputs.forEach((input, i) => {
            if (targetInputs[i] && input.type !== 'checkbox') {
                targetInputs[i].value = input.value;
            }
        });
    }

    function getCellHtml(r_idx, c_idx, type, options = []) {
        if (type === 'file' || type === 'signature') {
            const icon = type === 'signature' ? 'bi-pen' : 'bi-plus';
            const action = type === 'signature' ? 'openSignatureModal(this)' : 'openMediaModal(this)';
            return `
                <div class="file-cell-ui" onclick="${action}">
                    <div class="file-indicator">
                        <i class="bi ${icon}"></i>
                    </div>
                    <span class="file-name-label"></span>
                    <input type="file" name="cell_files[${r_idx}][${c_idx}]" style="display: none;" onchange="handleFileChange(this)">
                </div>
            `;
        } else if (type === 'dropdown' || type === 'status') {
            let optsHtml = '<option value="">-- Select --</option>';
            if (options && options.length > 0) {
                options.forEach(opt => {
                    optsHtml += `<option value="${opt}">${opt}</option>`;
                });
            } else if (type === 'status') {
                const defaults = ['Pending', 'In Progress', 'Completed', 'On Hold'];
                defaults.forEach(opt => {
                    optsHtml += `<option value="${opt}">${opt}</option>`;
                });
            } else {
                // Fallback to employees for dropdown if no custom options
                <?php foreach ($employees as $emp): ?>
                optsHtml += `<option value="<?= $emp['name'] ?>"><?= $emp['name'] ?></option>`;
                <?php endforeach; ?>
            }
            return `<select name="cell[${r_idx}][${c_idx}]" class="form-control" onchange="autoSave()" style="background: var(--bg-admin-card); border: 1px solid var(--border-admin); color: var(--text-admin-main); width: 100%; padding: 8px; border-radius: 6px;">${optsHtml}</select>`;
        } else if (type === 'yesno') {
            return `<select name="cell[${r_idx}][${c_idx}]" class="form-control" onchange="autoSave()" style="background: var(--bg-admin-card); border: 1px solid var(--border-admin); color: var(--text-admin-main); width: 100%; padding: 8px; border-radius: 6px;"><option value="Yes">Yes</option><option value="No">No</option></select>`;
        } else if (type === 'percentage') {
            return `<div style="position: relative;"><input type="number" name="cell[${r_idx}][${c_idx}]" class="form-control" onchange="autoSave()" style="background: var(--bg-admin-card); border: 1px solid var(--border-admin); color: var(--text-admin-main); width: 100%; padding: 8px 25px 8px 8px; border-radius: 6px;"><span style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); color: var(--text-admin-muted);">%</span></div>`;
        } else if (type === 'amount') {
            return `<div style="position: relative;"><span style="position: absolute; left: 10px; top: 50%; transform: translateY(-50%); color: var(--text-admin-muted);">₹</span><input type="number" name="cell[${r_idx}][${c_idx}]" class="form-control" onchange="autoSave()" style="background: var(--bg-admin-card); border: 1px solid var(--border-admin); color: var(--text-admin-main); width: 100%; padding: 8px 8px 8px 25px; border-radius: 6px;"></div>`;
        } else if (type === 'formula') {
            const formula = (options && options.formula) ? options.formula : '';
            return `<input type="text" name="cell[${r_idx}][${c_idx}]" class="form-control formula-input" data-formula="${formula}" value="${formula}" onchange="autoSave()" onfocus="showFormula(this)" onblur="hideFormula(this)" placeholder="= {Column} + 10" style="background: rgba(52, 152, 219, 0.05); border: 1px solid #3498db; color: #3498db; width: 100%; padding: 8px; border-radius: 6px; font-weight: 600;">`;
        } else {
            let inputType = type;
            if (type === 'phone') inputType = 'tel';
            if (['unit', 'location', 'label'].includes(type)) inputType = 'text';
            return `<input type="${inputType}" name="cell[${r_idx}][${c_idx}]" class="form-control" onchange="autoSave()" style="background: var(--bg-admin-card); border: 1px solid var(--border-admin); color: var(--text-admin-main); width: 100%; padding: 8px; border-radius: 6px;">`;
        }
    }

    function addRow(atIdx = null) {
        const body = document.getElementById('sheet-body');
        
        // Remove empty state if it exists
        const emptyState = body.querySelector('.empty-state');
        if (emptyState) {
            body.innerHTML = '';
        }

        const rowCount = body.rows.length;
        const colCount = document.getElementById('header-row').cells.length - 2; // -2 for checkbox and action col
        
        const tr = document.createElement('tr');
        tr.className = 'data-row';
        
        // Checkbox column
        const checkTd = document.createElement('td');
        checkTd.style.textAlign = 'center';
        checkTd.innerHTML = `<input type="checkbox" class="row-checkbox">`;
        tr.appendChild(checkTd);

        for (let i = 0; i < colCount; i++) {
            const typeSelect = document.getElementsByName('col_type[]')[i];
            const type = typeSelect ? typeSelect.value : 'text';
            const optionsInput = document.getElementsByName('col_options[]')[i];
            const options = optionsInput ? JSON.parse(optionsInput.value || '[]') : [];
            
            const td = document.createElement('td');
            td.innerHTML = getCellHtml(rowCount, i, type, options);
            tr.appendChild(td);
        }
        
        const actionTd = document.createElement('td');
        actionTd.style.textAlign = 'center';
        actionTd.style.position = 'relative';
        actionTd.style.width = '50px';
        actionTd.innerHTML = `
            <button type="button" class="btn-action-trigger" style="background: rgba(0,0,0,0.03); border: none; padding: 5px 10px; border-radius: 4px; color: var(--text-admin-muted);">
                <i class="bi bi-three-dots-vertical"></i>
            </button>
            <div class="row-options-menu"></div>
        `;
        tr.appendChild(actionTd);

        if (atIdx !== null) {
            body.insertBefore(tr, body.rows[atIdx]);
        } else {
            body.appendChild(tr);
        }
        
        reindexCells();
        autoSave();
        return tr;
    }

    function removeColumn(idx) {
        if (confirm("Are you sure you want to permanently delete this column and all its data? This action will save the table immediately.")) {
            const headerRow = document.getElementById('header-row');
            // idx+1 because 0 is checkbox
            if (headerRow.cells[idx + 1]) {
                headerRow.deleteCell(idx + 1);
                document.querySelectorAll('.data-row').forEach(row => {
                    if (row.cells[idx + 1]) row.deleteCell(idx + 1);
                });
                reindexCells();
                prepareData();
                autoSave();
            }
        }
    }

    function removeRowByIdx(idx) {
        if (confirm("Are you sure you want to permanently delete this record? This action will save the table immediately.")) {
            const rows = document.querySelectorAll('.data-row');
            if (rows[idx]) {
                rows[idx].remove();
                reindexCells();
                prepareData();
                autoSave();
            }
        }
    }

    function removeRow(btn) {
        const row = btn.closest('tr');
        row.remove();
        reindexCells();
        autoSave();
    }

    function updateCellTypes(colIdx, newType) {
        document.querySelectorAll('.data-row').forEach((row, r_idx) => {
            const cell = row.cells[colIdx + 1]; // +1 for checkbox column
            if (!cell) return;
            
            const optionsInput = document.getElementsByName('col_options[]')[colIdx];
            const options = optionsInput ? JSON.parse(optionsInput.value || '[]') : [];
            
            cell.innerHTML = getCellHtml(r_idx, colIdx, newType, options);
        });
    }

    function reindexCells() {
        document.querySelectorAll('.data-row').forEach((row, r_idx) => {
            const cols = document.getElementsByName('col_type[]');
            // Reindex data inputs (offset by 1 for checkbox col)
            for (let c_idx = 0; c_idx < row.cells.length - 2; c_idx++) {
                const cell = row.cells[c_idx + 1];
                const input = cell.querySelector('input, select');
                if (input) {
                    const type = cols[c_idx] ? cols[c_idx].value : 'text';
                    if (type === 'file' || type === 'signature') {
                        input.name = input.type === 'file' ? `cell_files[${r_idx}][${c_idx}]` : `cell[${r_idx}][${c_idx}]`;
                    } else {
                        input.name = `cell[${r_idx}][${c_idx}]`;
                    }
                }
            }
            
            // Rebuild row action menu
            const actionTd = row.lastElementChild;
            const trigger = actionTd.querySelector('.btn-action-trigger');
            const menu = actionTd.querySelector('.row-options-menu');
            
            if (trigger) trigger.setAttribute('onclick', `toggleRowMenu(event, ${r_idx})`);
            if (menu) {
                menu.id = `row-menu-${r_idx}`;
                menu.innerHTML = `
                    <div class="row-option-item" onclick="viewRecordDetails(${r_idx})">
                        <i class="bi bi-info-circle"></i> 
                        <span>Record Details</span>
                    </div>
                    <div class="row-option-item" onclick="downloadRecordPDF(${r_idx})">
                        <i class="bi bi-file-earmark-pdf"></i> 
                        <div>
                            <span>Download as PDF</span>
                            <span class="row-option-subtext">3 columns excluded</span>
                        </div>
                    </div>
                    <div class="row-option-item" onclick="shareRecordAsText(${r_idx})">
                        <i class="bi bi-share"></i> 
                        <div>
                            <span>Share as Text</span>
                            <span class="row-option-subtext">3 columns excluded</span>
                        </div>
                    </div>
                    <div class="row-option-item" onclick="insertRowAbove(${r_idx})">
                        <i class="bi bi-arrow-up"></i> 
                        <span>Insert row above</span>
                    </div>
                    <div class="row-option-item" onclick="insertRowBelow(${r_idx})">
                        <i class="bi bi-arrow-down"></i> 
                        <span>Insert row below</span>
                    </div>
                    <div class="row-option-item" onclick="duplicateRow(${r_idx})">
                        <i class="bi bi-copy"></i> 
                        <span>Duplicate Record</span>
                    </div>
                    <div class="row-option-item delete" onclick="removeRowByIdx(${r_idx})">
                        <i class="bi bi-trash"></i> 
                        <span>Delete</span>
                    </div>
                `;
            }
        });
        
        // Update column removal buttons
        document.querySelectorAll('.col-header-content').forEach((container, idx) => {
            const trash = container.querySelector('.delete');
            const select = container.querySelector('select');
            const menu = container.querySelector('.bi-three-dots-vertical');
            if (menu) menu.setAttribute('onclick', `toggleColMenu(event, ${idx})`);
            if (trash) trash.setAttribute('onclick', `removeColumn(${idx})`);
            if (select) select.setAttribute('onchange', `updateCellTypes(${idx}, this.value)`);
        });
    }

    function removeLastColumn() {
        const headerRow = document.getElementById('header-row');
        const colCount = headerRow.cells.length - 1;
        if (colCount > 1) {
            removeColumn(colCount - 1);
        }
    }
    let editingColIdx = null;
    function toggleColModal(show, colIdx = null) {
        const modal = document.getElementById('col-modal');
        const submitBtn = modal.querySelector('button[onclick="confirmAddColumn()"]');
        editingColIdx = colIdx;

        if (show) {
            modal.classList.add('active');
            if (colIdx !== null) {
                // Populate for editing
                const name = document.getElementsByName('col_name[]')[colIdx].value;
                const type = document.getElementsByName('col_type[]')[colIdx].value;
                const optionsStr = document.getElementsByName('col_options[]')[colIdx].value;
                const options = JSON.parse(optionsStr || '[]');

                document.getElementById('modal-col-name').value = name;
                document.getElementById('modal-col-type').value = type;
                
                if (type === 'formula' && options.formula) {
                    document.getElementById('modal-col-formula').value = options.formula;
                } else {
                    document.getElementById('modal-col-formula').value = '';
                }
                
                handleModalTypeChange();

                if (options.length > 0) {
                    const list = document.getElementById('dropdown-options-list');
                    list.innerHTML = '';
                    options.forEach(opt => {
                        addNewOption(opt);
                    });
                }
                submitBtn.innerText = "UPDATE COLUMN";
            } else {
                submitBtn.innerText = "CREATE COLUMN";
            }
        } else {
            modal.classList.remove('active');
            // Reset
            document.getElementById('modal-col-type').value = "";
            document.getElementById('modal-col-name').value = "";
            document.getElementById('modal-col-formula').value = "";
            document.getElementById('dropdown-options-section').style.display = 'none';
            document.getElementById('formula-section').style.display = 'none';
            document.getElementById('dropdown-options-list').innerHTML = '';
        }
    }

    function handleModalTypeChange() {
        const type = document.getElementById('modal-col-type').value;
        const optionsSection = document.getElementById('dropdown-options-section');
        const optionsLabel = optionsSection.querySelector('label');
        const selectIcon = document.querySelector('.select-icon');

        // Update icon based on type
        let iconClass = 'bi-list-ul';
        if (type === 'status') iconClass = 'bi-tag';
        if (type === 'formula') iconClass = 'bi-calculator';
        if (type === 'number') iconClass = 'bi-hash';
        if (type === 'date') iconClass = 'bi-calendar3';
        if (type === 'amount') iconClass = 'bi-currency-rupee';
        if (type === 'file') iconClass = 'bi-paperclip';
        if (type === 'email') iconClass = 'bi-envelope';
        if (type === 'phone') iconClass = 'bi-telephone';
        if (type === 'location') iconClass = 'bi-geo-alt';
        if (type === 'percentage') iconClass = 'bi-percent';
        if (type === 'yesno') iconClass = 'bi-toggle-on';
        if (type === 'signature') iconClass = 'bi-pencil-fill';
        
        selectIcon.className = `bi ${iconClass} select-icon`;

        if (type === 'dropdown' || type === 'status') {
            optionsSection.style.display = 'block';
            document.getElementById('formula-section').style.display = 'none';
            optionsLabel.innerText = type.charAt(0).toUpperCase() + type.slice(1) + ' Options';
            const list = document.getElementById('dropdown-options-list');
            if (list.children.length === 0) {
                addNewOption();
            }
        } else if (type === 'formula') {
            optionsSection.style.display = 'none';
            document.getElementById('formula-section').style.display = 'block';
        } else {
            optionsSection.style.display = 'none';
            document.getElementById('formula-section').style.display = 'none';
        }
    }

    function addNewOption(defaultValue = "") {
        const list = document.getElementById('dropdown-options-list');
        const index = list.children.length;
        const colors = ['#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6'];
        const color = colors[index % colors.length];
        const val = defaultValue || `Option ${index + 1}`;
        
        const div = document.createElement('div');
        div.className = 'dropdown-option-item';
        div.style.border = '1px solid #e2e8f0';
        div.style.borderRadius = '12px';
        div.style.padding = '8px';
        div.style.background = '#fff';

        div.innerHTML = `
            <div class="option-color-box" style="background: ${color}; width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: #fff;">
                <i class="bi bi-check-lg"></i>
            </div>
            <div class="option-input-wrapper" style="flex-grow: 1; position: relative; margin: 0 10px;">
                <input type="text" value="${val}" placeholder="Enter option text" 
                       style="width: 100%; border: 1px solid transparent; background: #f8fafc; padding: 8px 35px 8px 12px; border-radius: 8px; font-weight: 500; outline: none; transition: all 0.2s;">
                <i class="bi bi-check2 option-check" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #64748b;"></i>
            </div>
            <div class="remove-option-btn" onclick="this.parentElement.remove()" style="color: #94a3b8; cursor: pointer; padding: 5px;">
                <i class="bi bi-trash"></i>
            </div>
        `;
        
        // Add focus effects for the new input
        const input = div.querySelector('input');
        input.onfocus = function() {
            this.style.background = '#fff';
            this.style.borderColor = '#3b82f6';
            this.style.boxShadow = '0 0 0 3px rgba(59, 130, 246, 0.1)';
        };
        input.onblur = function() {
            this.style.background = '#f8fafc';
            this.style.borderColor = 'transparent';
            this.style.boxShadow = 'none';
        };

        list.appendChild(div);
    }

    function toggleAdvancedSettings() {
        const body = document.getElementById('advanced-settings-body');
        const chevron = document.getElementById('adv-chevron');
        if (body.style.display === 'none') {
            body.style.display = 'block';
            chevron.classList.replace('bi-chevron-down', 'bi-chevron-up');
        } else {
            body.style.display = 'none';
            chevron.classList.replace('bi-chevron-up', 'bi-chevron-down');
        }
    }

    function confirmAddColumn() {
        const type = document.getElementById('modal-col-type').value;
        const name = document.getElementById('modal-col-name').value;
        
        if (!type || !name) {
            alert("Please select a type and enter a name.");
            return;
        }

        if (editingColIdx !== null) {
            updateColumnFromModal(editingColIdx, name, type);
        } else {
            addColumnFromModal(name, type);
        }
        toggleColModal(false);
    }

    function updateColumnFromModal(idx, name, type) {
        const headerRow = document.getElementById('header-row');
        // idx+1 because 0 is checkbox
        const th = headerRow.cells[idx + 1];
        
        let options = [];
        if (type === 'dropdown' || type === 'status') {
            document.querySelectorAll('#dropdown-options-list input').forEach(input => {
                if (input.value.trim()) options.push(input.value.trim());
            });
        } else if (type === 'formula') {
            const formula = document.getElementById('modal-col-formula').value.trim();
            options = { formula: formula };
        }

        // Update TH inputs
        th.querySelector('input[name="col_name[]"]').value = name;
        th.querySelector('select[name="col_type[]"]').value = type;
        th.querySelector('input[name="col_options[]"]').value = JSON.stringify(options);

        // Update Icon
        let icon = 'bi-type';
        if (type == 'number') icon = 'bi-hash';
        if (type == 'percentage') icon = 'bi-percent';
        if (type == 'amount') icon = 'bi-currency-rupee';
        if (type == 'phone') icon = 'bi-telephone';
        if (type == 'email') icon = 'bi-envelope';
        if (type == 'location') icon = 'bi-geo-alt';
        if (type == 'date') icon = 'bi-calendar3';
        if (type == 'time') icon = 'bi-clock';
        if (type == 'dropdown') icon = 'bi-list-ul';
        if (type == 'yesno') icon = 'bi-toggle-on';
        if (type == 'status') icon = 'bi-tag';
        if (type == 'file') icon = 'bi-paperclip';
        if (type == 'label') icon = 'bi-info-circle';
        if (type == 'signature') icon = 'bi-pencil-fill';
        if (type == 'formula') icon = 'bi-calculator';
        
        const iconEl = th.querySelector('.col-icon');
        if (iconEl) iconEl.className = `bi ${icon} col-icon`;

        // Update all cells in this column
        updateCellTypes(idx, type);
        autoSave();
    }

    function addColumnFromModal(name, type) {
        const headerRow = document.getElementById('header-row');
        const colIdx = headerRow.cells.length - 2; 
        
        let options = [];
        if (type === 'dropdown' || type === 'status') {
            document.querySelectorAll('#dropdown-options-list input').forEach(input => {
                if (input.value.trim()) options.push(input.value.trim());
            });
        } else if (type === 'formula') {
            const formula = document.getElementById('modal-col-formula').value.trim();
            options = { formula: formula };
        }

        const th = document.createElement('th');
        th.style.minWidth = '200px';

        let icon = 'bi-type';
        if (type == 'number') icon = 'bi-hash';
        if (type == 'percentage') icon = 'bi-percent';
        if (type == 'amount') icon = 'bi-currency-rupee';
        if (type == 'phone') icon = 'bi-telephone';
        if (type == 'email') icon = 'bi-envelope';
        if (type == 'location') icon = 'bi-geo-alt';
        if (type == 'date') icon = 'bi-calendar3';
        if (type == 'time') icon = 'bi-clock';
        if (type == 'dropdown') icon = 'bi-list-ul';
        if (type == 'yesno') icon = 'bi-toggle-on';
        if (type == 'status') icon = 'bi-tag';
        if (type == 'file') icon = 'bi-paperclip';
        if (type == 'label') icon = 'bi-info-circle';
        if (type == 'signature') icon = 'bi-pencil-fill';
        if (type == 'formula') icon = 'bi-calculator';

        th.innerHTML = `
            <div class="col-header-content">
                <i class="bi ${icon} col-icon"></i>
                <input type="text" name="col_name[]" value="${name}" placeholder="New Column..." style="border: none; background: none; font-weight: 600; width: 100%; outline: none;">
                
                <input type="hidden" name="col_options[]" value='${JSON.stringify(options).replace(/'/g, "&apos;")}'>
                
                <div style="display: none;">
                    <select name="col_type[]" onchange="updateCellTypes(${colIdx}, this.value)">
                        <option value="text" ${type == 'text' ? 'selected' : ''}>Text</option>
                        <option value="number" ${type == 'number' ? 'selected' : ''}>Number</option>
                        <option value="percentage" ${type == 'percentage' ? 'selected' : ''}>Percentage</option>
                        <option value="amount" ${type == 'amount' ? 'selected' : ''}>Amount</option>
                        <option value="unit" ${type == 'unit' ? 'selected' : ''}>Unit</option>
                        <option value="phone" ${type == 'phone' ? 'selected' : ''}>Phone Number</option>
                        <option value="email" ${type == 'email' ? 'selected' : ''}>Email</option>
                        <option value="location" ${type == 'location' ? 'selected' : ''}>Location</option>
                        <option value="date" ${type == 'date' ? 'selected' : ''}>Date</option>
                        <option value="time" ${type == 'time' ? 'selected' : ''}>Time</option>
                        <option value="dropdown" ${type == 'dropdown' ? 'selected' : ''}>Dropdown</option>
                        <option value="yesno" ${type == 'yesno' ? 'selected' : ''}>Yes / No</option>
                        <option value="status" ${type == 'status' ? 'selected' : ''}>Status</option>
                        <option value="file" ${type == 'file' ? 'selected' : ''}>Photo & File</option>
                        <option value="label" ${type == 'label' ? 'selected' : ''}>Label</option>
                        <option value="signature" ${type == 'signature' ? 'selected' : ''}>Signature</option>
                        <option value="formula" ${type == 'formula' ? 'selected' : ''}>Formula</option>
                    </select>
                </div>
                <i class="bi bi-three-dots-vertical" style="cursor: pointer; color: var(--text-admin-muted);" onclick="toggleColMenu(event, ${colIdx})"></i>
                
                <div class="col-options-menu" id="col-menu-${colIdx}">
                    <div class="col-option-item"><i class="bi bi-dash"></i> Sort</div>
                    <div class="col-option-item" onclick="toggleColMenu(event, ${colIdx}); toggleColModal(true, ${colIdx})"><i class="bi bi-pencil"></i> Edit Column</div>
                    <div class="col-option-item"><i class="bi bi-eye-slash"></i> Hide Column</div>
                    <div class="col-option-item"><i class="bi bi-pin"></i> Freeze column</div>
                    <div class="col-option-item delete" onclick="removeColumn(${colIdx})"><i class="bi bi-trash"></i> Delete Column</div>
                </div>
            </div>
        `;
        headerRow.insertBefore(th, headerRow.lastElementChild);
        
        // Add cell to every existing row
        document.querySelectorAll('.data-row').forEach((row, r_idx) => {
            const td = document.createElement('td');
            td.innerHTML = getCellHtml(r_idx, colIdx, type, options);
            row.insertBefore(td, row.lastElementChild);
        });
        
        reindexCells();
        autoSave();
    }

    function createNewTable(folderName = null) {
        const modal = document.getElementById('table-modal');
        const folderInput = document.getElementById('modal-table-folder');
        const folderLabel = document.getElementById('target-folder-label');
        
        folderInput.value = folderName || "";
        folderLabel.innerText = folderName ? `This table will be added to the "${folderName}" folder.` : "This table will be added to the main project area.";
        
        toggleModal('table-modal', true);
    }

    function createNewFolder() {
        toggleModal('folder-modal', true);
    }

    function toggleModal(id, show) {
        const modal = document.getElementById(id);
        if (show) {
            modal.classList.add('active');
        } else {
            modal.classList.remove('active');
        }
    }
    function toggleFolderDropdown(event, folderHash) {
        event.stopPropagation();
        const menuId = `folder-menu-${folderHash}`;
        
        // Close all other folder menus
        document.querySelectorAll('.folder-dropdown-menu').forEach(menu => {
            if (menu.id !== menuId) menu.classList.remove('active');
        });

        const menu = document.getElementById(menuId);
        if (menu) menu.classList.toggle('active');
    }

    // Add to global click listener
    document.addEventListener('click', function() {
        document.querySelectorAll('.folder-dropdown-menu').forEach(menu => menu.classList.remove('active'));
    });

    function deleteFolder(folderName) {
        if (confirm(`Are you sure you want to delete the folder "${folderName}" and ALL tables inside it? This action cannot be undone.`)) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '<?= base_url('admin/delete_folder/' . $project['id']) ?>';
            
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'folder_name';
            input.value = folderName;
            
            form.appendChild(input);
            document.body.appendChild(form);
            form.submit();
        }
    }
    function toggleTableOptions(event, tableId) {
        event.stopPropagation();
        const menuId = `table-options-${tableId}`;
        
        // Close all other menus
        document.querySelectorAll('.table-options-menu').forEach(menu => {
            if (menu.id !== menuId) menu.classList.remove('active');
        });

        const menu = document.getElementById(menuId);
        if (menu) menu.classList.toggle('active');
    }

    function renameTable(id, currentName) {
        document.getElementById('rename-table-id').value = id;
        document.getElementById('rename-table-name').value = currentName;
        toggleModal('rename-modal', true);
    }

    function moveToFolder(id) {
        document.getElementById('move-table-id').value = id;
        toggleModal('move-modal', true);
    }

    function duplicateTable(id) {
        if (confirm('Duplicate this table and all its data?')) {
            window.location.href = `<?= base_url('admin/duplicate_table/' . $project['id']) ?>/${id}`;
        }
    }

    function deleteTable(id) {
        if (confirm('Delete this table and all its data?')) {
            window.location.href = `<?= base_url('admin/delete_table/' . $project['id']) ?>/${id}`;
        }
    }

    // Add global listener for table options
    document.addEventListener('click', function() {
        document.querySelectorAll('.table-options-menu').forEach(menu => menu.classList.remove('active'));
    });

    // Handle new folder input in move modal
    document.querySelector('#move-table-form select').addEventListener('change', function() {
        document.getElementById('new-folder-input-div').style.display = this.value === '__new__' ? 'block' : 'none';
    });
    function openSharing(id, tableName) {
        document.getElementById('sharing-table-title').innerText = tableName;
        toggleModal('sharing-modal', true);
    }
    function openCustomPermissions(userName) {
        document.getElementById('perm-user-title').innerText = userName;
        toggleModal('custom-perms-modal', true);
    }

    function selectQuickRole(element, role) {
        // Toggle active class
        document.querySelectorAll('.permission-card').forEach(card => card.classList.remove('active'));
        element.classList.add('active');

        // Update checkboxes based on role
        const actionChecks = document.querySelectorAll('#custom-perms-modal .action-item input');
        const columnChecks = document.querySelectorAll('#custom-perms-modal table input');
        const allActionCheck = document.querySelector('#toggle-all-actions');

        if (role === 'editor') {
            actionChecks.forEach(cb => cb.checked = true);
            columnChecks.forEach(cb => cb.checked = true);
            if (allActionCheck) allActionCheck.checked = true;
        } else if (role === 'viewer') {
            actionChecks.forEach((cb, i) => cb.checked = (i === 0)); // Only View Records
            columnChecks.forEach((cb, i) => cb.checked = (i % 3 === 0)); // Only View column
            if (allActionCheck) allActionCheck.checked = false;
        } else if (role === 'add_only') {
            actionChecks.forEach((cb, i) => cb.checked = (i === 0 || i === 1)); // View & Create
            columnChecks.forEach((cb, i) => cb.checked = (i % 3 === 0 || i % 3 === 2)); // View & Add
            if (allActionCheck) allActionCheck.checked = false;
        }
    }

    function toggleAllActions(master) {
        document.querySelectorAll('#custom-perms-modal .action-item input').forEach(cb => cb.checked = master.checked);
    }

    let currentFileTarget = null;
    function openMediaModal(wrapper) {
        currentFileTarget = wrapper;
        document.getElementById('media-upload-modal').classList.add('active');
    }

    function closeMediaModal() {
        document.getElementById('media-upload-modal').classList.remove('active');
    }

    function handleMediaSelect(input) {
        if (input.files && input.files[0] && currentFileTarget) {
            const fileInput = currentFileTarget.querySelector('input[type="file"]');
            
            // Transfer file to the specific cell's input
            const dataTransfer = new DataTransfer();
            dataTransfer.items.add(input.files[0]);
            fileInput.files = dataTransfer.files;
            
            // Capture Time and Location metadata
            captureMetadata(currentFileTarget.closest('tr'));
            
            handleFileChange(fileInput);
            closeMediaModal();
        }
    }

    function captureMetadata(row) {
        const now = new Date();
        const timeStr = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        const dateStr = now.toLocaleDateString();
        
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition((position) => {
                const lat = position.coords.latitude.toFixed(6);
                const lng = position.coords.longitude.toFixed(6);
                const locStr = `${lat}, ${lng}`;
                updateMetadataColumns(row, timeStr, locStr, dateStr);
            }, (err) => {
                console.warn("Location denied:", err);
                updateMetadataColumns(row, timeStr, "Location Denied", dateStr);
            });
        } else {
            updateMetadataColumns(row, timeStr, "GPS Not Supported", dateStr);
        }
    }

    function updateMetadataColumns(row, timeVal, locVal, dateVal) {
        const headerRow = document.getElementById('header-row');
        if (!headerRow) return;

        const headerCells = headerRow.cells;
        for (let i = 1; i < headerCells.length - 1; i++) { // Skip checkbox and action
            const th = headerCells[i];
            const nameInput = th.querySelector('input[name="col_name[]"]');
            if (nameInput) {
                const name = nameInput.value.toLowerCase();
                const cell = row.cells[i];
                const input = cell.querySelector('input, select');
                
                if (input && (!input.value || input.value === "")) {
                    if (name.includes('time')) input.value = timeVal;
                    if (name.includes('location') || name.includes('gps')) input.value = locVal;
                    if (name.includes('date')) input.value = dateVal;
                }
            }
        }
        autoSave();
    }

    let mediaRecorder;
    let audioChunks = [];

    async function toggleAudioRecording() {
        const btn = document.getElementById('audio-record-btn');
        const icon = btn.querySelector('i');
        const textNode = Array.from(btn.childNodes).find(n => n.nodeType === 3 && n.textContent.trim().includes('Record'));
        
        if (!mediaRecorder || mediaRecorder.state === "inactive") {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                mediaRecorder = new MediaRecorder(stream);
                audioChunks = [];

                mediaRecorder.ondataavailable = (event) => audioChunks.push(event.data);
                mediaRecorder.onstop = () => {
                    const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                    const audioFile = new File([audioBlob], `voice_${Date.now()}.wav`, { type: 'audio/wav' });
                    handleMediaSelect({ files: [audioFile] });
                    stream.getTracks().forEach(track => track.stop());
                };

                mediaRecorder.start();
                btn.style.background = '#ef4444';
                btn.style.color = '#fff';
                icon.className = 'bi bi-stop-circle';
                if (textNode) textNode.textContent = ' Stop recording';
            } catch (err) {
                alert("Microphone error: " + err.message);
            }
        } else {
            mediaRecorder.stop();
            btn.style.background = '#fff';
            btn.style.color = '#4285f4';
            icon.className = 'bi bi-mic';
            if (textNode) textNode.textContent = ' Record audio';
        }
    }

    let cameraStream = null;

    function startCamera() {
        const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
        
        if (isMobile) {
            // Direct camera capture for mobile
            const cameraInput = document.createElement('input');
            cameraInput.type = 'file';
            cameraInput.accept = 'image/*';
            cameraInput.capture = 'environment';
            cameraInput.onchange = function() { handleMediaSelect(this); };
            cameraInput.click();
        } else {
            // Live preview for desktop
            startCameraDesktop();
        }
    }

    async function startCameraDesktop() {
        try {
            cameraStream = await navigator.mediaDevices.getUserMedia({ video: true });
            const video = document.getElementById('camera-video');
            const container = document.getElementById('camera-preview-container');
            const controls = document.getElementById('camera-controls');
            const mainActions = document.querySelector('.media-actions');
            const cloudIcon = document.querySelector('.upload-cloud-icon');
            const title = document.querySelector('.upload-title');

            video.srcObject = cameraStream;
            container.style.display = 'block';
            controls.style.display = 'flex';
            mainActions.style.display = 'none';
            cloudIcon.style.display = 'none';
            title.style.display = 'none';
        } catch (err) {
            alert("Camera error: " + err.message);
        }
    }

    function stopCamera() {
        if (cameraStream) {
            cameraStream.getTracks().forEach(track => track.stop());
            cameraStream = null;
        }
        document.getElementById('camera-preview-container').style.display = 'none';
        document.getElementById('camera-controls').style.display = 'none';
        document.querySelector('.media-actions').style.display = 'flex';
        document.querySelector('.upload-cloud-icon').style.display = 'inline-block';
        document.querySelector('.upload-title').style.display = 'block';
    }

    function capturePhoto() {
        const video = document.getElementById('camera-video');
        const canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        
        const ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0);
        
        canvas.toBlob((blob) => {
            const photoFile = new File([blob], `photo_${Date.now()}.jpg`, { type: 'image/jpeg' });
            handleMediaSelect({ files: [photoFile] });
            stopCamera();
        }, 'image/jpeg', 0.8);
    }

    function handleFileChange(input) {
        const wrapper = input.closest('.file-cell-ui');
        const label = wrapper.querySelector('.file-name-label');
        const icon = wrapper.querySelector('.file-indicator i');
        
        if (input.files && input.files[0]) {
            const fileName = input.files[0].name;
            wrapper.classList.add('has-file');
            if (label) label.innerText = fileName;
            if (icon) icon.className = 'bi bi-check-lg';
            
            // For images, we could even show a tiny preview
            autoSave();
        }
    }

    /* Signature Pad Logic */
    let sigCanvas, sigCtx, isDrawing = false;
    let sigTargetWrapper = null;

    function openSignatureModal(wrapper) {
        sigTargetWrapper = wrapper;
        const modal = document.getElementById('signature-modal');
        modal.classList.add('active');
        
        sigCanvas = document.getElementById('signature-canvas');
        sigCtx = sigCanvas.getContext('2d');
        
        // Resize canvas to its display size
        const rect = sigCanvas.parentElement.getBoundingClientRect();
        sigCanvas.width = rect.width;
        sigCanvas.height = 300;
        
        sigCtx.strokeStyle = '#1e293b';
        sigCtx.lineWidth = 3;
        sigCtx.lineCap = 'round';
        sigCtx.lineJoin = 'round';
        
        // Mouse Events
        sigCanvas.onmousedown = (e) => {
            isDrawing = true;
            sigCtx.beginPath();
            sigCtx.moveTo(e.offsetX, e.offsetY);
        };
        sigCanvas.onmousemove = (e) => {
            if (!isDrawing) return;
            sigCtx.lineTo(e.offsetX, e.offsetY);
            sigCtx.stroke();
        };
        window.onmouseup = () => isDrawing = false;

        // Touch Events
        sigCanvas.ontouchstart = (e) => {
            e.preventDefault();
            const touch = e.touches[0];
            const rect = sigCanvas.getBoundingClientRect();
            isDrawing = true;
            sigCtx.beginPath();
            sigCtx.moveTo(touch.clientX - rect.left, touch.clientY - rect.top);
        };
        sigCanvas.ontouchmove = (e) => {
            e.preventDefault();
            if (!isDrawing) return;
            const touch = e.touches[0];
            const rect = sigCanvas.getBoundingClientRect();
            sigCtx.lineTo(touch.clientX - rect.left, touch.clientY - rect.top);
            sigCtx.stroke();
        };
        sigCanvas.ontouchend = () => isDrawing = false;
    }

    function closeSignatureModal() {
        document.getElementById('signature-modal').classList.remove('active');
        sigTargetWrapper = null;
    }

    function clearSignature() {
        if (sigCtx) {
            sigCtx.clearRect(0, 0, sigCanvas.width, sigCanvas.height);
        }
    }

    function saveSignature() {
        if (!sigCanvas || !sigTargetWrapper) return;
        
        // Check if canvas is empty (optional, but good)
        // For now just convert to blob
        sigCanvas.toBlob((blob) => {
            const signatureFile = new File([blob], `signature_${Date.now()}.png`, { type: 'image/png' });
            const fileInput = sigTargetWrapper.querySelector('input[type="file"]');
            
            const dt = new DataTransfer();
            dt.items.add(signatureFile);
            fileInput.files = dt.files;
            
            handleFileChange(fileInput);
            closeSignatureModal();
        }, 'image/png');
    }

    function showFormula(input) {
        const formula = input.getAttribute('data-formula');
        if (formula) input.value = formula;
        input.style.color = '#3498db';
    }

    function hideFormula(input) {
        if (input.value.startsWith('=')) {
            input.setAttribute('data-formula', input.value);
        }
        evaluateFormulas();
    }

    function evaluateFormulas() {
        const rows = document.querySelectorAll('.data-row');
        const headerRow = document.getElementById('header-row');
        const colNames = Array.from(headerRow.querySelectorAll('input[name="col_name[]"]')).map(i => i.value.trim());

        rows.forEach((row) => {
            const inputs = Array.from(row.querySelectorAll('input, select'));
            const rowValues = {};
            
            // Map column names to values for this row
            colNames.forEach((name, idx) => {
                const input = row.cells[idx + 1]?.querySelector('input, select');
                if (input) {
                    let val = input.value;
                    // If it's a number, amount, or percentage, treat as number
                    rowValues[name] = isNaN(parseFloat(val)) ? val : parseFloat(val);
                }
            });

            // Evaluate all formula inputs in this row
            const rowFormulaInputs = row.querySelectorAll('.formula-input');
            rowFormulaInputs.forEach(input => {
                const formula = input.getAttribute('data-formula') || input.value;
                if (formula && formula.startsWith('=')) {
                    input.setAttribute('data-formula', formula);
                    let expression = formula.substring(1);
                    
                    // Replace {Column Name} with actual values
                    Object.keys(rowValues).forEach(name => {
                        const val = rowValues[name];
                        const replacement = typeof val === 'number' ? val : `'${val}'`;
                        expression = expression.split(`{${name}}`).join(replacement);
                    });

                    try {
                        const result = new Function(`return ${expression}`)();
                        input.value = result;
                        input.style.color = '#10b981'; // Success green
                    } catch (e) {
                        console.warn("Formula error:", e);
                        input.value = "#ERROR!";
                        input.style.color = '#ef4444'; // Error red
                    }
                }
            });
        });
    }

    let autoSaveTimeout = null;
    function autoSave() {
        if (autoSaveTimeout) clearTimeout(autoSaveTimeout);
        
        const indicator = document.getElementById('save-status-indicator');
        const statusText = document.getElementById('status-text');
        const statusIcon = document.getElementById('status-icon');
        
        indicator.style.opacity = '1';
        statusText.innerText = 'Saving...';
        statusIcon.className = 'bi bi-arrow-repeat spin';
        
        autoSaveTimeout = setTimeout(() => {
            prepareData();
            const form = document.getElementById('sheet-form');
            const formData = new FormData(form);

            fetch(form.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    statusText.innerText = 'All changes saved';
                    statusIcon.className = 'bi bi-cloud-check';
                    evaluateFormulas(); // Re-evaluate formulas after save to ensure sync
                    setTimeout(() => { indicator.style.opacity = '0'; }, 2000);
                    
                    if (data.sheet_id && !form.action.includes(data.sheet_id)) {
                        const baseUrl = '<?= base_url('admin/save_sheet/' . $project['id']) ?>';
                        form.action = baseUrl + '/' + data.sheet_id;
                    }
                }
            })
            .catch(error => {
                console.error('Auto-save error:', error);
                statusText.innerText = 'Save failed. Retrying...';
                statusIcon.className = 'bi bi-exclamation-triangle';
            });
        }, 1000);
    }

    function prepareData() {
        const rows = document.querySelectorAll('.data-row');
        const sheetData = [];
        const cols = document.getElementsByName('col_type[]');

        rows.forEach((row, r_idx) => {
            const rowData = [];
            for (let c_idx = 0; c_idx < row.cells.length - 2; c_idx++) {
                const cell = row.cells[c_idx + 1];
                const input = cell.querySelector('input, select');
                if (input) {
                    rowData.push(input.value);
                } else {
                    rowData.push("");
                }
            }
            sheetData.push(rowData);
        });

        document.getElementById('json_data').value = JSON.stringify(sheetData);
    }

    // Initialize indexing on page load
    document.addEventListener('DOMContentLoaded', function() {
        reindexCells();
        evaluateFormulas();
    });

    function viewRecordDetails(idx) {
        const body = document.getElementById('sheet-body');
        const row = body.rows[idx];
        const cols = document.getElementsByName('col_name[]');
        const container = document.getElementById('details-modal-body');
        
        let html = `
            <div style="margin-bottom: 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 2px solid #e2e8f0; padding-bottom: 15px;">
                <div style="font-size: 1.1rem; font-weight: 700; color: #1e293b;">
                    <span style="color: var(--primary);">#</span> Record Index: ${idx + 1}
                </div>
                <div style="font-size: 0.85rem; color: #64748b; font-weight: 500;">
                    <i class="bi bi-clock-history"></i> Real-time Snapshot
                </div>
            </div>
            <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px;">
        `;
             for (let i = 0; i < cols.length; i++) {
            const name = cols[i].value || `Column ${i+1}`;
            const cell = row.cells[i+1];
            const input = cell.querySelector('input, select');
            let value = input ? input.value : '';
            
            let displayValue = value;
            let isEmpty = !value || value.trim() === '';
            
            if (isEmpty) {
                displayValue = '<span style="color: #cbd5e1; font-style: italic; font-weight: 400;">No data entered</span>';
            } else {
                // Better Image/File detection
                const lowerName = name.toLowerCase();
                const lowerVal = value.toLowerCase();
                const isImagePath = lowerVal.startsWith('http') || lowerVal.includes('uploads/');
                const isImageExt = lowerVal.endsWith('.jpg') || lowerVal.endsWith('.jpeg') || lowerVal.endsWith('.png') || lowerVal.endsWith('.gif') || lowerVal.endsWith('.webp');
                
                if (isImagePath || isImageExt || lowerName.includes('image') || lowerName.includes('photo') || lowerName.includes('signature') || lowerName.includes('sign')) {
                    displayValue = `
                        <div style="margin-top: 5px;">
                            <img src="${value}" style="max-width: 100%; max-height: 250px; object-fit: contain; border-radius: 8px; border: 1px solid #e2e8f0; background: #fff;" onerror="this.parentElement.innerHTML='<a href=\'${value}\' target=\'_blank\' style=\'color: var(--primary); text-decoration: underline; font-size: 0.85rem;\'><i class=\'bi bi-file-earmark\'></i> View Attachment</a>'">
                        </div>
                    `;
                }
            }
            
            html += `
                <div style="background: #fff; border: 1px solid ${isEmpty ? '#f1f5f9' : '#e2e8f0'}; border-radius: 12px; padding: 20px; box-shadow: ${isEmpty ? 'none' : '0 4px 6px -1px rgba(0, 0, 0, 0.05)'}; display: flex; flex-direction: column;">
                    <label style="display: block; font-size: 0.7rem; font-weight: 800; color: ${isEmpty ? '#cbd5e1' : '#94a3b8'}; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 10px;">${name}</label>
                    <div style="font-size: 1rem; font-weight: ${isEmpty ? '400' : '600'}; color: ${isEmpty ? '#94a3b8' : '#1e293b'}; word-break: break-all; flex-grow: 1;">${displayValue}</div>
                </div>
            `;
        }
        html += '</div>';
        container.innerHTML = html;
        toggleModal('details-modal', true);
    }

    function toggleSelectAll(master) {
        const checkboxes = document.querySelectorAll('.row-checkbox');
        checkboxes.forEach(cb => {
            cb.checked = master.checked;
        });
    }

    function shareRecordAsText(idx) {
        const body = document.getElementById('sheet-body');
        const row = body.rows[idx];
        const cols = document.getElementsByName('col_name[]');
        
        let text = "RECORD DETAILS\n==============\n";
        for (let i = 0; i < cols.length; i++) {
            const name = cols[i].value || `Column ${i+1}`;
            const cell = row.cells[i+1];
            const input = cell.querySelector('input, select');
            const value = input ? input.value : '';
            text += `${name}: ${value}\n`;
        }
        
        navigator.clipboard.writeText(text).then(() => {
            alert("Record data copied to clipboard!");
        });
    }

    function downloadRecordPDF(idx) {
        const body = document.getElementById('sheet-body');
        const row = body.rows[idx];
        const cols = document.getElementsByName('col_name[]');
        const tableName = "<?= $table_name ?>";
        const today = new Date();
        const timestamp = today.toLocaleString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
        const monthYear = today.toLocaleString('en-IN', { month: 'short' }).toUpperCase();
        
        let printContent = `
            <html>
            <head>
                <title>Record Report - Saanvi Infratech</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
                <style>
                    @page { size: A4; margin: 0; }
                    body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; padding: 0; background: #fff; color: #333; }
                    .header { background: #b91c1c; color: #fff; padding: 30px 40px; display: flex; justify-content: space-between; align-items: center; position: relative; }
                    .logo-section { display: flex; align-items: center; gap: 15px; }
                    .logo-box { background: #fff; padding: 8px; border-radius: 8px; width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; }
                    .logo-box img { max-width: 100%; max-height: 100%; }
                    .company-name { font-size: 1.4rem; font-weight: 800; }
                    .gen-date { font-size: 0.75rem; opacity: 0.8; }
                    .month-label { text-align: right; }
                    .month-text { font-size: 1.2rem; font-weight: 800; letter-spacing: 2px; }
                    .record-book { font-size: 0.9rem; font-weight: 600; display: flex; align-items: center; gap: 8px; margin-top: 5px; }
                    
                    .main-content { padding: 50px 60px; position: relative; min-height: 800px; }
                    .watermark { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(-30deg); width: 450px; opacity: 0.04; pointer-events: none; z-index: -1; display: flex; align-items: center; justify-content: center; }
                    .watermark img { width: 100%; height: auto; filter: grayscale(100%); }
                    
                    .section-divider { border-bottom: 1px solid #e2e8f0; margin-bottom: 25px; display: flex; align-items: center; gap: 10px; width: 100%; }
                    .section-dot { width: 40px; height: 3px; background: #b91c1c; }
                    .section-title { font-size: 0.85rem; font-weight: 800; color: #1e293b; text-transform: uppercase; letter-spacing: 1px; }
                    
                    table { width: 100%; border-collapse: collapse; border: 1px solid #e2e8f0; }
                    th { background: #b91c1c; color: #fff; text-align: left; padding: 15px 20px; font-size: 0.8rem; text-transform: uppercase; letter-spacing: 1px; font-weight: 800; }
                    td { padding: 14px 20px; border-bottom: 1px solid #e2e8f0; font-size: 0.95rem; }
                    .col-name { font-weight: 800; color: #b91c1c; width: 35%; background: #f8fafc; border-right: 1px solid #e2e8f0; }
                    .col-val { font-weight: 600; color: #334155; background: #fff; }
                    
                    .footer { position: fixed; bottom: 0; width: 100%; background: #b91c1c; color: #fff; padding: 12px 40px; display: flex; justify-content: space-between; font-size: 0.75rem; font-weight: 600; }
                </style>
            </head>
            <body>
                <div class="header">
                    <div class="logo-section">
                        <div class="logo-box">
                            <img src="<?= $siteLogo ?: 'https://via.placeholder.com/60' ?>" alt="Logo">
                        </div>
                        <div>
                            <div class="company-name">Saanvi Infratech</div>
                            <div class="gen-date">Generated: ${timestamp}</div>
                        </div>
                    </div>
                    <div class="month-label">
                        <div class="month-text">${monthYear}</div>
                        <div class="record-book"><i class="bi bi-journal-bookmark-fill"></i> RecordBook</div>
                    </div>
                </div>
                
                <div class="main-content">
                    <div class="watermark">
                        <img src="<?= $siteLogo ?: 'https://via.placeholder.com/450' ?>" alt="Watermark">
                    </div>
                    
                    <div class="section-divider">
                        <div class="section-dot"></div>
                        <div class="section-title">COLUMN NAME</div>
                    </div>
                    
                    <table>
                        <thead>
                            <tr>
                                <th>COLUMN NAME</th>
                                <th>DETAILS</th>
                            </tr>
                        </thead>
                        <tbody>
        `;
        
        for (let i = 0; i < cols.length; i++) {
            const name = cols[i].value || `Column ${i+1}`;
            const cell = row.cells[i+1];
            const input = cell.querySelector('input, select');
            const value = input ? input.value : '';
            
            // Skip empty fields
            if (!value || value.trim() === '') continue;

            let displayValue = value;
            
            // Detect if this is an image path
            if (name.toLowerCase().includes('image') && value && (value.startsWith('http') || value.includes('uploads/'))) {
                displayValue = `<img src="${value}" style="max-width: 300px; max-height: 200px; border-radius: 4px; border: 1px solid #e2e8f0;">`;
            }
            
            printContent += `
                <tr>
                    <td class="col-name">${name}</td>
                    <td class="col-val">${displayValue}</td>
                </tr>
            `;
        }
        
        printContent += `
                        </tbody>
                    </table>
                </div>
                
                <div class="footer">
                    <div>Page 1 of 1</div>
                    <div>Generated using RecordBook at ${timestamp}</div>
                </div>
                
                <script>
                    window.onload = function() { window.print(); window.close(); }
                <\/script>
            </body>
            </html>
        `;
        
        const printWindow = window.open('', '_blank');
        printWindow.document.open();
        printWindow.document.write(printContent);
        printWindow.document.close();
    }
</script>

<?= $this->endSection() ?>
