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

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

$id = intval($_GET['id']);
$result = $con->query("SELECT * FROM users_shop WHERE id = $id");
$user = $result->fetch_assoc();

if (isset($_POST['update'])) {

    $name = $_POST['name'];
    $email = $_POST['email'];
    $role = $_POST['role'];
    $password = $_POST['password'];

    // যদি পাসওয়ার্ড খালি থাকে তাহলে পুরাতন পাসওয়ার্ড থাকবে
    if (!empty($password)) {
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $con->prepare("UPDATE users_shop SET name=?, email=?, role=?, password=? WHERE id=?");
        $stmt->bind_param("ssssi", $name, $email, $role, $hashedPassword, $id);
    } else {
        $stmt = $con->prepare("UPDATE users_shop SET name=?, email=?, role=? WHERE id=?");
        $stmt->bind_param("sssi", $name, $email, $role, $id);
    }

    if ($stmt->execute()) {
        echo "<script>alert('ইউজার আপডেট সফল হয়েছে!'); window.location='manage_users.php';</script>";
    }
}

/*----------------------------------------inclode------------------------*/

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



<div class="container mt-4">


    <h3>ইউজার এডিট</h3>
    <form method="POST">
        <div class="mb-3">
            <label>নাম</label>
            <input type="text" name="name" value="<?= $user['name'] ?>" class="form-control" required>
        </div>

        <div class="mb-3">
            <label>ইমেইল</label>
            <input type="email" name="email" value="<?= $user['email'] ?>" class="form-control" required>
        </div>

        <div class="mb-3">
            <label>নতুন পাসওয়ার্ড (খালি রাখলে পরিবর্তন হবে না)</label>
            <input type="password" name="password" class="form-control">
        </div>

        <div class="mb-3">
            <label>ভূমিকা</label>
            <select name="role" class="form-control">
                <option value="admin" <?= $user['role']=='admin'?'selected':'' ?>>Admin</option>
                <option value="user" <?= $user['role']=='user'?'selected':'' ?>>User</option>
            </select>
        </div>

        <button type="submit" name="update" class="btn btn-success">আপডেট করুন</button>
    </form>
</div>