<?php
// Define admin access constant
define('ADMIN_ACCESS', true);

session_start();
require_once '../config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$pdo = getDBConnection();

// Create blog_posts table if it doesn't exist
try {
    $createTableSQL = "
    CREATE TABLE IF NOT EXISTS blog_posts (
        id INT PRIMARY KEY AUTO_INCREMENT,
        title VARCHAR(255) NOT NULL,
        content TEXT NOT NULL,
        excerpt TEXT,
        category VARCHAR(100) DEFAULT 'General',
        image_url VARCHAR(500),
        is_active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )";
    
    $pdo->exec($createTableSQL);
} catch (Exception $e) {
    error_log("Failed to create blog_posts table: " . $e->getMessage());
}

// Handle form submissions
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create_post':
                $title = trim($_POST['title']);
                $content = trim($_POST['content']);
                $excerpt = trim($_POST['excerpt']);
                $category = trim($_POST['category']);
                $image_url = trim($_POST['image_url']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                if (empty($title) || empty($content)) {
                    $message = 'Title and content are required.';
                    $message_type = 'error';
                } else {
                    if (empty($excerpt)) {
                        $excerpt = substr(strip_tags($content), 0, 200) . '...';
                    }
                    
                    try {
                        $stmt = $pdo->prepare("
                            INSERT INTO blog_posts (title, content, excerpt, category, image_url, is_active) 
                            VALUES (?, ?, ?, ?, ?, ?)
                        ");
                        $stmt->execute([$title, $content, $excerpt, $category, $image_url, $is_active]);
                        $message = 'Blog post created successfully!';
                        $message_type = 'success';
                    } catch (Exception $e) {
                        $message = 'Error creating blog post: ' . $e->getMessage();
                        $message_type = 'error';
                    }
                }
                break;
        }
    }
}

// Get all blog posts
$stmt = $pdo->query("SELECT * FROM blog_posts ORDER BY created_at DESC");
$blog_posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blog Management - Astro Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .sidebar {
            min-height: 100vh;
            background-color: #343a40;
        }
        .content-area {
            margin-left: 250px;
            padding: 20px;
        }
        .blog-card {
            transition: transform 0.2s;
        }
        .blog-card:hover {
            transform: translateY(-2px);
        }
        .status-badge {
            font-size: 0.75rem;
        }
        @media (max-width: 768px) {
            .content-area {
                margin-left: 0;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0">
                <div class="sidebar p-3">
                    <div class="text-center mb-4">
                        <h4 class="text-warning">
                            <i class="fas fa-star"></i> ASTRO ADMIN
                        </h4>
                    </div>
                    
                    <nav class="nav flex-column">
                        <a class="nav-link text-light" href="index.php">
                            <i class="fas fa-tachometer-alt me-2"></i> Dashboard
                        </a>
                        <a class="nav-link text-light" href="users.php">
                            <i class="fas fa-users me-2"></i> Users
                        </a>
                        <a class="nav-link text-light" href="appointments.php">
                            <i class="fas fa-calendar-check me-2"></i> Appointments
                        </a>
                        <a class="nav-link text-light active" href="blog_management.php">
                            <i class="fas fa-blog me-2"></i> Blog Management
                        </a>
                        <a class="nav-link text-light" href="settings.php">
                            <i class="fas fa-cog me-2"></i> Settings
                        </a>
                        <a class="nav-link text-light" href="logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i> Logout
                        </a>
                    </nav>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10">
                <div class="content-area">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-blog me-2"></i>Blog Management</h2>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createPostModal">
                            <i class="fas fa-plus me-2"></i>Create New Post
                        </button>
                    </div>

                    <!-- Messages -->
                    <?php if (!empty($message)): ?>
                        <div class="alert alert-<?php echo $message_type == 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show" role="alert">
                            <?php echo htmlspecialchars($message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Blog Posts Grid -->
                    <div class="row">
                        <?php if (empty($blog_posts)): ?>
                            <div class="col-12">
                                <div class="text-center py-5">
                                    <i class="fas fa-blog fa-3x text-muted mb-3"></i>
                                    <h4 class="text-muted">No blog posts found</h4>
                                    <p class="text-muted">Create your first blog post to get started!</p>
                                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createPostModal">
                                        <i class="fas fa-plus me-2"></i>Create First Post
                                    </button>
                                </div>
                            </div>
                        <?php else: ?>
                            <?php foreach ($blog_posts as $post): ?>
                                <div class="col-md-6 col-lg-4 mb-4">
                                    <div class="card blog-card h-100">
                                        <div class="card-body d-flex flex-column">
                                            <div class="d-flex justify-content-between align-items-start mb-2">
                                                <span class="badge bg-primary"><?php echo htmlspecialchars($post['category']); ?></span>
                                                <span class="badge status-badge <?php echo $post['is_active'] ? 'bg-success' : 'bg-secondary'; ?>">
                                                    <?php echo $post['is_active'] ? 'Active' : 'Inactive'; ?>
                                                </span>
                                            </div>
                                            <h5 class="card-title"><?php echo htmlspecialchars($post['title']); ?></h5>
                                            <p class="card-text flex-grow-1"><?php echo htmlspecialchars($post['excerpt']); ?></p>
                                            <div class="mt-auto">
                                                <small class="text-muted">
                                                    <i class="fas fa-calendar me-1"></i>
                                                    <?php echo date('M d, Y', strtotime($post['created_at'])); ?>
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Create Post Modal -->
    <div class="modal fade" id="createPostModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Create New Blog Post</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="create_post">
                        
                        <div class="row">
                            <div class="col-md-8 mb-3">
                                <label for="title" class="form-label">Title *</label>
                                <input type="text" class="form-control" id="title" name="title" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="category" class="form-label">Category</label>
                                <input type="text" class="form-control" id="category" name="category" value="General">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="excerpt" class="form-label">Excerpt</label>
                            <textarea class="form-control" id="excerpt" name="excerpt" rows="2"></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="content" class="form-label">Content *</label>
                            <textarea class="form-control" id="content" name="content" rows="10" required></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="image_url" class="form-label">Image URL</label>
                            <input type="url" class="form-control" id="image_url" name="image_url">
                        </div>
                        
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="is_active" name="is_active" checked>
                            <label class="form-check-label" for="is_active">
                                Active (visible in app)
                            </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">Create Post</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
