<?php include '../includes/auth.php'; ?>
<?php include '../includes/db.php'; ?>
<?php include 'header.php'; ?>
<?php
if (isset($_GET['delete'])) {
    $id = (int) $_GET['delete'];

    // delete images first
    $conn->query("DELETE FROM news_images WHERE news_id=$id");

    // delete news
    $conn->query("DELETE FROM news WHERE id=$id");

    header("Location: News_php.php");
    exit;
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add News</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Include Poppins from Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">

<!-- Self-hosted TinyMCE -->
<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js"></script>

<script>
tinymce.init({
  selector: 'textarea',
  height: 500,
  plugins: 'advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code fullscreen insertdatetime media table emoticons template paste wordcount',
  
  toolbar: 'undo redo | formatselect | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist checklist | outdent indent | link image media | print preview fullscreen | forecolor backcolor emoticons | code',
  
  menubar: 'file edit view insert format tools table help',
  branding: false,
  
  // Set default font to Poppins
  content_style: "body { font-family: 'Poppins', sans-serif; }"
});
</script>


<style>
body { background: #f3f5f9; font-family: "Segoe UI", sans-serif; }
.admin-container {
    width: 80%; max-width: 900px; margin: 50px auto; background: #fff;
    padding: 30px 40px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}
.admin-container h2 {
    text-align: center; margin-bottom: 25px; color: #333;
    font-size: 1.8rem; border-bottom: 2px solid #007bff; display: inline-block;
    padding-bottom: 5px;
}
.news-form { display: flex; flex-direction: column; gap: 15px; }
.news-form label { font-weight: bold; color: #444; }
.news-form input[type="text"], 
.news-form input[type="file"], 
.news-form textarea {
    padding: 10px; border: 1px solid #ccc; border-radius: 8px; font-size: 1rem; width: 100%;
}
.news-form input[type="file"] { background: #f9f9f9; }
.btn {
    width: 200px; background: #007bff; color: white; padding: 10px 15px;
    border: none; border-radius: 6px; cursor: pointer; font-weight: bold;
    transition: 0.3s; align-self: center;
}
.btn:hover { background: #0056b3; }
.success, .error {
    padding: 12px; border-radius: 6px; text-align: center; margin-bottom: 15px;
}
.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
.error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
</style>
</head>
<body>

<div class="admin-container">
    <h2>Add News</h2>

    <?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $title = trim($_POST['title']);
        $content = trim($_POST['content']);

        if (!empty($title) && !empty($content)) {

            $stmt = $conn->prepare("INSERT INTO news (title, content) VALUES (?, ?)");
            $stmt->bind_param("ss", $title, $content);

            if ($stmt->execute()) {
                $news_id = $stmt->insert_id;
                $stmt->close();

                // Image upload
                $targetDir = "../uploads/news/";
                if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);

                $files = $_FILES['images'];
                for ($i = 0; $i < count($files['name']); $i++) {
                    if (!empty($files['name'][$i])) {
                        $fileName = time() . '_' . basename($files['name'][$i]);
                        $targetFile = $targetDir . $fileName;

                        if (move_uploaded_file($files['tmp_name'][$i], $targetFile)) {
                            $imagePath = "uploads/news/" . $fileName;

                            $imgStmt = $conn->prepare("INSERT INTO news_images (news_id, image_path) VALUES (?, ?)");
                            $imgStmt->bind_param("is", $news_id, $imagePath);
                            $imgStmt->execute();
                            $imgStmt->close();
                        }
                    }
                }

                echo "<p class='success'>✅ News added successfully with images!</p>";

            } else {
                echo "<p class='error'>❌ Failed to save news.</p>";
            }

        } else {
            echo "<p class='error'>⚠️ Title and content cannot be empty.</p>";
        }
    }
    ?>

    <form action="" method="POST" enctype="multipart/form-data" class="news-form">
        <label for="title">News Title:</label>
        <input type="text" name="title" id="title" required>

        <label for="images">Upload Images (multiple allowed):</label>
        <input type="file" name="images[]" accept="image/*" multiple>

        <label for="content">News Content:</label>
        <textarea name="content" id="content"></textarea>

        <button type="submit" class="btn">Add News</button>
    </form>
    
    <hr style="margin:40px 0">

<h2 style="font-size:1.4rem;">Existing News</h2>

<?php
$newsList = $conn->query("SELECT * FROM news ORDER BY id DESC");
if ($newsList && $newsList->num_rows > 0):
?>
<table style="width:100%; border-collapse:collapse; margin-top:20px;">
    <tr style="background:#f1f5f9;">
        <th style="padding:10px; text-align:left;">Title</th>
        <th style="padding:10px; width:160px;">Actions</th>
    </tr>

    <?php while($row = $newsList->fetch_assoc()): ?>
    <tr style="border-bottom:1px solid #ddd;">
        <td style="padding:10px;">
            <?= htmlspecialchars($row['title']) ?>
        </td>
        <td style="padding:10px; text-align:center;">
            <a href="edit-news.php?id=<?= $row['id'] ?>" 
               style="color:#007bff; font-weight:bold; margin-right:10px;">
               ✏️ Edit
            </a>

            <a href="?delete=<?= $row['id'] ?>" 
               onclick="return confirm('Are you sure you want to delete this news?')"
               style="color:#dc3545; font-weight:bold;">
               🗑️ Delete
            </a>
        </td>
    </tr>
    <?php endwhile; ?>
</table>
<?php else: ?>
<p>No news added yet.</p>
<?php endif; ?>
</div>
<?php include '../includes/footer.php'; ?>
</body>
</html>
