<?php 
include '../includes/auth.php';
include '../includes/db.php';

$success = '';
$error = '';

// DELETE blog image individually
if (isset($_GET['delete_img'])) {
    $imgId = (int)$_GET['delete_img'];
    $imgData = $conn->query("SELECT image_path, blog_id FROM blog_images WHERE id=$imgId")->fetch_assoc();
    if ($imgData) {
        $path = '../' . $imgData['image_path'];
        if (file_exists($path)) unlink($path);
        $conn->query("DELETE FROM blog_images WHERE id=$imgId");
        header("Location: blog_add.php?edit=".$imgData['blog_id']);
        exit;
    }
}

// DELETE blog
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $imgs = $conn->query("SELECT image_path FROM blog_images WHERE blog_id=$id");
    while ($img = $imgs->fetch_assoc()) {
        $path = '../' . $img['image_path'];
        if (file_exists($path)) unlink($path);
    }
    $conn->query("DELETE FROM blog_images WHERE blog_id=$id");
    $conn->query("DELETE FROM blog WHERE id=$id");
    header("Location: blog_add.php");
    exit;
}

// EDIT blog
$editing = false;
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $blog = $conn->query("SELECT * FROM blog WHERE id=$id")->fetch_assoc();
    if (!$blog) die("Blog not found");
    $editing = true;

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

        $stmt = $conn->prepare("UPDATE blog SET title=?, author=?, content=? WHERE id=?");
        $stmt->bind_param("sssi", $title, $author, $content, $id);
        $stmt->execute();
        $stmt->close();

        // Upload new images if selected
        if (!empty($_FILES['images']['name'][0])) {
            $targetDir = "../uploads/blog/";
            if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);

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

                    if (move_uploaded_file($files['tmp_name'][$i], $targetFile)) {
                        $imagePath = "uploads/blog/".$fileName;
                        $imgStmt = $conn->prepare("INSERT INTO blog_images (blog_id, image_path) VALUES (?, ?)");
                        $imgStmt->bind_param("is", $id, $imagePath);
                        $imgStmt->execute();
                        $imgStmt->close();
                    }
                }
            }
        }

        $success = "Blog updated successfully!";
    }
}

// ADD new blog
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_GET['edit'])) {
    $title = trim($_POST['title']);
    $author = trim($_POST['author']);
    $content = trim($_POST['content']);

    $stmt = $conn->prepare("INSERT INTO blog (title, author, content) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $title, $author, $content);
    if($stmt->execute()){
        $blogId = $stmt->insert_id; 
        $stmt->close();

        // Upload images
        if (!empty($_FILES['images']['name'][0])) {
            $targetDir = "../uploads/blog/";
            if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);

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

                    if (move_uploaded_file($files['tmp_name'][$i], $targetFile)) {
                        $imagePath = "uploads/blog/".$fileName;
                        $imgStmt = $conn->prepare("INSERT INTO blog_images (blog_id, image_path) VALUES (?, ?)");
                        $imgStmt->bind_param("is", $blogId, $imagePath);
                        $imgStmt->execute();
                        $imgStmt->close();
                    }
                }
            }
        }

        $success = "Blog added successfully!";
        // stay in Add mode
        header("Location: blog_add.php?added=1");
        exit;
    } else {
        $error = "Error adding blog: " . $conn->error;
    }
}

