<?php
include 'admin-header.php';

$message = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $id = intval($_POST['id']);
    $username = trim($_POST['username']);
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];

    if ($id > 0) { // Update existing admin
        if (!empty($password)) {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE admins SET username=?, full_name=?, email=?, password=? WHERE id=?");
            $stmt->bind_param("ssssi", $username, $full_name, $email, $hashed_password, $id);
        } else {
            $stmt = $conn->prepare("UPDATE admins SET username=?, full_name=?, email=? WHERE id=?");
            $stmt->bind_param("sssi", $username, $full_name, $email, $id);
        }
    } else { // Create new admin
        if (!empty($password)) {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("INSERT INTO admins (username, full_name, email, password) VALUES (?,?,?,?)");
            $stmt->bind_param("ssss", $username, $full_name, $email, $hashed_password);
        } else {
            $message = '<div class="alert alert-danger">Password is required for new admins.</div>';
        }
    }
    
    if (isset($stmt) && $stmt->execute()) {
        $message = '<div class="alert alert-success">Admin saved successfully.</div>';
    } elseif (empty($message)) {
        $message = '<div class="alert alert-danger">Error saving admin.</div>';
    }
}
?>
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Manage Admins</h1>
</div>
<?php echo $message; ?>
<div class="card">
    <div class="card-body">
        <h5 class="card-title">Add / Edit Admin</h5>
        <form method="POST">
            <input type="hidden" name="id" value="0">
            <div class="mb-3"><input type="text" class="form-control" name="full_name" placeholder="Full Name" required></div>
            <div class="mb-3"><input type="text" class="form-control" name="username" placeholder="Username" required></div>
            <div class="mb-3"><input type="email" class="form-control" name="email" placeholder="Email" required></div>
            <div class="mb-3"><input type="password" class="form-control" name="password" placeholder="New Password (leave blank to keep current)"></div>
            <button type="submit" class="btn btn-primary">Add New Admin</button>
        </form>
    </div>
</div>
<?php include 'admin-footer.php'; ?>
