<?php
/**
 * Admin Panel — Overview
 */
if (!hasRole('captain')) {
    header('Location: ../dashboard.php?error=forbidden');
    exit;
}

$db = getDB();
$totalUsers = (int)$db->query("SELECT COUNT(*) FROM users WHERE status = 'active'")->fetchColumn();
$pendingUsers = (int)$db->query("SELECT COUNT(*) FROM users WHERE status = 'pending'")->fetchColumn();
$totalIncidents = (int)$db->query("SELECT COUNT(*) FROM incidents_cache WHERE received_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)")->fetchColumn();
$recentLogs = $db->query("SELECT a.*, u.first_name, u.last_name FROM audit_log a LEFT JOIN users u ON a.user_id = u.id ORDER BY a.created_at DESC LIMIT 15")->fetchAll();
?>

<div class="page-header">
    <h1>Admin Panel</h1>
</div>

<!-- Stats -->
<div class="grid grid-4" style="margin-bottom:24px;">
    <div class="stat-card">
        <span class="stat-value"><?= $totalUsers ?></span>
        <span class="stat-label">Active Users</span>
    </div>
    <div class="stat-card" style="<?= $pendingUsers > 0 ? 'border: 2px solid var(--ios-orange);' : '' ?>">
        <span class="stat-value"><?= $pendingUsers ?></span>
        <span class="stat-label">Pending Approvals</span>
    </div>
    <div class="stat-card">
        <span class="stat-value"><?= $totalIncidents ?></span>
        <span class="stat-label">Incidents (24h)</span>
    </div>
    <div class="stat-card">
        <span class="stat-value"><?= (int)$db->query("SELECT COUNT(*) FROM audit_log WHERE DATE(created_at) = CURDATE()")->fetchColumn() ?></span>
        <span class="stat-label">Actions Today</span>
    </div>
</div>

<!-- Quick Links -->
<div class="grid grid-3" style="margin-bottom:24px;">
    <a href="dashboard.php?page=admin-users" class="card" style="text-decoration:none;">
        <div style="display:flex; align-items:center; gap:12px;">
            <div style="width:44px; height:44px; background:var(--ios-bg); border-radius:10px; display:flex; align-items:center; justify-content:center;">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--ios-blue)" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
            </div>
            <div>
                <div style="font-weight:700; color:var(--ios-text);">Manage Users</div>
                <div style="font-size:13px; color:var(--ios-secondary);">
                    <?= $pendingUsers ?> pending approval<?= $pendingUsers !== 1 ? 's' : '' ?>
                </div>
            </div>
        </div>
    </a>
    <div class="card">
        <div style="display:flex; align-items:center; gap:12px;">
            <div style="width:44px; height:44px; background:var(--ios-bg); border-radius:10px; display:flex; align-items:center; justify-content:center;">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--cfd-red)" stroke-width="2"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>
            </div>
            <div>
                <div style="font-weight:700; color:var(--ios-text);">Settings</div>
                <div style="font-size:13px; color:var(--ios-secondary);">Configure portal options</div>
            </div>
        </div>
    </div>
    <div class="card">
        <div style="display:flex; align-items:center; gap:12px;">
            <div style="width:44px; height:44px; background:var(--ios-bg); border-radius:10px; display:flex; align-items:center; justify-content:center;">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--ios-green)" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
            </div>
            <div>
                <div style="font-weight:700; color:var(--ios-text);">Audit Log</div>
                <div style="font-size:13px; color:var(--ios-secondary);">View system activity</div>
            </div>
        </div>
    </div>
</div>

<!-- Settings Quick Config -->
<?php if (hasRole('admin')): ?>
<div class="card" style="margin-bottom:24px;">
    <div class="card-header">
        <h2 class="card-title">Quick Settings</h2>
    </div>
    <form method="POST" action="dashboard.php?page=admin" style="display:grid; grid-template-columns:1fr 1fr; gap:16px;">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
        <input type="hidden" name="action" value="update_settings">
        <div class="form-group">
            <label>Google Slides URL</label>
            <input type="url" name="google_slides_url" class="form-control" value="<?= htmlspecialchars(getSetting('google_slides_url')) ?>" placeholder="https://docs.google.com/presentation/...">
        </div>
        <div class="form-group">
            <label>OT Embed Dashboard URL</label>
            <input type="url" name="ot_embed_url" class="form-control" value="<?= htmlspecialchars(getSetting('ot_embed_url')) ?>" placeholder="Power BI / Tableau embed URL">
        </div>
        <div class="form-group">
            <label>Target Solutions URL</label>
            <input type="url" name="target_solutions_url" class="form-control" value="<?= htmlspecialchars(getSetting('target_solutions_url')) ?>">
        </div>
        <div class="form-group">
            <label>Admin Email</label>
            <input type="email" name="admin_email" class="form-control" value="<?= htmlspecialchars(getSetting('admin_email')) ?>">
        </div>
        <div style="grid-column:1/-1;">
            <button type="submit" class="btn btn-primary">Save Settings</button>
        </div>
    </form>
</div>
<?php
// Handle settings update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'update_settings') {
    validateCsrf();
    $settingsFields = ['google_slides_url', 'ot_embed_url', 'target_solutions_url', 'admin_email'];
    foreach ($settingsFields as $field) {
        if (isset($_POST[$field])) {
            setSetting($field, trim($_POST[$field]));
        }
    }
    auditLog('settings_updated', $user['id'], 'Admin settings updated');
    echo '<div class="alert alert-success" style="margin-bottom:16px;">Settings saved.</div>';
}
endif; ?>

<!-- Audit Log -->
<div class="card">
    <div class="card-header">
        <h2 class="card-title">Recent Activity</h2>
    </div>
    <div class="table-wrapper">
        <table>
            <thead>
                <tr><th>Time</th><th>User</th><th>Action</th><th>Details</th><th>IP</th></tr>
            </thead>
            <tbody>
            <?php foreach ($recentLogs as $log): ?>
                <tr>
                    <td style="white-space:nowrap; font-size:13px; color:var(--ios-secondary);">
                        <?= date('M j g:i A', strtotime($log['created_at'])) ?>
                    </td>
                    <td><?= htmlspecialchars(($log['first_name'] ?? '') . ' ' . ($log['last_name'] ?? '')) ?></td>
                    <td><span class="badge badge-blue"><?= htmlspecialchars($log['action']) ?></span></td>
                    <td style="max-width:300px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:13px;">
                        <?= htmlspecialchars($log['detail'] ?? '') ?>
                    </td>
                    <td style="font-size:12px; color:var(--ios-tertiary);"><?= htmlspecialchars($log['ip_address'] ?? '') ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
