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

// Auth Check
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: admin.php");
    exit;
}

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$user = null;
$error = null;
$success = null;

// Fetch Categories for Dropdown
$cats = [];
$cat_res = $conn->query("SELECT id, title FROM categories ORDER BY id");
if ($cat_res) {
    while ($c = $cat_res->fetch_assoc())
        $cats[] = $c;
}

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $org_name = $_POST['org_name'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $role = $_POST['role'];
    $status = $_POST['status'];
    $assigned_category_id = !empty($_POST['assigned_category_id']) ? intval($_POST['assigned_category_id']) : null;

    if ($id > 0) {
        // Update
        if (!empty($password)) {
            $hash = password_hash($password, PASSWORD_BCRYPT);
            $stmt = $conn->prepare("UPDATE users SET org_name=?, email=?, password=?, role=?, status=?, assigned_category_id=? WHERE id=?");
            $stmt->bind_param("sssssii", $org_name, $email, $hash, $role, $status, $assigned_category_id, $id);
        } else {
            $stmt = $conn->prepare("UPDATE users SET org_name=?, email=?, role=?, status=?, assigned_category_id=? WHERE id=?");
            $stmt->bind_param("ssssii", $org_name, $email, $role, $status, $assigned_category_id, $id);
        }

        if ($stmt->execute()) {
            $success = "User updated successfully.";
        } else {
            $error = "Error updating user: " . $conn->error;
        }
    } else {
        // Create
        if (empty($password)) {
            $error = "Password is required for new users.";
        } else {
            $hash = password_hash($password, PASSWORD_BCRYPT);
            $stmt = $conn->prepare("INSERT INTO users (org_name, email, password, role, status, assigned_category_id) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssssi", $org_name, $email, $hash, $role, $status, $assigned_category_id);

            if ($stmt->execute()) {
                $success = "User created successfully.";
                $id = $stmt->insert_id;
            } else {
                $error = "Error creating user: " . $conn->error;
            }
        }
    }
}

// Fetch User Data for Edit
if ($id > 0) {
    $stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    $user = $res->fetch_assoc();
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SaniBook Admin -
        <?php echo $id > 0 ? 'Edit' : 'Add'; ?> User
    </title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
</head>

<body class="bg-slate-100 font-sans text-slate-900">

    <?php include 'navbar.php'; ?>

    <div class="max-w-3xl mx-auto p-6">
        <div class="flex items-center gap-4 mb-6">
            <a href="users.php" class="text-slate-500 hover:text-blue-600"><i class="fa-solid fa-arrow-left mr-1"></i>
                Back to Users</a>
            <h2 class="text-2xl font-bold text-slate-800">
                <?php echo $id > 0 ? 'Edit User' : 'Add New User'; ?>
            </h2>
        </div>

        <?php if ($error): ?>
            <div class="bg-red-100 text-red-700 p-4 rounded-lg mb-6 border border-red-200">
                <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="bg-green-100 text-green-700 p-4 rounded-lg mb-6 border border-green-200">
                <?php echo $success; ?>
            </div>
        <?php endif; ?>

        <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-8">
            <form method="POST" class="space-y-6">

                <div class="grid md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Organization/Name</label>
                        <input type="text" name="org_name" required value="<?php echo $user['org_name'] ?? ''; ?>"
                            class="w-full border border-slate-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Email Address</label>
                        <input type="email" name="email" required value="<?php echo $user['email'] ?? ''; ?>"
                            class="w-full border border-slate-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Password
                        <?php echo $id > 0 ? '<span class="text-xs font-normal text-slate-500">(Leave blank to keep unchanged)</span>' : ''; ?>
                    </label>
                    <input type="password" name="password" <?php echo $id == 0 ? 'required' : ''; ?> class="w-full border
                    border-slate-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-500 focus:outline-none">
                </div>

                <div class="border-t border-slate-100 pt-6 grid md:grid-cols-3 gap-6">
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Role</label>
                        <select name="role"
                            class="w-full border border-slate-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-500 bg-white">
                            <option value="contributor" <?php echo ($user['role'] ?? '') === 'contributor' ? 'selected' : ''; ?>>Contributor</option>
                            <option value="editor" <?php echo ($user['role'] ?? '') === 'editor' ? 'selected' : ''; ?>>
                                Editor</option>
                            <option value="admin" <?php echo ($user['role'] ?? '') === 'admin' ? 'selected' : ''; ?>>Admin
                            </option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Status</label>
                        <select name="status"
                            class="w-full border border-slate-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-500 bg-white">
                            <option value="pending" <?php echo ($user['status'] ?? '') === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="approved" <?php echo ($user['status'] ?? '') === 'approved' ? 'selected' : ''; ?>>Approved</option>
                            <option value="rejected" <?php echo ($user['status'] ?? '') === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Assigned Category</label>
                        <select name="assigned_category_id"
                            class="w-full border border-slate-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-500 bg-white">
                            <option value="">-- None / All --</option>
                            <?php foreach ($cats as $c): ?>
                                <option value="<?php echo $c['id']; ?>" <?php echo ($user['assigned_category_id'] ?? '') == $c['id'] ? 'selected' : ''; ?>>
                                    <?php echo $c['id'] . '. ' . htmlspecialchars($c['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <p class="text-xs text-slate-500 mt-1">If set, limits contributor to this category.</p>
                    </div>
                </div>

                <div class="pt-4 flex justify-end">
                    <button type="submit"
                        class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-8 rounded-lg shadow-lg transition-all transform hover:scale-105">
                        <i class="fa-solid fa-save mr-2"></i> Save User
                    </button>
                </div>

            </form>
        </div>
    </div>
</body>

</html>
