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

<?= $this->section('content') ?>
<h2 class="mb-4">Settings</h2>

<div class="row">
    <div class="col-md-6">
        <div class="card mb-4">
            <div class="card-header"><h5 class="mb-0">Manage License Key</h5></div>
            <div class="card-body">
                <form action="/admin/settings/update-license" method="post">
                    <div class="mb-3">
                        <label class="form-label">License Key</label>
                        <div class="input-group">
                            <input type="text" name="license_key" id="licenseKey" class="form-control" 
                                   value="<?= esc($settings['license_key']) ?>" placeholder="Enter 16-digit license key">
                            <button type="button" class="btn btn-outline-secondary" id="validateBtn">Validate</button>
                        </div>
                    </div>
                    
                    <?php if($licenseInfo): ?>
                    <div id="licenseDetails" class="border rounded p-3 bg-light">
                        <table class="table table-borderless table-sm mb-0">
                            <tr><th>Assigned To:</th><td><?= esc($licenseInfo['assigned_to']) ?></td></tr>
                            <tr><th>Status:</th><td><span class="badge bg-<?= $licenseInfo['status'] == 'Valid' ? 'success' : 'danger' ?>"><?= esc($licenseInfo['status']) ?></span></td></tr>
                            <tr><th>Default URL:</th><td><?= esc($licenseInfo['default_url']) ?: '-' ?></td></tr>
                            <tr><th>Seats Limit:</th><td><?= $licenseInfo['seats_limit'] == -1 ? 'Unlimited' : $licenseInfo['seats_limit'] ?></td></tr>
                            <tr><th>Current Usage:</th><td><?= $licenseInfo['current_limit_used'] ?></td></tr>
                            <tr><th>Valid From:</th><td><?= $licenseInfo['valid_from'] ? date('M d, Y', strtotime($licenseInfo['valid_from'])) : '-' ?></td></tr>
                            <tr><th>Valid To:</th><td><?= $licenseInfo['valid_to'] ? date('M d, Y', strtotime($licenseInfo['valid_to'])) : '-' ?></td></tr>
                        </table>
                    </div>
                    <?php else: ?>
                    <div id="licenseDetails"></div>
                    <?php endif; ?>
                    
                    <button type="submit" class="btn btn-primary mt-3">Save License Key</button>
                </form>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header"><h5 class="mb-0">Application Settings</h5></div>
            <div class="card-body">
                <form action="/admin/settings/update" method="post">
                    <div class="mb-3">
                        <label class="form-label">Allow Login</label>
                        <div class="form-check form-switch">
                            <input type="checkbox" name="allow_login" value="yes" class="form-check-input" id="allowLogin" <?= $settings['allow_login'] ? 'checked' : '' ?>>
                            <label class="form-check-label" for="allowLogin">Show login screen to users</label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Camera Detection</label>
                        <div class="form-check form-switch">
                            <input type="checkbox" name="camera_detection" value="yes" class="form-check-input" id="cameraDetection" <?= $settings['camera_detection'] ? 'checked' : '' ?>>
                            <label class="form-check-label" for="cameraDetection">Detect Camera</label>
                        </div>
                    </div>
                    
                    <div class="mb-3" id="personDetectionGroup">
                        <label class="form-label">Person Detection</label>
                        <div class="form-check form-switch">
                            <input type="checkbox" name="person_detection" value="yes" class="form-check-input" id="personDetection" <?= $settings['person_detection'] ? 'checked' : '' ?>>
                            <label class="form-check-label" for="personDetection">Detect Person</label>
                        </div>
                        <small class="text-muted">Only enabled when camera detection is on</small>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">Save Settings</button>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="card">
            <div class="card-header"><h5 class="mb-0">System Usage</h5></div>
            <div class="card-body">
                <?php if(empty($systemUsage)): ?>
                    <p class="text-muted mb-0">No systems registered yet.</p>
                <?php else: ?>
                    <div class="mb-2">
                        <input type="text" class="form-control" id="usageSearch" placeholder="Search...">
                    </div>
                    <table class="table table-hover table-sm" id="usageTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>MAC ID</th>
                                <th>IP</th>
                                <th>Installed</th>
                                <th>Last Used</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($systemUsage as $i => $usage): ?>
                            <tr>
                                <td><?= $i + 1 ?></td>
                                <td><code><?= esc($usage['mac_id']) ?></code></td>
                                <td><?= esc($usage['ip_address']) ?></td>
                                <td><?= $usage['date_installed'] ? date('M d, Y', strtotime($usage['date_installed'])) : '-' ?></td>
                                <td><?= $usage['last_used_on'] ? date('M d, Y', strtotime($usage['last_used_on'])) : '-' ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
document.getElementById('cameraDetection').addEventListener('change', function() {
    const personGroup = document.getElementById('personDetectionGroup');
    const personCheckbox = document.getElementById('personDetection');
    if (!this.checked) {
        personCheckbox.checked = false;
        personCheckbox.disabled = true;
        personGroup.style.opacity = '0.5';
    } else {
        personCheckbox.disabled = false;
        personGroup.style.opacity = '1';
    }
});

document.getElementById('validateBtn').addEventListener('click', function() {
    const code = document.getElementById('licenseKey').value;
    if (!code) {
        alert('Please enter a license key');
        return;
    }
    
    fetch('/admin/settings/validate-license?code=' + encodeURIComponent(code))
        .then(response => response.json())
        .then(data => {
            const container = document.getElementById('licenseDetails');
            if (data.valid && data.license) {
                const l = data.license;
                container.innerHTML = `
                    <div class="border rounded p-3 bg-light">
                        <table class="table table-borderless table-sm mb-0">
                            <tr><th>Assigned To:</th><td>${l.assigned_to || '-'}</td></tr>
                            <tr><th>Status:</th><td><span class="badge bg-${l.status == 'Valid' ? 'success' : 'danger'}">${l.status}</span></td></tr>
                            <tr><th>Default URL:</th><td>${l.default_url || '-'}</td></tr>
                            <tr><th>Seats Limit:</th><td>${l.seats_limit == -1 ? 'Unlimited' : l.seats_limit}</td></tr>
                            <tr><th>Current Usage:</th><td>${l.current_limit_used}</td></tr>
                            <tr><th>Valid From:</th><td>${l.valid_from || '-'}</td></tr>
                            <tr><th>Valid To:</th><td>${l.valid_to || '-'}</td></tr>
                        </table>
                    </div>
                `;
            } else {
                container.innerHTML = '<div class="alert alert-danger">Invalid or expired license key</div>';
            }
        });
});

if (document.getElementById('usageSearch')) {
    document.getElementById('usageSearch').addEventListener('keyup', function() {
        const filter = this.value.toLowerCase();
        const rows = document.querySelectorAll('#usageTable tbody tr');
        rows.forEach(row => {
            row.style.display = row.textContent.toLowerCase().includes(filter) ? '' : 'none';
        });
    });
}

// Check initial state
if (!document.getElementById('cameraDetection').checked) {
    document.getElementById('personDetection').disabled = true;
    document.getElementById('personDetectionGroup').style.opacity = '0.5';
}
</script>
<?= $this->endSection() ?>
