<?php
/**
 * Admin Blog Management
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';
require_login();

if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

$page_title = 'Blog';

// Handle delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("DELETE FROM blog_posts WHERE id = ?");
        $stmt->execute([$id]);
        set_flash_message('Post deleted successfully!', 'success');
    } catch (PDOException $e) {
        set_flash_message('Failed to delete post.', 'error');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Handle add/edit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        set_flash_message('Invalid request.', 'error');
    } else {
        $id = (int)($_POST['id'] ?? 0);
        $title = sanitize($_POST['title'] ?? '');
        $slug = slugify($_POST['slug'] ?? $title);
        $content = $_POST['content'] ?? '';
        $excerpt = sanitize($_POST['excerpt'] ?? '');
        $status = sanitize($_POST['status'] ?? 'draft');
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        if (empty($title)) {
            set_flash_message('Post title is required.', 'error');
        } else {
            try {
                $author_id = $_SESSION['user_id'];
                $published_at = ($status === 'published') ? ($id ? null : date('Y-m-d H:i:s')) : null;
                
                if ($id) {
                    // Update
                    $stmt = $pdo->prepare("UPDATE blog_posts SET title = ?, slug = ?, content = ?, excerpt = ?, status = ?, is_active = ?, updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$title, $slug, $content, $excerpt, $status, $is_active, $id]);
                    set_flash_message('Post updated successfully!', 'success');
                } else {
                    // Insert
                    $stmt = $pdo->prepare("INSERT INTO blog_posts (title, slug, content, excerpt, author_id, status, is_active, published_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
                    $stmt->execute([$title, $slug, $content, $excerpt, $author_id, $status, $is_active, $published_at]);
                    set_flash_message('Post created successfully!', 'success');
                }
            } catch (PDOException $e) {
                if ($e->getCode() == 23000) {
                    set_flash_message('Post slug already exists.', 'error');
                } else {
                    set_flash_message('Failed to save post.', 'error');
                }
            }
        }
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Get posts
$posts = get_blog_posts(50);

// Get post for edit
$edit_post = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM blog_posts WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_post = $stmt->fetch();
}

include __DIR__ . '/includes/header.php';
?>

<div class="admin-content">
    <div class="admin-header d-flex justify-content-between align-items-center">
        <h1><i class="fas fa-blog me-2"></i>Blog</h1>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#postModal">
            <i class="fas fa-plus me-2"></i>Add Post
        </button>
    </div>
    
    <!-- Posts Table -->
    <div class="card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Title</th>
                            <th>Author</th>
                            <th>Status</th>
                            <th>Published</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($posts as $post): ?>
                        <tr>
                            <td>
                                <strong><?php echo sanitize($post['title']); ?></strong>
                                <?php if ($post['excerpt']): ?>
                                <small class="d-block text-muted"><?php echo truncate($post['excerpt'], 50); ?></small>
                                <?php endif; ?>
                            </td>
                            <td><?php echo sanitize($post['author_name'] ?? 'Unknown'); ?></td>
                            <td>
                                <span class="badge bg-<?php 
                                    echo match($post['status']) {
                                        'published' => 'success',
                                        'draft' => 'warning',
                                        default => 'secondary'
                                    };
                                ?>">
                                    <?php echo ucfirst($post['status']); ?>
                                </span>
                            </td>
                            <td><?php echo $post['published_at'] ? format_date($post['published_at']) : '-'; ?></td>
                            <td>
                                <a href="<?php echo BASE_URL; ?>/blog-post.php?slug=<?php echo $post['slug']; ?>" target="_blank" class="btn btn-sm btn-info" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="?edit=<?php echo $post['id']; ?>" class="btn btn-sm btn-primary" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="?delete=<?php echo $post['id']; ?>" class="btn btn-sm btn-danger confirm-delete" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Post Modal -->
<div class="modal fade" id="postModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content bg-dark">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo $edit_post ? 'Edit Post' : 'Add Post'; ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <?php echo csrf_field(); ?>
                    
                    <?php if ($edit_post): ?>
                    <input type="hidden" name="id" value="<?php echo $edit_post['id']; ?>">
                    <?php endif; ?>
                    
                    <div class="mb-3">
                        <label class="form-label">Title <span class="text-danger">*</span></label>
                        <input type="text" name="title" class="form-control" 
                               value="<?php echo $edit_post ? sanitize($edit_post['title']) : ''; ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Slug</label>
                        <input type="text" name="slug" class="form-control" 
                               value="<?php echo $edit_post ? sanitize($edit_post['slug']) : ''; ?>"
                               placeholder="auto-generated-from-title">
                        <small class="text-muted">Leave empty to auto-generate from title</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Content</label>
                        <textarea name="content" class="form-control" rows="10"><?php echo $edit_post ? htmlspecialchars($edit_post['content']) : ''; ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Excerpt</label>
                        <textarea name="excerpt" class="form-control" rows="2"><?php echo $edit_post ? sanitize($edit_post['excerpt']) : ''; ?></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <option value="draft" <?php echo ($edit_post && $edit_post['status'] === 'draft') ? 'selected' : ''; ?>>Draft</option>
                                <option value="published" <?php echo ($edit_post && $edit_post['status'] === 'published') ? 'selected' : ''; ?>>Published</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" name="is_active" id="is_active" 
                               <?php echo (!$edit_post || $edit_post['is_active']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="is_active">Active</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><?php echo $edit_post ? 'Update' : 'Add'; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php if ($edit_post): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var modal = new bootstrap.Modal(document.getElementById('postModal'));
    modal.show();
});
</script>
<?php endif; ?>

<?php include __DIR__ . '/includes/footer.php'; ?>
