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

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

$message = "";
$message_type = "";

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

    $member_id  = $_SESSION['member_id'];
    $category_id = (int)($_POST['category_id'] ?? 0);
    $title       = trim($_POST['title'] ?? '');
    $detail      = trim($_POST['detail'] ?? '');
    $image_name  = null;
    $status      = "pending";

    if ($category_id <= 0 || $title === '' || $detail === '') {

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

    } else {

        if (
            isset($_FILES['image']) &&
            $_FILES['image']['error'] === UPLOAD_ERR_OK
        ) {

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

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

        if ($message === "") {

            $sql = "INSERT INTO news
                    (member_id, category_id, title, detail, image, status, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, NOW())";

            $stmt = $conn->prepare($sql);

            if (!$stmt) {

                error_log('Prepare news submission failed: ' . $conn->error);
                $message = "เกิดข้อผิดพลาดของระบบ กรุณาลองใหม่อีกครั้ง";
                $message_type = "danger";

            } else {

                $stmt->bind_param(
                    "iissss",
                    $member_id,
                    $category_id,
                    $title,
                    $detail,
                    $image_name,
                    $status
                );

                if ($stmt->execute()) {

                    $message = "ส่งข่าวเรียบร้อยแล้ว กรุณารอผู้ดูแลระบบตรวจสอบ";
                    $message_type = "success";

                } else {

                    error_log('News submission failed: ' . $stmt->error);
                    $message = "ไม่สามารถส่งข่าวได้ กรุณาลองใหม่อีกครั้ง";
                    $message_type = "danger";
                }

                $stmt->close();
            }
        }
    }
}

include "includes/header.php";
?>

<div class="container mt-5 mb-5">

    <div class="card shadow-sm">

        <div class="card-body p-4">

    <h2 class="mb-3">
        📰 ส่งข่าวประชาสัมพันธ์
    </h2>

    <p class="text-muted">
        สมาชิกสามารถส่งข่าวให้ผู้ดูแลระบบตรวจสอบก่อนเผยแพร่ได้
    </p>
    <?php if ($message !== ""): ?>

    <div class="alert alert-<?= $message_type ?>">
        <?= htmlspecialchars($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
                $category = $conn->query("SELECT * FROM news_categories ORDER BY id ASC");

                while($row = $category->fetch_assoc()){
                ?>

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

                <?php } ?>

            </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"
                class="form-control"
                rows="6"
                required></textarea>
        </div>

        <div class="mb-3">
            <label class="form-label">รูปภาพประกอบ</label>

            <input
                type="file"
                name="image"
                class="form-control"
                accept=".jpg,.jpeg,.png">
        </div>

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

            📤 ส่งข่าว

        </button>

    </form>

</div>

    </div>

</div>