// Show success after redirect
if(isset($_GET['added']) && $_GET['added'] == 1){
    $success = "Blog added successfully!";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= $editing ? "Edit Blog" : "Add Blog Post" ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js"></script>
<script>
tinymce.init({
  selector: '#content',
  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 | outdent indent | link image media | preview fullscreen | forecolor backcolor emoticons | code',
  menubar: 'file edit view insert format tools table help',
  branding: false
  
  
});
</script>
<style>
body { background:#f3f5f9; font-family:"Segoe UI",sans-serif; color:#333; }
.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%; }
.btn { width:200px; background:#007bff; color:white; padding:10px 15px; border:none; border-radius:6px; cursor:pointer; font-weight:bold; align-self:center; transition:0.3s; }
.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; }

/* Existing images */
.existing-images { display:flex; gap:15px; flex-wrap:wrap; margin-bottom:15px; }
.existing-images .img-box { position:relative; width:120px; height:80px; }
.existing-images img { width:100%; height:100%; object-fit:cover; border-radius:6px; }
.existing-images .delete-img { position:absolute; top:-6px; right:-6px; background:#dc3545; color:#fff; border:none; border-radius:50%; width:24px; height:24px; cursor:pointer; font-weight:bold; }

/* Blog table */
.blog-table { width:100%; border-collapse:collapse; margin-top:35px; font-size:0.95rem; }
.blog-table th, .blog-table td { padding:12px 15px; border-bottom:1px solid #ddd; text-align:left; }
.blog-table th { background:#007bff; color:#fff; font-weight:600; text-transform:uppercase; }
.blog-table tr:hover { background:#f1f5f9; }
.blog-table img { width:70px; height:50px; object-fit:cover; border-radius:4px; }
.blog-table a.edit, .blog-table a.delete { padding:5px 10px; border-radius:5px; text-decoration:none; color:#fff; font-size:0.85rem; margin-right:5px; }
.blog-table a.edit { background:#28a745; }
.blog-table a.edit:hover { background:#1e7e34; }
.blog-table a.delete { background:#dc3545; }
.blog-table a.delete:hover { background:#a71d2a; }
</style>
</head>
<?php include 'header.php'; ?>
<body>

<div class="admin-container">
<h2><?= $editing ? "Edit Blog" : "Add Blog Post" ?></h2>

<?php if($success): ?>
<div class="success"><?= $success ?></div>
<?php endif; ?>
<?php if($error): ?>
<div class="error"><?= $error ?></div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data" class="news-form">
    <label>Title:</label>
    <input type="text" name="title" value="<?= $editing ? htmlspecialchars($blog['title']) : '' ?>" required>

    <label>Author:</label>
    <input type="text" name="author" value="<?= $editing ? htmlspecialchars($blog['author']) : '' ?>">

    <?php if($editing):
        $images = $conn->query("SELECT * FROM blog_images WHERE blog_id=".$blog['id']);
        if($images->num_rows > 0): ?>
        <label>Existing Images:</label>
        <div class="existing-images">
            <?php while($img = $images->fetch_assoc()): ?>
            <div class="img-box">
                <img src="../<?= $img['image_path'] ?>" alt="Blog Image">
                <a href="blog_add.php?delete_img=<?= $img['id'] ?>" class="delete-img" onclick="return confirm('Delete this image?')">&times;</a>
            </div>
            <?php endwhile; ?>
        </div>
        <?php endif; ?>
    <?php endif; ?>

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

    <label>Content:</label>
    <textarea name="content" id="content"><?= $editing ? htmlspecialchars($blog['content']) : '' ?></textarea>

    <button type="submit" class="btn"><?= $editing ? "Update Blog" : "Add Blog Post" ?></button>
</form>

<!-- Existing Blogs List -->
<table class="blog-table">
<thead>
<tr>
    <th>ID</th>
    <th>Title</th>
    <th>Author</th>
    <th>Images</th>
    <th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$blogs = $conn->query("SELECT * FROM blog ORDER BY id DESC");
while($b = $blogs->fetch_assoc()):
    $imgRes = $conn->query("SELECT image_path FROM blog_images WHERE blog_id=".$b['id']." LIMIT 1");
    $img = $imgRes->num_rows ? $imgRes->fetch_assoc()['image_path'] : '';
?>
<tr>
    <td><?= $b['id'] ?></td>
    <td><?= htmlspecialchars($b['title']) ?></td>
    <td><?= htmlspecialchars($b['author']) ?></td>
    <td><?php if($img): ?><img src="../<?= $img ?>" alt="Blog Image"><?php endif; ?></td>
    <td>
        <a href="blog_add.php?edit=<?= $b['id'] ?>" class="edit">Edit</a>
        <a href="blog_add.php?delete=<?= $b['id'] ?>" class="delete" onclick="return confirm('Are you sure?')">Delete</a>
    </td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

</div>
</body>
</html>
