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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method not allowed');
}

requireValidCsrf();

if (!isset($_POST['id'])) {
    header("Location: news_manage.php");
    exit;
}

$id = (int)$_POST['id'];

// ดึงชื่อไฟล์รูปก่อนลบ
$stmt = $conn->prepare("SELECT image FROM news WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();

$result = $stmt->get_result();

if ($result->num_rows == 0) {
    $stmt->close();
    header("Location: news_manage.php");
    exit;
}

$row = $result->fetch_assoc();
$stmt->close();

// ลบไฟล์รูป (ถ้ามี)
if (!empty($row['image'])) {

    $imagePath = "../uploads/news/" . $row['image'];

    if (file_exists($imagePath)) {
        unlink($imagePath);
    }

}

// ลบข้อมูลในฐานข้อมูล
$stmt = $conn->prepare("DELETE FROM news WHERE id = ?");
$stmt->bind_param("i", $id);

if ($stmt->execute()) {

    $stmt->close();

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

} else {

    $stmt->close();

    echo "เกิดข้อผิดพลาดในการลบข้อมูล";

}

$conn->close();
?>
