<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if user is admin
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Super Admin') {
    header('Location: index.php');
    exit();
}

$user_id = $_GET['id'] ?? '';
$edit_mode = !empty($user_id);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'] ?? '';
    $email = $_POST['email'] ?? '';
    $first_name = $_POST['first_name'] ?? '';
    $last_name = $_POST['last_name'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $role_id = $_POST['role_id'] ?? '';
    $password = $_POST['password'] ?? '';
    
    if ($edit_mode) {
        // Update user
        if (!empty($password)) {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $sql = "UPDATE users SET username = ?, email = ?, first_name = ?, last_name = ?, 
                    phone = ?, role_id = ?, password = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssssisi", $username, $email, $first_name, $last_name, $phone, $role_id, $hashed_password, $user_id);
        } else {
            $sql = "UPDATE users SET username = ?, email = ?, first_name = ?, last_name = ?, 
                    phone = ?, role_id = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssssii", $username, $email, $first_name, $last_name, $phone, $role_id, $user_id);
        }
    } else {
        // Create new user
        if (empty($password)) {
            $error_message = "Password is required for new users";
        } else {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $sql = "INSERT INTO users (username, email, first_name, last_name, phone, role_id, password, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssssis", $username, $email, $first_name, $last_name, $phone, $role_id, $hashed_password);
        }
    }
    
    if (isset($stmt) && $stmt->execute()) {
        $_SESSION['success_message'] = $edit_mode ? "User updated successfully!" : "User created successfully!";
        header('Location: list_users.php');
        exit();
    } else {
        $error_message = "Error: " . $conn->error;
    }
}

// Get user data if editing
$user_data = null;
if ($edit_mode) {
    $sql_user = "SELECT * FROM users WHERE id = ?";
    $stmt_user = $conn->prepare($sql_user);
    $stmt_user->bind_param("i", $user_id);
    $stmt_user->execute();
    $result_user = $stmt_user->get_result();
    $user_data = $result_user->fetch_assoc();
}

// Get roles
$sql_roles = "SELECT * FROM roles ORDER BY role_name";
$result_roles = $conn->query($sql_roles);
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $edit_mode ? 'Edit User' : 'Add User')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array(
                        'pagetitle' => 'System', 
                        'title' => $edit_mode ? 'Edit User' : 'Add User'
                    )); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="list_users.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i>Back to Users
                            </a>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0"><?php echo $edit_mode ? 'Edit' : 'Add'; ?> User</h4>
                                </div>
                                <div class="card-body">
                                    <?php if (isset($error_message)): ?>
                                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                            <?php echo htmlspecialchars($error_message); ?>
                                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                        </div>
                                    <?php endif; ?>

                                    <form method="POST">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Username <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="username" 
                                                       value="<?php echo htmlspecialchars($user_data['username'] ?? ''); ?>" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Email <span class="text-danger">*</span></label>
                                                <input type="email" class="form-control" name="email" 
                                                       value="<?php echo htmlspecialchars($user_data['email'] ?? ''); ?>" required>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">First Name <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="first_name" 
                                                       value="<?php echo htmlspecialchars($user_data['first_name'] ?? ''); ?>" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Last Name <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="last_name" 
                                                       value="<?php echo htmlspecialchars($user_data['last_name'] ?? ''); ?>" required>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Phone</label>
                                                <input type="tel" class="form-control" name="phone" 
                                                       value="<?php echo htmlspecialchars($user_data['phone'] ?? ''); ?>">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Role <span class="text-danger">*</span></label>
                                                <select class="form-select" name="role_id" required>
                                                    <option value="">Select Role</option>
                                                    <?php while($role = $result_roles->fetch_assoc()): ?>
                                                        <option value="<?php echo $role['id']; ?>" 
                                                                <?php echo ($user_data['role_id'] ?? '') == $role['id'] ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($role['role_name']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Password <?php echo $edit_mode ? '(leave blank to keep current)' : ''; ?> <span class="text-danger"><?php echo $edit_mode ? '' : '*'; ?></span></label>
                                            <input type="password" class="form-control" name="password" 
                                                   <?php echo $edit_mode ? '' : 'required'; ?>>
                                        </div>

                                        <div class="mt-4">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-save-line align-bottom me-1"></i><?php echo $edit_mode ? 'Update' : 'Create'; ?> User
                                            </button>
                                            <a href="list_users.php" class="btn btn-light ms-2">
                                                <i class="ri-close-line align-bottom me-1"></i>Cancel
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
