<?php
require_once "../includes/auth.php";
requireAdmin();

require_once "../includes/config.php";
require_once "../includes/functions.php";

// ตรวจสอบ id
if (!isset($_GET['id'])) {
    header("Location: news_manage.php");
    exit;
}

$id = intval($_GET['id']);

// ดึงข้อมูลข่าว
$stmt = $conn->prepare("SELECT * FROM news WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();

$result = $stmt->get_result();

if ($result->num_rows == 0) {
    header("Location: news_manage.php");
    exit;
}

$news = $result->fetch_assoc();
$stmt->close();

$categoryResult = $conn->query(
    "SELECT id, category_name
     FROM news_categories
     WHERE status = 1
     ORDER BY category_name ASC"
);

$message = "";
$messageType = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    requireValidCsrf();

    $title  = trim($_POST['title'] ?? '');
    $detail = trim($_POST['detail'] ?? '');

    $category_id = (int)($_POST['category_id'] ?? 0);

    $imageName = $news['image'];
    $newImageName = '';

    // ถ้ามีการอัปโหลดรูปใหม่
    if (!empty($_FILES['image']['name'])) {

        $upload = saveUploadedImage(
            $_FILES['image'],
            '../uploads/news/'
        );

        if (!$upload['ok']) {
            $message = $upload['error'];
            $messageType = 'danger';
        } else {
            $newImageName = $upload['filename'];
            $imageName = $newImageName;
        }
    }

    if ($title === '' || $detail === '' || $category_id <= 0) {
        $message = 'กรุณากรอกข้อมูลให้ครบ';
        $messageType = 'danger';
    }

    if ($message === '') {
        $stmt = $conn->prepare(
            "UPDATE news
             SET category_id = ?, title = ?, detail = ?, image = ?
             WHERE id = ?"
        );

        $stmt->bind_param(
            "isssi",
            $category_id,
            $title,
            $detail,
            $imageName,
            $id
        );

        if ($stmt->execute()) {
            if ($newImageName !== '') {
                deleteUploadedImage('../uploads/news/', $news['image']);
            }

            $stmt->close();
            header("Location: news_manage.php");
            exit;

        } else {
            if ($newImageName !== '') {
                deleteUploadedImage('../uploads/news/', $newImageName);
            }

            $message = "ไม่สามารถบันทึกข้อมูลได้";
            $messageType = "danger";

            $stmt->close();
        }
    }
}

include '../includes/header.php';
?>

<div class="container mt-5">

    <h2 class="mb-4">
        ✏️ แก้ไขข่าวประชาสัมพันธ์
    </h2>

    <?php if ($message != ""): ?>

        <div class="alert alert-<?= $messageType; ?>">

            <?= $message; ?>

        </div>

    <?php endif; ?>

    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">

        <div class="mb-3">
            <label class="form-label">หมวดข่าว</label>
            <select name="category_id" class="form-select" required>
                <?php while ($category = $categoryResult->fetch_assoc()): ?>
                    <option
                        value="<?= (int)$category['id'] ?>"
                        <?= (int)$category['id'] === (int)$news['category_id'] ? 'selected' : '' ?>
                    >
                        <?= htmlspecialchars($category['category_name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>

        <div class="mb-3">

            <label class="form-label">
                หัวข้อข่าว
            </label>

            <input
                type="text"
                name="title"
                class="form-control"
                value="<?= htmlspecialchars($news['title']); ?>"
                required>

        </div>

        <div class="mb-3">

            <label class="form-label">
                รายละเอียดข่าว
            </label>

            <textarea
                name="detail"
                rows="8"
                class="form-control"
                required><?= htmlspecialchars($news['detail']); ?></textarea>

        </div>

        <?php if (!empty($news['image'])): ?>

        <div class="mb-3">

            <label class="form-label">
                รูปปัจจุบัน
            </label>

            <br>

            <img
                src="../uploads/news/<?= htmlspecialchars($news['image']); ?>"
                width="250"
                class="img-thumbnail">

        </div>

        <?php endif; ?>

        <div class="mb-3">

            <label class="form-label">
                เปลี่ยนรูปภาพ (ถ้ามี)
            </label>

            <input
                type="file"
                name="image"
                class="form-control"
                accept="image/*">

        </div>

        <button
            type="submit"
            class="btn btn-warning">

            💾 บันทึกการแก้ไข

        </button>

        <a
            href="news_manage.php"
            class="btn btn-secondary">

            ยกเลิก

        </a>

    </form>

</div>

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