<?php
session_start();
include('db_connection.php');

/* =========================
   SECURITY CHECK
========================= */
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$created_by = $_SESSION['user_id'];
$message = "";

/* =========================
   CREATE GROUP
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_group'])) {
    $group_name = trim($_POST['group_name']);
    $description = trim($_POST['description']);

    if (!empty($group_name)) {
        $sql = "INSERT INTO soc_groups (group_name, description, created_by) VALUES (?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssi", $group_name, $description, $created_by);

        if ($stmt->execute()) {
            $message = "Group created successfully.";
        } else {
            $message = "Error creating group: " . $stmt->error;
        }
        $stmt->close();
    } else {
        $message = "Group name is required.";
    }
}

/* =========================
   DELETE GROUP
========================= */
if (isset($_GET['delete'])) {
    $group_id = (int) $_GET['delete'];

    $sql = "DELETE FROM soc_groups WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $group_id);

    if ($stmt->execute()) {
        $message = "Group deleted successfully.";
    } else {
        $message = "Error deleting group: " . $stmt->error;
    }
    $stmt->close();
}

/* =========================
   UPDATE GROUP
========================= */
if (isset($_POST['update_group'])) {
    $group_id = (int) $_POST['group_id'];
    $group_name = trim($_POST['group_name']);
    $description = trim($_POST['description']);

    $sql = "UPDATE soc_groups SET group_name = ?, description = ? WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssi", $group_name, $description, $group_id);

    if ($stmt->execute()) {
        $message = "Group updated successfully.";
    } else {
        $message = "Error updating group: " . $stmt->error;
    }
    $stmt->close();
}

/* =========================
   FETCH GROUPS
========================= */
$sql = "SELECT * FROM soc_groups ORDER BY id DESC";
$result = $conn->query($sql);
$groups = $result->fetch_all(MYSQLI_ASSOC);

/* =========================
   EDIT MODE FETCH
========================= */
$edit_group = null;

if (isset($_GET['edit'])) {
    $id = (int) $_GET['edit'];

    $sql = "SELECT * FROM soc_groups WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);
    $stmt->execute();

    $result = $stmt->get_result();
    $edit_group = $result->fetch_assoc();
    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin - Manage Groups</title>

<style>
/* =========================
   BASE STYLE
========================= */
body {
    font-family: Arial, sans-serif;
    background: #f4f6f9;
    margin: 0;
}

/* =========================
   HEADER
========================= */
.header {
    background: #1e293b;
    color: white;
    padding: 15px 20px;
}

.header-container {
    max-width: 1100px;
    margin: auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.logo h2 {
    margin: 0;
    font-size: 20px;
}

.nav {
    display: flex;
    gap: 15px;
}

.nav a {
    color: white;
    text-decoration: none;
    padding: 8px 12px;
    border-radius: 6px;
}

.nav a:hover { background: rgba(255,255,255,0.1); }
.nav a.active { background: #2563eb; }
.nav a.logout { background: #ef4444; }

/* =========================
   MAIN CONTAINER
========================= */
.container {
    max-width: 900px;
    margin: 30px auto;
    background: white;
    padding: 25px;
    border-radius: 12px;
    box-shadow: 0 5px 20px rgba(0,0,0,0.08);
}

/* =========================
   BUTTONS
========================= */
.back-btn {
    display: inline-block;
    margin-bottom: 15px;
    background: #111827;
    color: white;
    padding: 10px 15px;
    border-radius: 8px;
    text-decoration: none;
}

.back-btn:hover { background: #000; }

button {
    padding: 10px 15px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
}

.create-btn, .update-btn {
    background: #2563eb;
    color: white;
}

.create-btn:hover, .update-btn:hover {
    background: #1d4ed8;
}

/* =========================
   FORM
========================= */
form {
    background: #f9fafb;
    padding: 20px;
    border-radius: 10px;
    margin-bottom: 25px;
}

input, textarea {
    width: 100%;
    padding: 10px;
    margin-top: 5px;
    border: 1px solid #ccc;
    border-radius: 8px;
}

/* =========================
   LIST
========================= */
.group {
    background: #fff;
    border: 1px solid #eee;
    padding: 12px;
    margin-bottom: 10px;
    border-radius: 8px;
    display: flex;
    justify-content: space-between;
}

.group a {
    padding: 5px 10px;
    border-radius: 6px;
    text-decoration: none;
    font-size: 13px;
}

.group a.edit { background: #f59e0b; color: white; }
.group a.delete { background: #ef4444; color: white; }

/* =========================
   MESSAGE
========================= */
.message {
    padding: 10px;
    background: #ecfdf5;
    border: 1px solid #10b981;
    color: #065f46;
    border-radius: 8px;
    margin-bottom: 15px;
}
</style>
</head>

<body>

<!-- ================= HEADER ================= -->
<div class="header">
    <div class="header-container">
        <div class="logo"><h2>AGID TECH</h2></div>
        <div class="nav">
            <a href="admin_dashboard.php">Dashboard</a>
            <a href="admin_groups.php" class="active">Groups</a>
            <a href="users.php">Users</a>
            <a href="logout.php" class="logout">Logout</a>
        </div>
    </div>
</div>

<!-- ================= MAIN ================= -->
<div class="container">

<a href="admin_dashboard.php" class="back-btn">← Back to Dashboard</a>

<?php if ($message): ?>
    <div class="message"><?php echo $message; ?></div>
<?php endif; ?>

<h2><?php echo $edit_group ? "Edit Group" : "Create New Group"; ?></h2>

<form method="POST">

    <?php if ($edit_group): ?>
        <input type="hidden" name="group_id" value="<?php echo $edit_group['id']; ?>">
    <?php endif; ?>

    <label>Group Name</label>
    <input type="text" name="group_name"
           value="<?php echo $edit_group['group_name'] ?? ''; ?>" required>

    <label>Description</label>
    <textarea name="description"><?php echo $edit_group['description'] ?? ''; ?></textarea>

    <?php if ($edit_group): ?>
        <button class="update-btn" name="update_group">Update Group</button>
        <a href="admin_groups.php">Cancel</a>
    <?php else: ?>
        <button class="create-btn" name="create_group">Create Group</button>
    <?php endif; ?>

</form>

<h2>Existing Groups</h2>

<?php foreach ($groups as $group): ?>
    <div class="group">
        <div>
            <strong><?php echo htmlspecialchars($group['group_name']); ?></strong><br>
            <small><?php echo htmlspecialchars($group['description']); ?></small>
        </div>

        <div>
            <a class="edit" href="?edit=<?php echo $group['id']; ?>">Edit</a>
            <a class="delete" onclick="return confirm('Delete this group?')"
               href="?delete=<?php echo $group['id']; ?>">Delete</a>
        </div>
    </div>
<?php endforeach; ?>

</div>

</body>
</html>