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

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

if(isset($_GET['id'])){
    $id = $_GET['id'];
    $result = $conn->query("SELECT * FROM news WHERE id = $id");
    $news = $result->fetch_assoc();
}

if(isset($_POST['update_news'])){
    $id = $_POST['news_id'];
    $title = mysqli_real_escape_string($conn, $_POST['title']);
    $detail = mysqli_real_escape_string($conn, $_POST['detail']);
    
    // จัดการเรื่องรูปภาพ (ถ้ามีการเลือกรูปใหม่)
    if($_FILES['image']['name'] != ""){
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $new_name = "news_" . time() . "." . $ext;
        move_uploaded_file($_FILES['image']['tmp_name'], "uploads/" . $new_name);
        $sql = "UPDATE news SET title='$title', detail='$detail', image='$new_name' WHERE id=$id";
    } else {
        $sql = "UPDATE news SET title='$title', detail='$detail' WHERE id=$id";
    }

    if($conn->query($sql)){
        echo "<script>alert('แก้ไขข่าวเรียบร้อย'); window.location='news.php';</script>";
    }
}
?>

<div class="container">
    <h2 style="color: #4a148c; margin: 30px 0;">✏️ แก้ไขข่าวสาร</h2>
    <div style="background: white; padding: 30px; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1);">
        <form action="edit_news.php" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="news_id" value="<?php echo $news['id']; ?>">
            
            <div style="margin-bottom: 15px;">
                <label>หัวข้อข่าว:</label>
                <input type="text" name="title" value="<?php echo $news['title']; ?>" style="width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 5px;" required>
            </div>
            
            <div style="margin-bottom: 15px;">
                <label>รายละเอียด:</label>
                <textarea name="detail" rows="5" style="width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 5px;" required><?php echo $news['detail']; ?></textarea>
            </div>

            <div style="margin-bottom: 15px;">
                <label>รูปภาพปัจจุบัน:</label><br>
                <?php if($news['image']): ?>
                    <img src="uploads/<?php echo $news['image']; ?>" width="200" style="border-radius: 10px; margin: 10px 0;">
                <?php endif; ?>
                <br>
                <label>เปลี่ยนรูปใหม่ (ปล่อยว่างถ้าไม่เปลี่ยน):</label>
                <input type="file" name="image" accept="image/*">
            </div>

            <button type="submit" name="update_news" style="padding: 12px 30px; background: #8e24aa; color: white; border: none; border-radius: 30px; cursor: pointer; font-weight: bold;">บันทึกการแก้ไข</button>
            <a href="news.php" style="margin-left:10px; color:#666; text-decoration:none;">ยกเลิก</a>
        </form>
    </div>
</div>

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