
<?php
// Get current settings
 $stmt = $pdo->query("SELECT * FROM system_settings");
 $settings = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $settings[$row['setting_key']] = $row['setting_value'];
}
?>

<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                System Settings
            </div>
            <div class="card-body">
                <form method="post" action="">
                    <input type="hidden" name="action" value="update_settings">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="registration_fee" class="form-label">Registration Fee (₦)</label>
                            <input type="number" class="form-control" id="registration_fee" name="registration_fee" value="<?php echo $settings['registration_fee']; ?>" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="payment_description" class="form-label">Payment Description</label>
                            <input type="text" class="form-control" id="payment_description" name="payment_description" value="<?php echo $settings['payment_description']; ?>" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="academic_session" class="form-label">Academic Session</label>
                            <input type="text" class="form-control" id="academic_session" name="academic_session" value="<?php echo $settings['academic_session']; ?>" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="application_deadline" class="form-label">Application Deadline</label>
                            <input type="date" class="form-control" id="application_deadline" name="application_deadline" value="<?php echo $settings['application_deadline']; ?>" required>
                        </div>
                        <div class="col-md-12 mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="email_notifications" id="email_notifications" <?php echo $settings['email_notifications'] === 'enabled' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="email_notifications">
                                    Enable Email Notifications
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">Save Settings</button>
                </form>
                
                <hr class="my-4">
                
                <h4>Admin Accounts</h4>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Username</th>
                                <th>Full Name</th>
                                <th>Email</th>
                                <th>Created At</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $stmt = $pdo->query("SELECT * FROM admins ORDER BY created_at DESC");
                            while ($admin = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                echo "<tr>";
                                echo "<td>" . $admin['username'] . "</td>";
                                echo "<td>" . $admin['full_name'] . "</td>";
                                echo "<td>" . $admin['email'] . "</td>";
                                echo "<td>" . date('d M Y', strtotime($admin['created_at'])) . "</td>";
                                echo "<td>
                                        <button class=\"btn btn-sm btn-primary\" onclick=\"editAdmin(" . $admin['id'] . ")\">Edit</button>";
                                if ($admin['id'] != $_SESSION['user_id']) {
                                    echo "<button class=\"btn btn-sm btn-danger ms-1\" onclick=\"deleteAdmin(" . $admin['id'] . ")\">Delete</button>";
                                }
                                echo "</td>";
                                echo "</tr>";
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
                
                <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addAdminModal">Add New Admin</button>
            </div>
        </div>
    </div>
</div>

<!-- Add Admin Modal -->
<div class="modal fade" id="addAdminModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Admin</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addAdminForm">
                    <div class="mb-3">
                        <label for="new_admin_username" class="form-label">Username</label>
                        <input type="text" class="form-control" id="new_admin_username" required>
                    </div>
                    <div class="mb-3">
                        <label for="new_admin_email" class="form-label">Email</label>
                        <input type="email" class="form-control" id="new_admin_email" required>
                    </div>
                    <div class="mb-3">
                        <label for="new_admin_full_name" class="form-label">Full Name</label>
                        <input type="text" class="form-control" id="new_admin_full_name" required>
                    </div>
                    <div class="mb-3">
                        <label for="new_admin_password" class="form-label">Password</label>
                        <input type="password" class="form-control" id="new_admin_password" required>
                    </div>
                    <div class="mb-3">
                        <label for="new_admin_confirm_password" class="form-label">Confirm Password</label>
                        <input type="password" class="form-control" id="new_admin_confirm_password" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="addAdmin()">Add Admin</button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
    // Add admin
    window.addAdmin = function() {
        const username = document.getElementById("new_admin_username").value;
        const email = document.getElementById("new_admin_email").value;
        const fullName = document.getElementById("new_admin_full_name").value;
        const password = document.getElementById("new_admin_password").value;
        const confirmPassword = document.getElementById("new_admin_confirm_password").value;
        
        if (password !== confirmPassword) {
            alert("Passwords do not match");
            return;
        }
        
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                if (xhr.responseText === "success") {
                    alert("Admin added successfully");
                    location.reload();
                } else {
                    alert("Error: " + xhr.responseText);
                }
            }
        };
        xhr.send("action=add_admin&username=" + encodeURIComponent(username) + "&email=" + encodeURIComponent(email) + "&full_name=" + encodeURIComponent(fullName) + "&password=" + encodeURIComponent(password));
    };
    
    // Edit admin
    window.editAdmin = function(id) {
        // This would open a modal with the admin details
        alert("Edit functionality would be implemented here");
    };
    
    // Delete admin
    window.deleteAdmin = function(id) {
        if (confirm("Are you sure you want to delete this admin account?")) {
            const xhr = new XMLHttpRequest();
            xhr.open("POST", "", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    if (xhr.responseText === "success") {
                        alert("Admin deleted successfully");
                        location.reload();
                    } else {
                        alert("Error: " + xhr.responseText);
                    }
                }
            };
            xhr.send("action=delete_admin&id=" + id);
        }
    };
});
</script>

<?php
// Handle AJAX requests for admin management
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add_admin') {
        $username = $_POST['username'] ?? '';
        $email = $_POST['email'] ?? '';
        $fullName = $_POST['full_name'] ?? '';
        $password = $_POST['password'] ?? '';
        
        // Check if username already exists
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM admins WHERE username = ?");
        $stmt->execute([$username]);
        if ($stmt->fetchColumn() > 0) {
            echo "Username already exists";
            exit;
        }
        
        // Check if email already exists
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM admins WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->fetchColumn() > 0) {
            echo "Email already exists";
            exit;
        }
        
        // Hash password
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        
        // Insert new admin
        $stmt = $pdo->prepare("INSERT INTO admins (username, email, full_name, password) VALUES (?, ?, ?, ?)");
        $stmt->execute([$username, $email, $fullName, $hashedPassword]);
        
        echo "success";
        exit;
    } elseif ($_POST['action'] === 'delete_admin') {
        $id = $_POST['id'] ?? 0;
        
        if ($id > 0) {
            $stmt = $pdo->prepare("DELETE FROM admins WHERE id = ?");
            $stmt->execute([$id]);
            echo "success";
        } else {
            echo "Invalid admin ID";
        }
        
        exit;
    }
}
?>
