<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <title>Companies - TyreCare 360</title>
    <link rel="stylesheet" href="<?= ($ASSET_PATH) ?>/css/variables.css">
    <link rel="stylesheet" href="<?= ($ASSET_PATH) ?>/css/base.css">
    <link rel="stylesheet" href="<?= ($ASSET_PATH) ?>/css/layout.css">
    <link rel="stylesheet" href="<?= ($ASSET_PATH) ?>/css/components.css">
    <link rel="stylesheet" href="<?= ($ASSET_PATH) ?>/css/mobile.css">
    <style>
/* =====================================================
   ANIMATIONS (UNCHANGED)
===================================================== */

@keyframes fadeInUp {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}
@keyframes slideIn {
    from { opacity: 0; transform: translateX(-10px); }
    to { opacity: 1; transform: translateX(0); }
}
@keyframes scaleIn {
    from { opacity: 0; transform: scale(0.95); }
    to { opacity: 1; transform: scale(1); }
}
@keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

.content-area { animation: fadeInUp 0.5s ease-out; }

/* =====================================================
   BASE UI (UNCHANGED)
===================================================== */

.card {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.card:hover {
    box-shadow: 0 8px 30px rgba(124, 58, 237, 0.12);
}

.data-table tbody tr {
    transition: all 0.2s ease;
}
.data-table tbody tr:hover {
    background: rgba(124, 58, 237, 0.04);
}

.action-buttons {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
}
.action-buttons .btn {
    transition: all 0.2s ease;
}
.action-buttons .btn:hover {
    transform: translateY(-2px);
}

.header-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.btn-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    padding: 0;
    border-radius: 8px;
}

