<?php
// Admin Registration Settings - Partial for Dashboard
// This file is included in admin/dashboard.php
if (!isset($db)) {
    echo '<div class="alert alert-danger">❌ Database connection missing.</div>';
    return;
}

$error = '';
$success = '';

// Get current settings
$settings = $db->query("SELECT * FROM admin_settings LIMIT 1")->fetch(PDO::FETCH_ASSOC);

// Default values if no settings exist
if (!$settings) {
    $registration_mode = 'otp';
    $otp_enabled = 1;
    $otp_expiry_minutes = 5;
} else {
    $registration_mode = isset($settings['registration_mode']) ? $settings['registration_mode'] : 'otp';
    $otp_enabled = isset($settings['otp_enabled']) ? $settings['otp_enabled'] : 1;
    $otp_expiry_minutes = isset($settings['otp_expiry_minutes']) ? $settings['otp_expiry_minutes'] : 5;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $new_mode = $_POST['registration_mode'] ?? 'otp';
    $new_otp_enabled = isset($_POST['otp_enabled']) ? 1 : 0;
    $new_otp_expiry = intval($_POST['otp_expiry_minutes']) ?? 5;
    
    // Validate
    if (!in_array($new_mode, ['otp', 'direct'])) {
        $error = '❌ Invalid registration mode selected.';
    } elseif ($new_otp_expiry < 1 || $new_otp_expiry > 60) {
        $error = '❌ OTP Expiry must be between 1-60 minutes.';
    } else {
        // Update settings
        try {
            if ($settings) {
                // Update existing
                $db->query(
                    "UPDATE admin_settings SET registration_mode = ?, otp_enabled = ?, otp_expiry_minutes = ? LIMIT 1",
                    [$new_mode, $new_otp_enabled, $new_otp_expiry]
                );
            } else {
                // Insert new
                $db->query(
                    "INSERT INTO admin_settings (registration_mode, otp_enabled, otp_expiry_minutes) VALUES (?, ?, ?)",
                    [$new_mode, $new_otp_enabled, $new_otp_expiry]
                );
            }
            
            $registration_mode = $new_mode;
            $otp_enabled = $new_otp_enabled;
            $otp_expiry_minutes = $new_otp_expiry;
            $success = '✅ Registration settings updated successfully!';
        } catch (Exception $e) {
            $error = '❌ Error updating settings: ' . $e->getMessage();
        }
    }
}
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-8">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">📋 Registration Settings</h5>
                </div>
                <div class="card-body">
                    <?php if ($success): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo htmlspecialchars($success); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo htmlspecialchars($error); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <form method="POST">
                        <!-- Registration Mode Selection -->
                        <div class="mb-4">
                            <label class="form-label fw-bold">🔐 Registration Mode</label>
                            <div class="card bg-light">
                                <div class="card-body">
                                    <div class="form-check mb-3">
                                        <input class="form-check-input" type="radio" name="registration_mode" id="mode_otp" 
                                               value="otp" <?php echo $registration_mode === 'otp' ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="mode_otp">
                                            <strong>OTP-Based Registration</strong>
                                            <small class="d-block text-muted mt-1">
                                                New users must verify with 6-digit OTP sent to their email
                                            </small>
                                        </label>
                                    </div>
                                    <hr>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="registration_mode" id="mode_direct" 
                                               value="direct" <?php echo $registration_mode === 'direct' ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="mode_direct">
                                            <strong>Direct Registration (No OTP)</strong>
                                            <small class="d-block text-muted mt-1">
                                                New users can register directly without email verification
                                            </small>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- OTP Enable/Disable Toggle -->
                        <div class="mb-4">
                            <label class="form-label fw-bold">⚙️ OTP Settings</label>
                            <div class="card bg-light">
                                <div class="card-body">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="otp_enabled" name="otp_enabled" 
                                               <?php echo $otp_enabled ? 'checked' : ''; ?> onchange="toggleOtpSettings()">
                                        <label class="form-check-label" for="otp_enabled">
                                            <strong>Enable OTP Requirement</strong>
                                        </label>
                                    </div>
                                    <small class="d-block text-muted mt-2">
                                        When disabled, users can register without OTP verification regardless of registration mode
                                    </small>
                                </div>
                            </div>
                        </div>

                        <!-- OTP Expiry Time -->
                        <div class="mb-4">
                            <label for="otp_expiry_minutes" class="form-label fw-bold">⏱️ OTP Expiry Time (Minutes)</label>
                            <div class="input-group">
                                <input type="number" class="form-control" id="otp_expiry_minutes" name="otp_expiry_minutes" 
                                       min="1" max="60" value="<?php echo $otp_expiry_minutes; ?>"
                                       <?php echo !$otp_enabled ? 'disabled' : ''; ?>>
                                <span class="input-group-text">minutes</span>
                            </div>
                            <small class="d-block text-muted mt-2">
                                OTP validity period: 1-60 minutes (Current: <?php echo $otp_expiry_minutes; ?> min)
                            </small>
                        </div>

                        <!-- Current Configuration Summary -->
                        <div class="alert alert-info">
                            <strong>📊 Current Configuration:</strong>
                            <ul class="mb-0 mt-2">
                                <li><strong>Registration Mode:</strong> <?php echo ucfirst(str_replace('_', ' ', $registration_mode)); ?></li>
                                <li><strong>OTP Status:</strong> <?php echo $otp_enabled ? '✅ Enabled' : '❌ Disabled'; ?></li>
                                <li><strong>OTP Expiry:</strong> <?php echo $otp_expiry_minutes; ?> minutes</li>
                            </ul>
                        </div>

                        <!-- Submit Button -->
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="fas fa-save"></i> Save Registration Settings
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Information Card -->
            <div class="card mt-4 border-info">
                <div class="card-header bg-info text-white">
                    <h6 class="mb-0">ℹ️ How It Works</h6>
                </div>
                <div class="card-body text-muted">
                    <p><strong>OTP-Based Mode:</strong> Users register → Receive 6-digit OTP via email → Verify OTP → Account activated</p>
                    <p><strong>Direct Mode:</strong> Users register → Account instantly activated → No email verification needed</p>
                    <p><strong>OTP Expiry:</strong> Determines how long users have to verify their OTP after registration</p>
                </div>
            </div>
        </div>

        <!-- Statistics Sidebar -->
        <div class="col-md-4">
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-success text-white">
                    <h6 class="mb-0">📈 Registration Stats</h6>
                </div>
                <div class="card-body">
                    <?php
                    $total_users = $db->query("SELECT COUNT(*) as count FROM users")->fetch(PDO::FETCH_ASSOC)['count'];
                    $verified_users = $db->query("SELECT COUNT(*) as count FROM users WHERE email_verified = 1")->fetch(PDO::FETCH_ASSOC)['count'];
                    $pending_otp = $db->query("SELECT COUNT(*) as count FROM email_otps")->fetch(PDO::FETCH_ASSOC)['count'];
                    ?>
                    <div class="stat-item mb-3">
                        <label class="text-muted">Total Users</label>
                        <h4 class="text-primary"><?php echo $total_users; ?></h4>
                    </div>
                    <div class="stat-item mb-3">
                        <label class="text-muted">Email Verified</label>
                        <h4 class="text-success"><?php echo $verified_users; ?></h4>
                    </div>
                    <div class="stat-item">
                        <label class="text-muted">Pending OTP</label>
                        <h4 class="text-warning"><?php echo $pending_otp; ?></h4>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function toggleOtpSettings() {
    const isEnabled = document.getElementById('otp_enabled').checked;
    document.getElementById('otp_expiry_minutes').disabled = !isEnabled;
}
</script>

<style>
.stat-item {
    padding: 10px;
    background: #f8f9fa;
    border-radius: 5px;
}
</style>
