<?php

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

// Allow: admin, subadmin, or editor with manage_blogs permission
$isAdmin = isset($_SESSION['is_admin']) && $_SESSION['is_admin'] === true;
$isSubadmin = isset($_SESSION['is_subadmin']) && $_SESSION['is_subadmin'] === true;
$editorPerms = $_SESSION['editor_permissions'] ?? [];
$isEditorWithBlog = (isset($editorPerms['manage_blogs']) && $editorPerms['manage_blogs'] !== 'none');
if (!$isAdmin && !$isSubadmin && !$isEditorWithBlog) {
    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>
    <?php
    session_start();
    // Access control: Only allow admins, subadmins, or editors with permission
    if (!isset($_SESSION['is_admin']) && !isset($_SESSION['is_subadmin']) && !isset($_SESSION['is_editor'])) {
        header('Location: admin_login.php');
        exit();
    }
    // If editor, check for permission (must have manage_posts set to "editor")
    if (isset($_SESSION['is_editor']) && $_SESSION['is_editor']) {
        $editor_permissions = isset($_SESSION['editor_permissions']) ? $_SESSION['editor_permissions'] : [];
        if (!isset($editor_permissions['manage_posts']) || $editor_permissions['manage_posts'] !== 'editor') {
            header('Location: admin_dashboard.php');
            exit();
        }
    }
    // If subadmin, check for permission (optional, if you want to restrict subadmins)
    // If you want subadmins to always have access, you can skip this check
    ?>
    <style>
        body {
            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>
            <?php
            $dashboardUrl = 'admin_dashboard.php';
            if (!empty($_SESSION['is_admin']) || (!empty($_SESSION['user_type']) && $_SESSION['user_type'] === 'admin')) {
                $dashboardUrl = 'admin_dashboard.php';
            } elseif (!empty($_SESSION['is_subadmin'])) {
                $dashboardUrl = 'subadmin_dashboard.php';
            } elseif (!empty($_SESSION['is_editor'])) {
                $dashboardUrl = 'subadmin_dashboard.php';
            }
            ?>

<?php
// Default link
$dashboardLink = "admin_dashboard.php";

// Adjust based on role
if (isset($_SESSION['role'])) {
    switch ($_SESSION['role']) {
        case 'admin':
            $dashboardLink = "admin_dashboard.php";
            break;
        case 'subadmin':
            $dashboardLink = "subadmin_dashboard.php";
            break;
        case 'editor':
            $dashboardLink = "subadmin_dashboard.php";
            break;
        default:
            $dashboardLink = "admin_dashboard.php"; // fallback
    }
}
?>

<a href="<?php echo $dashboardLink; ?>" class="back-btn">← Back to Dashboard</a>

<style>
.back-btn {
    background-color: orange;
    color: white;
    padding: 8px 14px;
    text-decoration: none;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
}
.back-btn:hover {
    background-color: darkorange;
}
</style>
            <!-- <a href="<?php echo htmlspecialchars($dashboardUrl); ?>" 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?');"></a>
                                    -->
                                   <?php
session_start(); // ensure session is active
$role = isset($_SESSION['role']) ? $_SESSION['role'] : '';

if ($role === 'admin' || $role === 'subadmin') {
    // Show delete button only for admin and subadmin
    echo '<button class="btn" type="submit" style="background:#999;">Delete</button>';
}
// If editor, nothing is echoed → button is hidden
?>

                                   
                                    </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
?>
