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

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

// ดึงหมวดข่าว
$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);
    $member_id   = $_SESSION['member_id'];

    $imageName = "";

    // อัปโหลดรูปภาพ
    if (!empty($_FILES['image']['name'])) {

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

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

    if ($message !== "") {
        // แสดงข้อความจากการตรวจไฟล์
    } elseif ($title == "" || $detail == "" || $category_id <= 0) {

        $message = "กรุณากรอกข้อมูลให้ครบ";
        $messageType = "danger";

    } else {

        $stmt = $conn->prepare(
    "INSERT INTO news(member_id, category_id, title, detail, image, status)
     VALUES (?, ?, ?, ?, ?, 'pending')"
);

        $stmt->bind_param(
            "iisss",
            $member_id,
            $category_id,
            $title,
            $detail,
            $imageName
        );

        if ($stmt->execute()) {

            header("Location: news_manage.php");
            exit;

        } else {

            $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>

            <option value="">
                -- เลือกหมวดข่าว --
            </option>

            <?php while ($cat = $categoryResult->fetch_assoc()): ?>

                <option value="<?= $cat['id']; ?>">
                    <?= htmlspecialchars($cat['category_name']); ?>
                </option>

            <?php endwhile; ?>

        </select>

    </div>

    <!-- หัวข้อข่าว -->
    <div class="mb-3">

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

        <input
            type="text"
            name="title"
            class="form-control"
            required>

    </div>

    <!-- รายละเอียดข่าว -->
    <div class="mb-3">

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

        <textarea
            name="detail"
            rows="8"
            class="form-control"
            required></textarea>

    </div>

        <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-success">

            💾 บันทึกข่าว

        </button>

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

            ยกเลิก

        </a>

    </form>

</div>

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