<?php
require_once __DIR__ . '/inc_functions.php';

// Safe esc() function for plain text fields
function esc($s){ return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

// Handle delete action
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM blogs WHERE id = ?");
    $stmt->execute([$id]);
    header('Location: admin.php');
    exit;
}

// Handle form submission for add/edit
$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? 0;
    $title = $_POST['title'];
    $slug = preg_replace('/[^a-z0-9-]/','',strtolower(str_replace(' ','-', $title)));
    $excerpt = $_POST['excerpt'];
    $content = $_POST['content'];
    $category = $_POST['category'];
    $is_published = isset($_POST['is_published']) ? 1 : 0;

    // Handle image upload
    $image_path = $_POST['existing_image'] ?? '';
    if (!empty($_FILES['image']['name'])) {
        if(!is_dir(__DIR__.'/uploads')) mkdir(__DIR__.'/uploads',0777,true);
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $image_path = 'uploads/' . time() . '.' . $ext;
        move_uploaded_file($_FILES['image']['tmp_name'], __DIR__ . '/' . $image_path);
    }

    if ($id) {
        // Update blog
        $stmt = $pdo->prepare("UPDATE blogs SET title=?, slug=?, excerpt=?, content=?, category=?, image_path=?, is_published=? WHERE id=?");
        $stmt->execute([$title, $slug, $excerpt, $content, $category, $image_path, $is_published, $id]);
        $msg = "Blog updated successfully!";
    } else {
        // Insert new blog
        $stmt = $pdo->prepare("INSERT INTO blogs (title, slug, excerpt, content, category, image_path, is_published, published_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
        $stmt->execute([$title, $slug, $excerpt, $content, $category, $image_path, $is_published]);
        $msg = "Blog added successfully!";
    }
}

// Fetch all blogs
$blogs = $pdo->query("SELECT * FROM blogs ORDER BY published_at DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Blogs Panel</title>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">

<!-- CKEditor -->
<script src="https://cdn.ckeditor.com/ckeditor5/39.0.1/classic/ckeditor.js"></script>

<style>
body{font-family:'Inter',sans-serif;background:#f5f5f5;margin:0;padding:0;}
.container{max-width:1200px;margin:30px auto;background:#fff;padding:25px;border-radius:12px;box-shadow:0 6px 20px rgba(0,0,0,0.1);}
h1{color:#0a74da;margin-bottom:20px;}
h2{color:#333;margin-bottom:15px;}
.msg{padding:12px 15px;background:#d4edda;color:#155724;border:1px solid #c3e6cb;margin-bottom:20px;border-radius:6px;}
.form-section{margin-bottom:40px;}
form label{font-weight:600;display:block;margin-top:12px;}
form input,form select,form textarea{width:100%;padding:10px 12px;margin-top:5px;border:1px solid #ccc;border-radius:6px;font-size:14px;}
form button{padding:10px 20px;margin-top:15px;background:#0a74da;color:#fff;border:none;border-radius:6px;cursor:pointer;font-weight:600;}
form button[type="button"]{background:#6c757d;}
.img-thumb{width:80px;height:auto;border-radius:4px;}
table{width:100%;border-collapse:collapse;box-shadow:0 2px 10px rgba(0,0,0,0.05);}
th,td{border:1px solid #ddd;padding:12px 10px;text-align:left;}
th{background:#f0f0f0;}
.action-btn{margin-right:5px;text-decoration:none;padding:5px 10px;border-radius:5px;color:#fff;font-size:13px;}
.edit-btn{background:#ffc107;}
.delete-btn{background:#dc3545;}
@media(max-width:768px){
    table,thead,tbody,th,td,tr{display:block;width:100%;}
    th,td{border:none;position:relative;padding-left:50%;}
    td::before{content:attr(data-label);position:absolute;left:10px;top:10px;font-weight:600;color:#333;}
    .action-btn{margin-bottom:5px;display:inline-block;}
}
</style>
</head>
<body>

<div class="container">
<h1>Manage Blogs</h1>

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

<div class="form-section">
<h2>Add / Edit Blog</h2>
<form method="post" enctype="multipart/form-data" id="blogForm">
<input type="hidden" name="id" id="blogId">
<input type="hidden" name="existing_image" id="existingImage">

<label>Title</label>
<input type="text" name="title" id="title" required>

<label>Excerpt</label>
<textarea name="excerpt" id="excerpt" rows="3"></textarea>

<label>Content</label>
<textarea name="content" id="content" rows="8"></textarea>

<label>Category</label>
<input type="text" name="category" id="category">

<label>Image</label>
<input type="file" name="image">

<label><input type="checkbox" name="is_published" id="isPublished"> Published</label>

<button type="submit">Save Blog</button>
<button type="button" onclick="resetForm()">Reset</button>
</form>
</div>

<div class="table-responsive">
<table>
<thead>
<tr>
<th>ID</th><th>Title</th><th>Category</th><th>Published</th><th>Date</th><th>Image</th><th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach($blogs as $b): ?>
<tr>
<td data-label="ID"><?= $b['id'] ?></td>
<td data-label="Title"><?= esc($b['title']) ?></td>
<td data-label="Category"><?= esc($b['category']) ?></td>
<td data-label="Published"><?= $b['is_published'] ? 'Yes' : 'No' ?></td>
<td data-label="Date"><?= date('M d, Y', strtotime($b['published_at'])) ?></td>
<td data-label="Image"><?php if($b['image_path']): ?><img src="<?= esc($b['image_path']) ?>" class="img-thumb"><?php endif; ?></td>
<td data-label="Actions">
<a href="#" class="action-btn edit-btn" onclick='editBlog(<?= json_encode([
'id'=>$b['id'],
'title'=>$b['title'],
'excerpt'=>$b['excerpt'],
'content'=>$b['content'],
'category'=>$b['category'],
'image_path'=>$b['image_path'],
'is_published'=>$b['is_published']
]) ?>)'>Edit</a>
<a href="?delete=<?= $b['id'] ?>" class="action-btn delete-btn" onclick="return confirm('Delete this blog?')">Delete</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>

<script>
let excerptEditor, contentEditor;

ClassicEditor.create(document.querySelector('#excerpt')).then(editor=>{ excerptEditor=editor; }).catch(console.error);
ClassicEditor.create(document.querySelector('#content')).then(editor=>{ contentEditor=editor; }).catch(console.error);

function editBlog(blog){
    document.getElementById('blogId').value = blog.id;
    document.getElementById('title').value = blog.title;
    excerptEditor.setData(blog.excerpt);
    contentEditor.setData(blog.content);
    document.getElementById('category').value = blog.category;
    document.getElementById('existingImage').value = blog.image_path;
    document.getElementById('isPublished').checked = blog.is_published==1;
}

function resetForm(){
    document.getElementById('blogId').value='';
    document.getElementById('existingImage').value='';
    document.getElementById('title').value='';
    excerptEditor.setData('');
    contentEditor.setData('');
    document.getElementById('category').value='';
    document.getElementById('isPublished').checked=false;
}

// Sync CKEditor before submit
document.getElementById('blogForm').addEventListener('submit', function(){
    document.getElementById('excerpt').value = excerptEditor.getData();
    document.getElementById('content').value = contentEditor.getData();
});
</script>

</body>
</html>
