<?php
session_start();
require_once 'db_config.php';
require_once 'blog_helpers.php';

// Check if user is admin
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    header('Location: admin_login.php');
    exit;
}

$message = '';
$msgType = '';

// Check if blogs table exists
$result = $conn->query("SHOW TABLES LIKE 'blogs'");
$blogsTableExists = $result && $result->num_rows > 0;

if (!$blogsTableExists) {
    $message = 'Blog module not yet set up. Please run setup: <a href="run_blog_migration.php" style="color: #007bff; font-weight: bold;">Setup Now</a>';
    $msgType = 'error';
    $blogs = [];
    $totalPages = 0;
} else {
    // Handle delete
    $action = $_GET['action'] ?? '';
    if ($action === 'delete' && isset($_GET['id'])) {
        $blogId = $_GET['id'];
        if (deleteBlog($blogId, $conn)) {
            $message = 'Blog deleted successfully!';
            $msgType = 'success';
        } else {
            $message = 'Failed to delete blog';
            $msgType = 'error';
        }
    }

    // Pagination
    $page = $_GET['page'] ?? 1;
    $limit = 10;
    $offset = ($page - 1) * $limit;

    // Get filters
    $filters = [
        'include_drafts' => true,
        'limit' => $limit,
        'offset' => $offset,
        'order' => 'b.created_at DESC'
    ];

    // Get total count (with all drafts included)
    $countQuery = "SELECT COUNT(DISTINCT b.id) as total FROM blogs b";
    $totalBlogs = $conn->query($countQuery)->fetch_assoc()['total'];
    $totalPages = ceil($totalBlogs / $limit);

    // Get blogs
    $blogs = getBlogs($conn, $filters);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Blogs - Admin</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f5f5;
            color: #333;
        }
        
        .admin-header {
            background: white;
            border-bottom: 3px solid #c76b8a;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .admin-header h1 {
            color: #c76b8a;
            font-size: 24px;
            margin: 0;
        }
        
        .main-content {
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .message {
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .add-btn {
            background: #c76b8a;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            font-weight: 600;
            display: inline-block;
        }
        
        .add-btn:hover {
            background: #b35975;
        }
        
        .table-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        thead {
            background: #ecf0f1;
            border-bottom: 2px solid #bdc3c7;
        }
        
        th {
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: #2c3e50;
        }
        
        td {
            padding: 15px;
            border-bottom: 1px solid #ecf0f1;
        }
        
        tbody tr:hover {
            background: #f8f9fa;
        }
        
        .status-badge {
            display: inline-block;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .status-published {
            background: #d4edda;
            color: #155724;
        }
        
        .status-draft {
            background: #fff3cd;
            color: #856404;
        }
        
        .actions {
            display: flex;
            gap: 10px;
        }
        
        .btn-small {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            text-decoration: none;
            display: inline-block;
            transition: all 0.3s;
        }
        
        .btn-edit {
            background: #c76b8a;
            color: white;
        }
        
        .btn-edit:hover {
            background: #b35975;
        }
        
        .btn-delete {
            background: #e74c3c;
            color: white;
        }
        
        .btn-delete:hover {
            background: #c0392b;
        }
        
        .btn-view {
            background: #95a5a6;
            color: white;
        }
        
        .btn-view:hover {
            background: #7f8c8d;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            gap: 5px;
            margin-top: 20px;
            flex-wrap: wrap;
        }
        
        .pagination a, .pagination span {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-decoration: none;
            color: #c76b8a;
            display: inline-block;
        }
        
        .pagination a:hover {
            background: #f5e6ed;
        }
        
        .pagination .current {
            background: #c76b8a;
            color: white;
            border-color: #c76b8a;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .empty-state h3 {
            margin-bottom: 10px;
        }
        
        @media (max-width: 768px) {
            table {
                font-size: 13px;
            }
            
            th, td {
                padding: 10px;
            }
            
            .actions {
                flex-wrap: wrap;
            }
        }
    </style>
</head>
<body>
    <div class="admin-header">
        <h1>Manage Blog Posts</h1>
        <div style="display: flex; gap: 10px;">
            <a href="admin_add_blog.php" class="add-btn">+ Add New Blog</a>
            <a href="admin_dashboard.php" class="add-btn">← Back to Dashboard</a>
        </div>
    </div>
    
    <div class="main-content">
        <?php if (!empty($message)): ?>
            <div class="message <?php echo $msgType; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>
        
        <div class="table-container">
            <?php if (!empty($blogs)): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Title</th>
                            <th>Category</th>
                            <th>Status</th>
                            <th>Author</th>
                            <th>Publish Date</th>
                            <th>Views</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($blogs as $blog): ?>
                            <tr>
                                <td>
                                    <strong><?php echo htmlspecialchars(substr($blog['title'], 0, 50)); ?></strong>
                                    <?php if (strlen($blog['title']) > 50): ?>
                                        ...
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($blog['category_name'] ?? 'N/A'); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $blog['status']; ?>">
                                        <?php echo ucfirst($blog['status']); ?>
                                    </span>
                                </td>
                                <td><?php echo htmlspecialchars($blog['author_name'] ?? 'Unknown'); ?></td>
                                <td>
                                    <?php 
                                        if ($blog['publish_date']) {
                                            echo date('Y-m-d H:i', strtotime($blog['publish_date']));
                                        } else {
                                            echo 'Immediate';
                                        }
                                    ?>
                                </td>
                                <td><?php echo $blog['views']; ?></td>
                                <td>
                                    <div class="actions">
                                        <a href="admin_edit_blog.php?id=<?php echo $blog['id']; ?>" class="btn-small btn-edit">Edit</a>
                                        <a href="blog.php?slug=<?php echo htmlspecialchars($blog['slug']); ?>" class="btn-small btn-view" target="_blank">View</a>
                                        <a href="?action=delete&id=<?php echo $blog['id']; ?>" class="btn-small btn-delete" onclick="return confirm('Are you sure you want to delete this blog?');">Delete</a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                
                <?php if ($totalPages > 1): ?>
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                            <a href="?page=1">First</a>
                            <a href="?page=<?php echo $page - 1; ?>">Previous</a>
                        <?php endif; ?>
                        
                        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                            <?php if ($i === (int)$page): ?>
                                <span class="current"><?php echo $i; ?></span>
                            <?php else: ?>
                                <a href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                            <?php endif; ?>
                        <?php endfor; ?>
                        
                        <?php if ($page < $totalPages): ?>
                            <a href="?page=<?php echo $page + 1; ?>">Next</a>
                            <a href="?page=<?php echo $totalPages; ?>">Last</a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            <?php else: ?>
                <div class="empty-state">
                    <h3>No Blog Posts Found</h3>
                    <p>Create your first blog post by clicking the "Add New Blog" button above.</p>
                    <a href="admin_add_blog.php" class="add-btn" style="margin-top: 15px;">+ Add New Blog</a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
<?php
?>
