<?php
/**
 * Security Settings View
 */
$pageTitle = 'Security Settings';
$breadcrumb = [
    ['label' => 'Settings', 'url' => APP_URL . '/settings'],
    ['label' => 'Security', 'url' => null],
];
ob_start();
?>
<div class="page-header">
    <div>
        <h1 class="page-title">Security Settings</h1>
        <p class="page-subtitle">Manage two-factor authentication and active sessions</p>
    </div>
</div>

<!-- Settings Tabs -->
<div class="tabs">
    <a href="<?= APP_URL ?>/settings" class="tab-item">General</a>
    <a href="<?= APP_URL ?>/settings/security" class="tab-item active">Security</a>
    <a href="<?= APP_URL ?>/settings/billing" class="tab-item">Billing</a>
    <?php if (\Core\Auth::isSuperAdmin()): ?>
    <a href="<?= APP_URL ?>/settings/email" class="tab-item">Email/SMTP</a>
    <a href="<?= APP_URL ?>/admin/system" class="tab-item">System</a>
    <?php endif; ?>
</div>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;">

    <!-- Two-Factor Authentication -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Two-Factor Authentication (2FA)</h3>
            <span class="badge badge-<?= ($otpSecret && $otpSecret['is_enabled']) ? 'active' : 'secondary' ?>">
                <?= ($otpSecret && $otpSecret['is_enabled']) ? 'Enabled' : 'Disabled' ?>
            </span>
        </div>
        <div class="card-body">
            <?php if ($otpSecret && $otpSecret['is_enabled']): ?>
                <!-- OTP is enabled -->
                <div style="display:flex;align-items:flex-start;gap:16px;margin-bottom:24px;">
                    <div style="width:48px;height:48px;background:#DCFCE7;border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                        <svg width="24" height="24" fill="none" stroke="#0E9F6E" stroke-width="2" viewBox="0 0 24 24"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                    </div>
                    <div>
                        <div style="font-weight:600;margin-bottom:4px;color:#166534;">2FA is Active</div>
                        <p style="font-size:0.85rem;color:var(--text-secondary);margin:0;">Your account is protected with two-factor authentication using your authenticator app.</p>
                    </div>
                </div>

                <!-- Backup Codes Status -->
                <?php
                $backupCodes = json_decode($otpSecret['backup_codes'] ?? '[]', true) ?? [];
                $remaining   = count($backupCodes);
                ?>
                <div style="background:<?= $remaining <= 2 ? '#FFF7ED' : '#F0FDF4' ?>;border:1px solid <?= $remaining <= 2 ? '#FED7AA' : '#BBF7D0' ?>;border-radius:8px;padding:12px 16px;margin-bottom:20px;">
                    <div style="font-size:0.85rem;font-weight:500;color:<?= $remaining <= 2 ? '#92400E' : '#166534' ?>;">
                        <?= $remaining ?> backup code<?= $remaining !== 1 ? 's' : '' ?> remaining
                        <?php if ($remaining <= 2): ?> — Generate new ones soon!<?php endif; ?>
                    </div>
                </div>

                <!-- Disable OTP -->
                <button type="button" class="btn btn-danger btn-sm" onclick="document.getElementById('disableOtpModal').classList.remove('hidden')">
                    <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 1 1 8 0v4"/></svg>
                    Disable 2FA
                </button>
            <?php else: ?>
                <!-- OTP is not enabled -->
                <div style="display:flex;align-items:flex-start;gap:16px;margin-bottom:24px;">
                    <div style="width:48px;height:48px;background:#FDE5E2;border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                        <svg width="24" height="24" fill="none" stroke="#A82E26" stroke-width="2" viewBox="0 0 24 24"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
                    </div>
                    <div>
                        <div style="font-weight:600;margin-bottom:4px;color:#A82E26;">2FA Not Enabled</div>
                        <p style="font-size:0.85rem;color:var(--text-secondary);margin:0;">Protect your account by enabling two-factor authentication. You'll need the Google Authenticator or Authy app.</p>
                    </div>
                </div>
                <a href="<?= APP_URL ?>/otp/setup" class="btn btn-primary">
                    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 1 1 8 0v4"/></svg>
                    Enable 2FA Now
                </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Change Password -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Change Password</h3>
        </div>
        <div class="card-body">
            <form method="POST" action="<?= APP_URL ?>/profile/change-password" id="changePasswordForm">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">

                <div class="form-group">
                    <label class="form-label required" for="current_password">Current Password</label>
                    <input type="password" id="current_password" name="current_password" class="form-control" required>
                </div>

                <div class="form-group">
                    <label class="form-label required" for="new_password">New Password</label>
                    <input type="password" id="new_password" name="new_password" class="form-control" required oninput="checkPasswordStrength(this)">
                    <!-- Password Strength Bar -->
                    <div style="margin-top:8px;">
                        <div class="progress progress-sm">
                            <div class="progress-bar" id="strengthBar" style="width:0%;background:var(--danger);"></div>
                        </div>
                        <div id="strengthLabel" style="font-size:0.75rem;color:var(--text-muted);margin-top:4px;"></div>
                    </div>
                    <div class="form-hint">Min 8 chars, uppercase, lowercase, number, special character</div>
                </div>

                <div class="form-group">
                    <label class="form-label required" for="confirm_new_password">Confirm New Password</label>
                    <input type="password" id="confirm_new_password" name="confirm_password" class="form-control" required>
                </div>

                <button type="submit" class="btn btn-primary">Update Password</button>
            </form>
        </div>
    </div>