.btn-view { background: #dbeafe; color: #2563eb; }
.btn-edit { background: #fef3c7; color: #d97706; }
.btn-delete { background: #fee2e2; color: #dc2626; }
.btn-refresh { background: #d1fae5; color: #059669; }
.btn-export { background: #ede9fe; color: #7c3aed; }

.spinning { animation: spin 0.5s linear; }

.text-success { color: #059669; }
.text-warning { color: #d97706; }
.text-danger { color: #dc2626; }

/* =====================================================
   TOGGLE SWITCH (UNCHANGED)
===================================================== */

.toggle-switch {
    position: relative;
    display: inline-block;
    width: 48px;
    height: 26px;
}
.toggle-switch input { display: none; }

.toggle-slider {
    position: absolute;
    inset: 0;
    background: #e5e7eb;
    border-radius: 26px;
    transition: 0.3s;
}
.toggle-slider:before {
    content: "";
    position: absolute;
    height: 20px;
    width: 20px;
    left: 3px;
    bottom: 3px;
    background: #fff;
    border-radius: 50%;
    transition: 0.3s;
}
.toggle-switch input:checked + .toggle-slider {
    background: #22c55e;
}
.toggle-switch input:checked + .toggle-slider:before {
    transform: translateX(22px);
}

/* =====================================================
   MOBILE CARD BASE
===================================================== */

.mobile-card {
    display: none;
}

.mobile-card-item {
    background: #fff;
    border-radius: 12px;
    padding: 14px;
    margin-bottom: 14px;
    box-shadow: 0 1px 4px rgba(0,0,0,0.1);
}

.mobile-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 10px;
    border-bottom: 1px solid #f3f4f6;
}

.mobile-card-title {
    font-weight: 600;
    font-size: 1rem;
}

.mobile-card-row {
    display: flex;
    justify-content: space-between;
    padding: 6px 0;
    font-size: 0.9rem;
}

.mobile-card-label {
    color: #6b7280;
}

.mobile-card-actions {
    display: flex;
    gap: 8px;
    margin-top: 10px;
}

/* =====================================================
   🔥 MOBILE RESPONSIVE – FINAL FIX
===================================================== */

@media (max-width: 768px) {

    /* GLOBAL RESET */
    html, body {
        width: 100%;
        max-width: 100%;
        overflow-x: hidden !important;
    }

    /* CONTAINER FIX */
    .app-container {
        width: 100% !important;
        max-width: 100% !important;
        overflow-x: hidden !important;
        display: block !important;
    }

    .main-content {
        width: 100% !important;
        max-width: 100% !important;
        padding: 0 !important;
        margin: 0 !important;
        display: block !important;
    }

    /* HEADER */
    .header {
        width: 100% !important;
        padding: 12px 16px !important;
        margin: 0 !important;
    }

    .header-actions .btn span {
        display: none;
    }

    /* CONTENT AREA (KEY FIX) */
    .content-area {
        width: 100% !important;
        max-width: 100% !important;
        padding: 12px !important;
        margin: 0 !important;
        display: block !important;
        box-sizing: border-box;
    }

    /* CARD */
    .card {
        width: 100% !important;
        margin: 0 !important;
        padding: 0 !important;
    }

    /* DESKTOP TABLE OFF */
    .table-wrapper,
    table.data-table {
        display: none !important;
    }

    /* MOBILE CARD ON */
    .mobile-card {
        display: block !important;
        width: 100% !important;
    }

    .mobile-card-item {
        width: 100% !important;
        margin-left: 0 !important;
        margin-right: 0 !important;
    }

    /* MODALS */
    .modal-overlay {
        padding: 10px !important;
        align-items: flex-start !important;
    }

    .modal {
        width: 100% !important;
        max-width: 100% !important;
        max-height: 95vh !important;
        overflow-y: auto !important;
    }

    .modal-footer {
        flex-direction: column;
        gap: 10px;
    }

    .modal-footer .btn {
        width: 100%;
    }
}
</style>

</head>
<body>
    <div class="app-container">
        <div class="sidebar-overlay" onclick="closeSidebar()"></div>
        <?php echo $this->render('super-admin/_sidebar.html',NULL,get_defined_vars(),0); ?>
        
        <main class="main-content">
            <header class="header">
                <div class="header-left">
                    <button class="menu-toggle" onclick="toggleSidebar()">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
                        </svg>
                    </button>
                    <h1 class="page-title">Companies</h1>
                </div>
                <div class="header-actions">
                    <button class="btn btn-secondary" onclick="refreshData()" id="refresh-btn">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                        </svg>
                        <span>Refresh</span>
                    </button>
                    <button class="btn btn-secondary" onclick="exportData()">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                        <span>Export</span>
                    </button>
                    <button class="btn btn-primary" onclick="openAddModal()">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                        </svg>
                        <span>Add Company</span>
                    </button>
                </div>
            </header>
            
            <div class="content-area">
                <div class="card" style="padding: 0; overflow: hidden;">
                    <div class="table-wrapper">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Company</th>
                                    <th>Owner</th>
                                    <th>Contact</th>
                                    <th>Joined Date</th>
                                    <th>Expiry Date</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach (($companies?:[]) as $company): ?>
                                    <tr data-id="<?= ($company['id']) ?>">
                                        <td>
                                            <div style="font-weight: 600;"><?= ($company['name']) ?></div>
                                            <div style="font-size: 12px; color: var(--text-muted);"><?= ($company['email']) ?></div>
                                        </td>
                                        <td><?= ($company['owner_name'] ? $company['owner_name'] : '-') ?></td>
                                        <td><?= ($company['phone'] ? $company['phone'] : '-') ?></td>
                                        <td class="date-cell">
                                            <span class="date-value"><?= ($company['joined_date'] ? date('M d, Y', strtotime($company['joined_date'])) : ($company['created_at'] ? date('M d, Y', strtotime($company['created_at'])) : '-')) ?></span>
                                        </td>
                                        <td class="date-cell">
                                            <?php if ($company['subscription_expiry']): ?>
                                                
                                                    <span class="date-value <?= (strtotime($company['subscription_expiry']) < time() ? 'text-danger' : (strtotime($company['subscription_expiry']) < strtotime('+30 days') ? 'text-warning' : 'text-success')) ?>">
                                                        <?= (date('M d, Y', strtotime($company['subscription_expiry'])))."
" ?>
                                                    </span>
                                                
                                                <?php else: ?><span class="text-muted">Not Set</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <label class="toggle-switch" title="Click to toggle active status">
                                                <input type="checkbox" onchange="toggleCompanyStatus(<?= ($company['id']) ?>, this.checked)" <?= ($company['is_active'] ? 'checked' : '') ?>>
                                                <span class="toggle-slider"></span>
                                            </label>
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <button class="btn btn-icon btn-view" onclick="viewCompany(<?= ($company['id']) ?>)" title="View">
                                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                                    </svg>
                                                </button>
                                                <button class="btn btn-icon btn-edit" onclick="openEditModal(<?= ($company['id']) ?>)" title="Edit">
                                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                    </svg>
                                                </button>
                                                <button class="btn btn-icon btn-delete" onclick="deleteCompany(<?= ($company['id']) ?>)" title="Delete">
                                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                    </svg>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <div class="mobile-card">
                    <?php foreach (($companies?:[]) as $company): ?>
                        <div class="mobile-card-item" data-id="<?= ($company['id']) ?>">
                            <div class="mobile-card-header">
                                <div class="mobile-card-title"><?= ($company['name']) ?></div>
                                <label class="toggle-switch" title="Click to toggle active status">
                                    <input type="checkbox" onchange="toggleCompanyStatus(<?= ($company['id']) ?>, this.checked)" <?= ($company['is_active'] ? 'checked' : '') ?>>
                                    <span class="toggle-slider"></span>
                                </label>
                            </div>
                            <div class="mobile-card-row">
                                <span class="mobile-card-label">Owner</span>
                                <span class="mobile-card-value"><?= ($company['owner_name'] ? $company['owner_name'] : '-') ?></span>
                            </div>
                            <div class="mobile-card-row">
                                <span class="mobile-card-label">Contact</span>
                                <span class="mobile-card-value"><?= ($company['phone'] ? $company['phone'] : '-') ?></span>
                            </div>
                            <div class="mobile-card-row">
                                <span class="mobile-card-label">Joined</span>
                                <span class="mobile-card-value"><?= ($company['joined_date'] ? date('M d, Y', strtotime($company['joined_date'])) : ($company['created_at'] ? date('M d, Y', strtotime($company['created_at'])) : '-')) ?></span>
                            </div>
                            <div class="mobile-card-row">
                                <span class="mobile-card-label">Expiry</span>
                                <span class="mobile-card-value <?= ($company['subscription_expiry'] && strtotime($company['subscription_expiry']) < time() ? 'text-danger' : '') ?>">
                                    <?= ($company['subscription_expiry'] ? date('M d, Y', strtotime($company['subscription_expiry'])) : 'Not Set')."
" ?>
                                </span>
                            </div>
                            <div class="mobile-card-actions">
                                <button class="btn btn-icon btn-view" onclick="viewCompany(<?= ($company['id']) ?>)" title="View">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                    </svg>
                                </button>
                                <button class="btn btn-icon btn-edit" onclick="openEditModal(<?= ($company['id']) ?>)" title="Edit">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                    </svg>
                                </button>
                                <button class="btn btn-icon btn-delete" onclick="deleteCompany(<?= ($company['id']) ?>)" title="Delete">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                    </svg>
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </main>
    </div>
    
    <div id="add-company-modal" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h3 class="modal-title">Add New Company</h3>
                <button class="modal-close" onclick="closeModal('add-company-modal')">&times;</button>
            </div>
            <form id="add-company-form">
                <div class="modal-body">
                    <div class="form-group">
                        <label class="form-label">Company Name *</label>
                        <input type="text" name="name" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Company Email *</label>
                        <input type="email" name="email" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Phone Number</label>
                        <input type="tel" name="phone" class="form-input">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Address</label>
                        <textarea name="address" class="form-input" rows="2"></textarea>
                    </div>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div class="form-group">
                            <label class="form-label">Joined Date</label>
                            <input type="date" name="joined_date" class="form-input">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Expiry Date</label>
                            <input type="date" name="subscription_expiry" class="form-input">
                        </div>
                    </div>
                    <hr style="margin: 20px 0; border: none; border-top: 1px solid #e5e7eb;">
                    <h4 style="margin-bottom: 16px; color: #374151;">Company Admin Login Credentials</h4>
                    <div class="form-group">
                        <label class="form-label">Admin Name *</label>
                        <input type="text" name="admin_name" class="form-input" required placeholder="e.g. John Smith">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Admin Email (Login) *</label>
                        <input type="email" name="admin_email" class="form-input" required placeholder="e.g. john@company.com">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Admin Password *</label>
                        <input type="password" name="admin_password" class="form-input" required placeholder="Enter password" minlength="6">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('add-company-modal')">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="add-company-btn">Create Company</button>
                </div>
            </form>
        </div>
    </div>
    
    <div id="edit-company-modal" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h3 class="modal-title">Edit Company</h3>
                <button class="modal-close" onclick="closeModal('edit-company-modal')">&times;</button>
            </div>
            <form id="edit-company-form">
                <input type="hidden" name="id" id="edit-company-id">
                <div class="modal-body">
                    <div class="form-group">
                        <label class="form-label">Company Name *</label>
                        <input type="text" name="name" id="edit-company-name" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Company Email *</label>
                        <input type="email" name="email" id="edit-company-email" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Phone Number</label>
                        <input type="tel" name="phone" id="edit-company-phone" class="form-input">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Address</label>
                        <textarea name="address" id="edit-company-address" class="form-input" rows="2"></textarea>
                    </div>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div class="form-group">
                            <label class="form-label">Joined Date</label>
                            <input type="date" name="joined_date" id="edit-company-joined" class="form-input">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Expiry Date</label>
                            <input type="date" name="subscription_expiry" id="edit-company-expiry" class="form-input">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('edit-company-modal')">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
    
    <div id="view-company-modal" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h3 class="modal-title">Company Details</h3>
                <button class="modal-close" onclick="closeModal('view-company-modal')">&times;</button>
            </div>
            <div class="modal-body" id="view-company-content">
                <div style="text-align: center; padding: 40px;">Loading...</div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal('view-company-modal')">Close</button>
            </div>
        </div>
    </div>
    
    <div class="toast-container" id="toast-container"></div>
    
    <script>
        const BASE_PATH = '<?= ($BASE_PATH) ?>';
        
        function toggleSidebar() {
            document.querySelector('.sidebar').classList.toggle('open');
            document.querySelector('.sidebar-overlay').classList.toggle('open');
        }
        
        function closeSidebar() {
            document.querySelector('.sidebar').classList.remove('open');
            document.querySelector('.sidebar-overlay').classList.remove('open');
        }
        
        function openAddModal() {
            document.getElementById('add-company-form').reset();
            document.getElementById('add-company-modal').classList.add('active');
        }
        
        async function openEditModal(id) {
            document.getElementById('edit-company-modal').classList.add('active');
            try {
                const response = await fetch(BASE_PATH + '/api/companies/' + id);
                const data = await response.json();
                if (data.success && data.company) {
                    const c = data.company;
                    document.getElementById('edit-company-id').value = c.id;
                    document.getElementById('edit-company-name').value = c.name || '';
                    document.getElementById('edit-company-email').value = c.email || '';
                    document.getElementById('edit-company-phone').value = c.phone || '';
                    document.getElementById('edit-company-address').value = c.address || '';
                    document.getElementById('edit-company-joined').value = c.joined_date ? c.joined_date.split('T')[0] : '';
                    document.getElementById('edit-company-expiry').value = c.subscription_expiry || '';
                }
            } catch (error) {
                console.error('Error fetching company:', error);
            }
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).classList.remove('active');
        }
        
        function showToast(message, type = 'info') {
            const container = document.getElementById('toast-container');
            const toast = document.createElement('div');
            toast.className = 'toast ' + type;
            toast.textContent = message;
            toast.style.animation = 'fadeInUp 0.3s ease-out';
            container.appendChild(toast);
            setTimeout(() => {
                toast.style.animation = 'fadeInUp 0.3s ease-out reverse';
                setTimeout(() => toast.remove(), 300);
            }, 3000);
        }
        
        function refreshData() {
            const btn = document.getElementById('refresh-btn');
            const svg = btn.querySelector('svg');
            svg.classList.add('spinning');
            setTimeout(() => {
                location.reload();
            }, 500);
        }
        
        function exportData() {
            const companies = [];
            document.querySelectorAll('.data-table tbody tr').forEach(row => {
                const cells = row.querySelectorAll('td');
                if (cells.length > 0) {
                    companies.push({
                        company: cells[0].textContent.trim(),
                        owner: cells[1].textContent.trim(),
                        contact: cells[2].textContent.trim(),
                        joined: cells[3].textContent.trim(),
                        expiry: cells[4].textContent.trim(),
                        status: cells[5].textContent.trim()
                    });
                }
            });
            
            let csv = 'Company,Owner,Contact,Joined Date,Expiry Date,Status\n';
            companies.forEach(c => {
                csv += `"${c.company}","${c.owner}","${c.contact}","${c.joined}","${c.expiry}","${c.status}"\n`;
            });
            
            const blob = new Blob([csv], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'companies_' + new Date().toISOString().split('T')[0] + '.csv';
            a.click();
            window.URL.revokeObjectURL(url);
            showToast('Data exported successfully', 'success');
        }
        
        async function viewCompany(id) {
            document.getElementById('view-company-modal').classList.add('active');
            document.getElementById('view-company-content').innerHTML = '<div style="text-align: center; padding: 40px;">Loading...</div>';
            
            try {
                const response = await fetch(BASE_PATH + '/api/companies/' + id);
                const data = await response.json();
                
                if (data.success && data.company) {
                    const c = data.company;
                    document.getElementById('view-company-content').innerHTML = `
                        <div style="display: grid; gap: 16px;">
                            <div style="display: flex; justify-content: space-between; padding: 12px; background: #f9fafb; border-radius: 8px;">
                                <span style="color: #6b7280;">Company Name</span>
                                <span style="font-weight: 600;">${c.name || '-'}</span>
                            </div>
                            <div style="display: flex; justify-content: space-between; padding: 12px; background: #f9fafb; border-radius: 8px;">
                                <span style="color: #6b7280;">Email</span>
                                <span style="font-weight: 500;">${c.email || '-'}</span>
                            </div>
                            <div style="display: flex; justify-content: space-between; padding: 12px; background: #f9fafb; border-radius: 8px;">
                                <span style="color: #6b7280;">Phone</span>
                                <span style="font-weight: 500;">${c.phone || '-'}</span>
                            </div>
                            <div style="display: flex; justify-content: space-between; padding: 12px; background: #f9fafb; border-radius: 8px;">
                                <span style="color: #6b7280;">Address</span>
                                <span style="font-weight: 500;">${c.address || '-'}</span>
                            </div>
                            <div style="display: flex; justify-content: space-between; padding: 12px; background: #f9fafb; border-radius: 8px;">
                                <span style="color: #6b7280;">Status</span>
                                <span class="badge ${c.is_active ? 'badge-success' : 'badge-danger'}">${c.is_active ? 'Active' : 'Inactive'}</span>
                            </div>
                            <div style="display: flex; justify-content: space-between; padding: 12px; background: #f9fafb; border-radius: 8px;">
                                <span style="color: #6b7280;">Joined Date</span>
                                <span style="font-weight: 500;">${c.joined_date || c.created_at || '-'}</span>
                            </div>
                            <div style="display: flex; justify-content: space-between; padding: 12px; background: #f9fafb; border-radius: 8px;">
                                <span style="color: #6b7280;">Expiry Date</span>
                                <span style="font-weight: 500;">${c.subscription_expiry || 'Not Set'}</span>
                            </div>
                        </div>
                    `;
                } else {
                    document.getElementById('view-company-content').innerHTML = '<div style="text-align: center; padding: 40px; color: #dc2626;">Failed to load company details</div>';
                }
            } catch (error) {
                document.getElementById('view-company-content').innerHTML = '<div style="text-align: center; padding: 40px; color: #dc2626;">Error loading company details</div>';
            }
        }
        
        document.getElementById('add-company-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const btn = document.getElementById('add-company-btn');
            btn.disabled = true;
            btn.textContent = 'Creating...';
            
            const formData = new FormData(this);
            const data = Object.fromEntries(formData);
            
            try {
                const response = await fetch(BASE_PATH + '/api/companies', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });
                const result = await response.json();
                
                if (result.success) {
                    showToast('Company created successfully', 'success');
                    closeModal('add-company-modal');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(result.message || 'Failed to create company', 'error');
                    btn.disabled = false;
                    btn.textContent = 'Create Company';
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('Failed to create company', 'error');
                btn.disabled = false;
                btn.textContent = 'Create Company';
            }
        });
        
        document.getElementById('edit-company-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const id = document.getElementById('edit-company-id').value;
            const formData = new FormData(this);
            const data = Object.fromEntries(formData);
            
            try {
                const response = await fetch(BASE_PATH + '/api/companies/' + id, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });
                const result = await response.json();
                
                if (result.success) {
                    showToast('Company updated successfully', 'success');
                    closeModal('edit-company-modal');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(result.message || 'Failed to update company', 'error');
                }
            } catch (error) {
                showToast('Failed to update company', 'error');
            }
        });
        
        async function toggleCompanyStatus(id, isActive) {
            try {
                const response = await fetch(BASE_PATH + '/api/companies/' + id + '/toggle', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ is_active: isActive })
                });
                const result = await response.json();
                
                if (result.success) {
                    showToast('Company status updated', 'success');
                } else {
                    showToast(result.message || 'Failed to update status', 'error');
                    event.target.checked = !isActive;
                }
            } catch (error) {
                showToast('Failed to update status', 'error');
                event.target.checked = !isActive;
            }
        }
        
        async function deleteCompany(id) {
            if (!confirm('Are you sure you want to delete this company? This action cannot be undone.')) {
                return;
            }
            
            try {
                const response = await fetch(BASE_PATH + '/api/companies/' + id, {
                    method: 'DELETE',
                    headers: { 'Content-Type': 'application/json' }
                });
                const result = await response.json();
                
                if (result.success) {
                    showToast('Company deleted successfully', 'success');
                    const row = document.querySelector('tr[data-id="' + id + '"]');
                    const card = document.querySelector('.mobile-card-item[data-id="' + id + '"]');
                    if (row) {
                        row.style.animation = 'fadeInUp 0.3s ease-out reverse';
                        setTimeout(() => row.remove(), 300);
                    }
                    if (card) {
                        card.style.animation = 'fadeInUp 0.3s ease-out reverse';
                        setTimeout(() => card.remove(), 300);
                    }
                } else {
                    showToast(result.message || 'Failed to delete company', 'error');
                }
            } catch (error) {
                showToast('Failed to delete company', 'error');
            }
        }
        
        document.querySelectorAll('.modal-overlay').forEach(modal => {
            modal.addEventListener('click', function(e) {
                if (e.target === this) {
                    this.classList.remove('active');
                }
            });
        });
    </script>
</body>
</html>
