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

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

$id = intval($_GET['id'] ?? 0);
if($id <= 0){
    die("ไม่พบข่าวนี้");
}

// ดึงข่าว
$article = $conn->query("SELECT * FROM articles WHERE id=$id")->fetch_assoc();
if(!$article){
    die("ไม่พบข่าวนี้");
}

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

// ฟังก์ชันสร้าง slug ไม่ซ้ำ
function generateSlug($title, $conn, $id){
    $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=? AND id<>?");
        $stmt->bind_param("si", $slug, $id);
        $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'];
    $slug = generateSlug($title, $conn, $id);

    $stmt = $conn->prepare("UPDATE articles SET title=?, slug=?, content=?, category_id=?, status=? WHERE id=?");
    $stmt->bind_param("sssisi", $title, $slug, $content, $category_id, $status, $id);

    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: "Poppins", sans-serif;
            margin: 0;
            padding: 0;
            background: linear-gradient(135deg, #667eea, #764ba2);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
        .container {
            background: #fff;
            padding: 35px 40px;
            border-radius: 15px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
            width: 90%;
            max-width: 700px;
            animation: fadeIn 0.5s ease-in-out;
        }
        h2 {
            text-align: center;
            margin-bottom: 25px;
            color: #444;
        }
        a.back-link {
            display: inline-block;
            margin-bottom: 20px;
            text-decoration: none;
            color: #667eea;
            font-weight: bold;
        }
        form label {
            display: block;
            margin-top: 15px;
            font-weight: 600;
            color: #333;
        }
        input[type="text"], select, textarea {
            width: 100%;
            padding: 12px 14px;
            margin-top: 8px;
            border: 1px solid #ccc;
            border-radius: 8px;
            font-size: 15px;
            transition: border-color 0.3s, box-shadow 0.3s;
        }
        input[type="text"]:focus, select:focus, textarea:focus {
            border-color: #667eea;
            box-shadow: 0 0 6px rgba(102,126,234,0.4);
            outline: none;
        }
        textarea {
            resize: vertical;
            min-height: 160px;
        }
        button {
            margin-top: 25px;
            width: 100%;
            padding: 14px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: #fff;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(118,75,162,0.4);
        }
        .error {
            color: red;
            font-weight: bold;
            text-align: center;
            margin-bottom: 15px;
        }
        @keyframes fadeIn {
            from {opacity: 0; transform: translateY(15px);}
            to {opacity: 1; transform: translateY(0);}
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>📝 แก้ไขข่าว</h2>
        <a href="manage_articles.php" class="back-link">⬅️ กลับหน้าจัดการข่าว</a>

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

        <form method="post">
            <label>หัวข้อข่าว:</label>
            <input type="text" name="title" value="<?php echo htmlspecialchars($article['title']); ?>" required>

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

            <label>เนื้อหาข่าว:</label>
            <textarea name="content" required><?php echo htmlspecialchars($article['content']); ?></textarea>

            <label>สถานะ:</label>
            <select name="status">
                <option value="draft" <?php if($article['status']=='draft') echo 'selected'; ?>>Draft</option>
                <option value="published" <?php if($article['status']=='published') echo 'selected'; ?>>Published</option>
            </select>

            <button type="submit">💾 บันทึกการแก้ไข</button>
        </form>
    </div>
</body>
</html>
