<?php
include '../includes/auth.php';
include '../includes/db.php';
include 'header.php';
$id = (int)$_GET['id'];
$news = $conn->query("SELECT * FROM news WHERE id=$id")->fetch_assoc();
if (!$news) die("News not found");

// Update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title']);
    $content = $_POST['content']; // keep full HTML content

    // Update title & content
    $stmt = $conn->prepare("UPDATE news SET title=?, content=? WHERE id=?");
    $stmt->bind_param("ssi", $title, $content, $id);
    $stmt->execute();

    // Delete selected images
    if (!empty($_POST['delete_images'])) {
        foreach ($_POST['delete_images'] as $imgId) {
            $imgId = (int)$imgId;
            $res = $conn->query("SELECT image_path FROM news_images WHERE id=$imgId");
            if ($row = $res->fetch_assoc()) @unlink("../".$row['image_path']);
            $conn->query("DELETE FROM news_images WHERE id=$imgId");
        }
    }

    // Upload new images
    if (!empty($_FILES['images']['name'][0])) {
        $dir = "../uploads/news/";
        if (!is_dir($dir)) mkdir($dir, 0777, true);

        foreach ($_FILES['images']['name'] as $i => $name) {
            if ($name) {
                $file = time()."_".basename($name);
                if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $dir.$file)) {
                    $path = "uploads/news/".$file;
                    $conn->query("INSERT INTO news_images (news_id, image_path) VALUES ($id,'$path')");
                }
            }
        }
    }

    header("Location: News_php.php");
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit News</title>

<!-- TinyMCE (working config as per your version) -->
<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js"></script>
<script>
tinymce.init({
    selector: 'textarea',
    height: 500,
    menubar: true,
    plugins: 'lists link image table code fullscreen',
    toolbar: 'undo redo | bold italic underline strikethrough | alignleft aligncenter alignright | bullist numlist | link image | code fullscreen',
    entity_encoding: 'raw', // preserve HTML tags
    convert_urls: false
});
</script>

<style>
.admin-container{
    max-width:900px;
    margin:40px auto;
    background:#fff;
    padding:30px;
    border-radius:14px;
    box-shadow:0 10px 30px rgba(0,0,0,.1);
}
.admin-container h2{
    text-align:center;
    margin-bottom:20px;
}
.admin-container label{
    font-weight:600;
    margin-top:15px;
    display:block;
}
.admin-container input,
.admin-container textarea{
    width:100%;
    padding:10px;
    border:1px solid #ccc;
    border-radius:8px;
}
.image-box{
    display:flex;
    gap:15px;
    flex-wrap:wrap;
    margin-top:10px;
}
.image-item{
    text-align:center;
}
.image-item img{
    width:160px;
    height:110px;
    object-fit:cover;
    border-radius:10px;
    box-shadow:0 4px 10px rgba(0,0,0,.15);
    margin-bottom:6px;
}
.btn{
    margin-top:25px;
    background:#25A9C2;
    color:#fff;
    padding:12px 30px;
    border:none;
    border-radius:30px;
    font-size:15px;
    cursor:pointer;
}
.btn:hover{
    background:#1c8aa0;
}
</style>

</head>
<body>

<div class="admin-container">
<h2>Edit News</h2>

<form method="POST" enctype="multipart/form-data">

    <label>Title</label>
    <input type="text" name="title" value="<?= htmlspecialchars($news['title']) ?>" required>

    <label>Content</label>
    <textarea name="content"><?= htmlspecialchars_decode($news['content']) ?></textarea>

    <label>Current Images</label>
    <div class="image-box">
        <?php
        $imgs = $conn->query("SELECT * FROM news_images WHERE news_id=$id");
        while($img = $imgs->fetch_assoc()):
        ?>
        <div class="image-item">
            <img src="../<?= $img['image_path'] ?>">
            <br>
            <input type="checkbox" name="delete_images[]" value="<?= $img['id'] ?>"> Delete
        </div>
        <?php endwhile; ?>
    </div>

    <label>Upload New Images</label>
    <input type="file" name="images[]" multiple accept="image/*">

    <button class="btn">Update News</button>

</form>
</div>

</body>
</html>
