<?php 
include 'header.php'; 
include 'connect.php';

// ตรวจสอบสิทธิ์ Admin
if(!isset($_SESSION['username']) || $_SESSION['username'] !== 'admin'){
    echo "<script>alert('เฉพาะ Admin เท่านั้น'); window.location='index.php';</script>";
    exit();
}

// รับค่า ID ที่ส่งมาจากการคลิกแก้ไข
if(isset($_GET['id'])){
    $id = $_GET['id'];
    $sql = "SELECT * FROM users WHERE id = $id";
    $result = $conn->query($sql);
    $user = $result->fetch_assoc();
}

// เมื่อกดปุ่มบันทึกการแก้ไข
if(isset($_POST['update_btn'])){
    $id = $_POST['user_id'];
    $new_user = $_POST['username'];
    // หมายเหตุ: ในระบบจริงควรมีการเข้ารหัสผ่าน แต่ในที่นี้ใช้แบบพื้นฐานตามโปรเจกต์เดิม
    $new_pass = $_POST['password']; 

    $sql_update = "UPDATE users SET username='$new_user', password='$new_pass' WHERE id=$id";
    
    if($conn->query($sql_update)){
        echo "<script>alert('แก้ไขข้อมูลเรียบร้อย'); window.location='show.php';</script>";
    } else {
        echo "Error updating record: " . $conn->error;
    }
}
?>

<div class="container" style="max-width: 500px; margin-top: 50px;">
    <div style="background: white; padding: 30px; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1);">
        <h2 style="text-align: center; color: #4a148c;">แก้ไขข้อมูลสมาชิก</h2>
        <hr>
        
        <form action="edit_user.php" method="POST">
            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
            
            <div style="margin-bottom: 15px;">
                <label>ชื่อผู้ใช้งาน:</label>
                <input type="text" name="username" value="<?php echo $user['username']; ?>" style="width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 5px;" required>
            </div>
            
            <div style="margin-bottom: 20px;">
                <label>รหัสผ่านใหม่:</label>
                <input type="text" name="password" value="<?php echo $user['password']; ?>" style="width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 5px;" required>
            </div>
            
            <div style="display: flex; gap: 10px;">
                <button type="submit" name="update_btn" style="flex: 1; padding: 12px; background: #8e24aa; color: white; border: none; border-radius: 30px; cursor: pointer; font-weight: bold;">
                    บันทึกการแก้ไข
                </button>
                <a href="show.php" style="flex: 1; padding: 12px; background: #ccc; color: #333; text-decoration: none; text-align: center; border-radius: 30px; font-weight: bold;">ยกเลิก</a>
            </div>
        </form>
    </div>
</div>

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