<?php
session_start();
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'teacher')) {
    header("Location: ../login.php");
    exit();
}

include(__DIR__ . '/../config/db.php');

// ดึงหมวดข่าว
$categories = $conn->query("SELECT * FROM categories ORDER BY name ASC");

// ฟังก์ชันสร้าง slug ไม่ซ้ำ
function generateSlug($title, $conn){
    $slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', trim($title)));
    $slug = trim($slug, '-');
    $baseSlug = $slug;
    $i = 1;
    while(true){
        $stmt = $conn->prepare("SELECT id FROM articles WHERE slug=?");
        $stmt->bind_param("s", $slug);
        $stmt->execute();
        $result = $stmt->get_result();
        if($result->num_rows == 0) break;
        $slug = $baseSlug . '-' . $i;
        $i++;
    }
    return $slug;
}

// บันทึกข่าวใหม่
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $title = $_POST['title'];
    $content = $_POST['content'];
    $category_id = intval($_POST['category_id']);
    $status = $_POST['status'];
    $author_id = $_SESSION['user_id'];
    $slug = generateSlug($title, $conn);

    $stmt = $conn->prepare("INSERT INTO articles (title, slug, content, category_id, author_id, status, created_at) 
                            VALUES (?, ?, ?, ?, ?, ?, NOW())");
    $stmt->bind_param("sssiss", $title, $slug, $content, $category_id, $author_id, $status);

    if($stmt->execute()){
        header("Location: manage_articles.php");
        exit();
    } else {
        $error = "ไม่สามารถเพิ่มข่าวได้: ".$stmt->error;
    }
    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <title>เพิ่มข่าวใหม่</title>
    <style>
        body {
            font-family: 'Kanit', sans-serif;
            background: linear-gradient(135deg, #dbeafe, #fef9c3);
            margin: 0;
            padding: 0;
        }
        .wrapper {
            max-width: 800px;
            margin: 50px auto;
            background: #ffffff;
            padding: 40px;
            border-radius: 16px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.08);
        }
        h2 {
            text-align: center;
            color: #222;
            margin-bottom: 30px;
            font-size: 28px;
        }
        nav {
            text-align: center;
            margin-bottom: 25px;
        }
        nav a {
            display: inline-block;
            background: #3b82f6;
            color: #fff;
            padding: 10px 18px;
            border-radius: 8px;
            font-size: 14px;
            margin: 0 8px;
            transition: 0.3s;
        }
        nav a:hover {
            background: #2563eb;
        }
        label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            color: #374151;
        }
        input[type="text"], select, textarea {
            width: 100%;
            padding: 12px;
            margin-bottom: 18px;
            border: 1px solid #d1d5db;
            border-radius: 10px;
            font-size: 15px;
            background: #f9fafb;
            transition: border 0.2s, box-shadow 0.2s;
        }
        input[type="text"]:focus, select:focus, textarea:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 6px rgba(59,130,246,0.3);
            outline: none;
        }
        textarea {
            resize: vertical;
            min-height: 120px;
        }
        button {
            width: 100%;
            padding: 14px;
            background: #10b981;
            color: #fff;
            border: none;
            font-size: 16px;
            font-weight: 600;
            border-radius: 10px;
            cursor: pointer;
            transition: background 0.3s;
        }
        button:hover {
            background: #059669;
        }
        .error {
            background: #fee2e2;
            color: #b91c1c;
            padding: 12px 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #fecaca;
        }
    </style>
</head>
<body>
<div class="wrapper">
    <h2>📰 เพิ่มข่าวใหม่</h2>

    <nav>
        <a href="manage_articles.php">📋 จัดการข่าว</a>
        <a href="logout.php">🚪 ออกจากระบบ</a>
    </nav>

    <?php if(isset($error)) echo "<div class='error'>$error</div>"; ?>

    <form method="post">
        <label>หัวข้อข่าว</label>
        <input type="text" name="title" placeholder="กรอกหัวข้อข่าว..." required>

        <label>หมวดข่าว</label>
        <select name="category_id" required>
            <option value="" disabled selected>-- เลือกหมวดข่าว --</option>
            <?php while($row = $categories->fetch_assoc()): ?>
                <option value="<?php echo $row['id']; ?>"><?php echo htmlspecialchars($row['name']); ?></option>
            <?php endwhile; ?>
        </select>

        <label>เนื้อหาข่าว</label>
        <textarea name="content" placeholder="กรอกเนื้อหาข่าว..." required></textarea>

        <label>สถานะ</label>
        <select name="status">
            <option value="draft">ฉบับร่าง</option>
            <option value="published" selected>เผยแพร่</option>
        </select>

        <button type="submit">✅ เพิ่มข่าว</button>
    </form>
</div>
</body>
</html>
