<?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?msg=updated");
        exit();
    } else {
        $error = "บันทึกไม่สำเร็จ: ".$stmt->error;
    }
    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8">
<title>แก้ไขข่าว</title>
<style>
    body {
        font-family: 'Prompt', sans-serif;
        background: linear-gradient(135deg, #6EE7B7, #3B82F6);
        margin: 0;
        padding: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 100vh;
    }
    .card {
        background: #fff;
        width: 95%;
        max-width: 700px;
        padding: 30px;
        border-radius: 16px;
        box-shadow: 0 10px 25px rgba(0,0,0,0.15);
        animation: fadeIn 0.6s ease-in-out;
    }
    @keyframes fadeIn {
        from {opacity: 0; transform: translateY(20px);}
        to {opacity: 1; transform: translateY(0);}
    }
    h2 {
        margin-bottom: 20px;
        text-align: center;
        color: #1f2937;
    }
    label {
        font-weight: bold;
        display: block;
        margin-top: 15px;
        margin-bottom: 5px;
        color: #374151;
    }
    input[type="text"], textarea, select {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #d1d5db;
        border-radius: 8px;
        font-size: 15px;
        transition: all 0.3s;
    }
    input[type="text"]:focus, textarea:focus, select:focus {
        border-color: #3B82F6;
        box-shadow: 0 0 5px rgba(59,130,246,0.5);
        outline: none;
    }
    textarea {
        resize: vertical;
        min-height: 120px;
    }
    .btn-group {
        margin-top: 25px;
        text-align: center;
    }
    button, .back-link {
        padding: 10px 20px;
        border: none;
        border-radius: 8px;
        font-size: 16px;
        font-weight: bold;
        cursor: pointer;
        margin: 5px;
        transition: transform 0.2s, box-shadow 0.2s;
    }
    button {
        background: #3B82F6;
        color: #fff;
    }
    button:hover {
        background: #2563eb;
        transform: translateY(-2px);
        box-shadow: 0 6px 12px rgba(0,0,0,0.15);
    }
    .back-link {
        background: #6B7280;
        color: #fff;
        text-decoration: none;
        display: inline-block;
    }
    .back-link:hover {
        background: #4B5563;
        transform: translateY(-2px);
        box-shadow: 0 6px 12px rgba(0,0,0,0.15);
    }
    .error {
        color: red;
        text-align: center;
        margin-bottom: 10px;
    }
</style>
</head>
<body>
    <div class="card">
        <h2>✏️ แก้ไขข่าว</h2>
        <div style="text-align:center; margin-bottom:15px;">
            <a href="manage_articles.php" class="back-link">⬅ กลับหน้าจัดการข่าว</a>
        </div>
        <?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>

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