</div>

<!-- Active Sessions -->
<div class="card" style="margin-top:24px;">
    <div class="card-header">
        <h3 class="card-title">Active Sessions</h3>
        <span class="badge badge-secondary"><?= count($sessions ?? []) ?> session<?= count($sessions ?? []) !== 1 ? 's' : '' ?></span>
    </div>
    <div class="card-body" style="padding:0;">
        <?php if (empty($sessions)): ?>
            <div class="empty-state" style="padding:32px;">
                <p style="color:var(--text-muted);">No active sessions found.</p>
            </div>
        <?php else: ?>
            <?php foreach ($sessions as $session): ?>
            <div style="display:flex;align-items:center;gap:16px;padding:14px 20px;border-bottom:1px solid var(--border-color);">
                <div style="width:40px;height:40px;background:#F1F5F9;border-radius:10px;display:flex;align-items:center;justify-content:center;">
                    <svg width="18" height="18" fill="none" stroke="var(--text-secondary)" stroke-width="1.5" viewBox="0 0 24 24"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>
                </div>
                <div style="flex:1;">
                    <div style="font-size:0.85rem;font-weight:500;"><?= htmlspecialchars(substr($session['user_agent'] ?? 'Unknown browser', 0, 80)) ?></div>
                    <div style="font-size:0.75rem;color:var(--text-muted);">
                        <?= htmlspecialchars($session['ip_address'] ?? 'Unknown IP') ?> ·
                        Started <?= timeAgo($session['created_at']) ?>
                        <?php if (strtotime($session['expires_at']) > time()): ?>
                            · <span style="color:var(--success);">Active</span>
                        <?php else: ?>
                            · <span style="color:var(--danger);">Expired</span>
                        <?php endif; ?>
                    </div>
                </div>
                <form method="POST" action="<?= APP_URL ?>/settings/revoke-session/<?= urlencode($session['token']) ?>">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">
                    <button type="submit" class="btn btn-ghost btn-sm" onclick="return confirm('Revoke this session?')">Revoke</button>
                </form>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<!-- Disable OTP Modal -->
<div class="modal-overlay hidden" id="disableOtpModal">
    <div class="modal modal-sm">
        <div class="modal-header">
            <h4 class="modal-title">Disable Two-Factor Authentication</h4>
            <button class="modal-close" onclick="document.getElementById('disableOtpModal').classList.add('hidden')">×</button>
        </div>
        <form method="POST" action="<?= APP_URL ?>/settings/disable-otp">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">
            <div class="modal-body">
                <div class="alert alert-danger" style="margin-bottom:16px;">
                    ⚠️ Disabling 2FA will make your account less secure. Are you sure?
                </div>
                <div class="form-group">
                    <label class="form-label required" for="confirm_password_otp">Confirm your password</label>
                    <input type="password" id="confirm_password_otp" name="confirm_password" class="form-control" required placeholder="Enter your current password">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="document.getElementById('disableOtpModal').classList.add('hidden')">Cancel</button>
                <button type="submit" class="btn btn-danger">Disable 2FA</button>
            </div>
        </form>
    </div>
</div>

<script>
function checkPasswordStrength(input) {
    const val = input.value;
    let score = 0;
    if (val.length >= 8) score++;
    if (/[A-Z]/.test(val)) score++;
    if (/[a-z]/.test(val)) score++;
    if (/[0-9]/.test(val)) score++;
    if (/[^A-Za-z0-9]/.test(val)) score++;

    const bar = document.getElementById('strengthBar');
    const label = document.getElementById('strengthLabel');
    const levels = [
        { w: '20%', color: 'var(--danger)',  text: 'Very Weak' },
        { w: '40%', color: 'var(--danger)',  text: 'Weak' },
        { w: '60%', color: 'var(--warning)', text: 'Fair' },
        { w: '80%', color: 'var(--primary)', text: 'Good' },
        { w: '100%',color: 'var(--success)', text: 'Strong' },
    ];
    if (score > 0) {
        const l = levels[score - 1];
        bar.style.width = l.w;
        bar.style.background = l.color;
        label.textContent = l.text;
        label.style.color = l.color;
    } else {
        bar.style.width = '0%';
        label.textContent = '';
    }
}
</script>

<?php
$content = ob_get_clean();
require ROOT_PATH . '/modules/shared/views/layouts/main.php';
?>
