<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

// Handle form submission
$error = '';
$success = '';

// Create new post
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_post'])) {
    $title = trim($_POST['title'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    $excerpt = trim($_POST['excerpt'] ?? '');
    $content = $_POST['content'] ?? '';
    $category_id = $_POST['category_id'] ?? null;
    $status = $_POST['status'] ?? 'draft';
    $is_featured = isset($_POST['is_featured']) ? 1 : 0;
    $tags = trim($_POST['tags'] ?? '');
    
    // Validate form data
    if (empty($title) || empty($content) || !$category_id) {
        $error = "Title, content, and category are required.";
    } else {
        try {
            // Start transaction
            $pdo->beginTransaction();
            
            // Create slug if not provided
            if (empty($slug)) {
                $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));
            }
            
            // Check if slug is unique
            $check_slug = $pdo->prepare("SELECT COUNT(*) FROM blog_posts WHERE slug = ?");
            $check_slug->execute([$slug]);
            if ($check_slug->fetchColumn() > 0) {
                $slug = $slug . '-' . time();
            }
            
            // Insert post
            $stmt = $pdo->prepare("INSERT INTO blog_posts (
                title, slug, excerpt, content, category_id, author_id, status, is_featured, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
            
            $stmt->execute([
                $title, $slug, $excerpt, $content, $category_id, $_SESSION['user_id'], $status, $is_featured
            ]);
            
            $post_id = $pdo->lastInsertId();
            
            // Handle featured image upload
            if (isset($_FILES['featured_image']) && $_FILES['featured_image']['name']) {
                $upload_dir = 'uploads/blog/';
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                
                $file_name = $_FILES['featured_image']['name'];
                $file_tmp = $_FILES['featured_image']['tmp_name'];
                $file_size = $_FILES['featured_image']['size'];
                $file_error = $_FILES['featured_image']['error'];
                
                if ($file_error === UPLOAD_ERR_OK && $file_size <= 5 * 1024 * 1024) {
                    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                    $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];
                    
                    if (in_array($file_ext, $allowed_exts)) {
                        $unique_name = 'post_' . $post_id . '_' . time() . '.' . $file_ext;
                        $file_path = $upload_dir . $unique_name;
                        
                        if (move_uploaded_file($file_tmp, $file_path)) {
                            // Update post with featured image
                            $pdo->prepare("UPDATE blog_posts SET featured_image = ? WHERE id = ?")
                                ->execute([$file_path, $post_id]);
                        }
                    }
                }
            }
            
            // Handle tags
            if (!empty($tags)) {
                $tag_array = array_map('trim', explode(',', $tags));
                foreach ($tag_array as $tag) {
                    if (!empty($tag)) {
                        // Check if tag exists
                        $check_tag = $pdo->prepare("SELECT id FROM blog_tags WHERE tag = ?");
                        $check_tag->execute([$tag]);
                        $tag_data = $check_tag->fetch();
                        
                        if (!$tag_data) {
                            // Create new tag
                            $pdo->prepare("INSERT INTO blog_tags (tag, created_at) VALUES (?, NOW())")
                                ->execute([$tag]);
                            $tag_id = $pdo->lastInsertId();
                        } else {
                            $tag_id = $tag_data['id'];
                        }
                        
                        // Link tag to post
                        $pdo->prepare("INSERT INTO post_tags (post_id, tag_id) VALUES (?, ?)")
                            ->execute([$post_id, $tag_id]);
                    }
                }
            }
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "blog_post_created",
                "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} created blog post: {$title}"
            ]);
            
            // Commit transaction
            $pdo->commit();
            
            $success = "Blog post created successfully!";
            header('Location: admin-blog-posts.php?success=created');
            exit;
            
        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Failed to create blog post. Please try again. Error: " . $e->getMessage();
        }
    }
}

// Update post status
if (isset($_GET['publish']) || isset($_GET['unpublish'])) {
    $post_id = $_GET['publish'] ?? $_GET['unpublish'];
    $status = isset($_GET['publish']) ? 'published' : 'draft';
    
    try {
        $stmt = $pdo->prepare("UPDATE blog_posts SET status = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$status, $post_id]);
        
        // Log the activity
        $pdo->prepare("INSERT INTO activities (
            user_id, activity_type, description, created_at
        ) VALUES (?, ?, ?, NOW())")->execute([
            $_SESSION['user_id'],
            "blog_post_status_changed",
            "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} changed post status to {$status}"
        ]);
        
        $success = "Post status updated successfully!";
        header('Location: admin-blog-posts.php?success=status');
        exit;
        
    } catch (Exception $e) {
        $error = "Failed to update post status.";
    }
}

// Delete post
if (isset($_GET['delete_post'])) {
    $post_id = $_GET['delete_post'];
    
    try {
        // Start transaction
        $pdo->beginTransaction();
        
        // Delete post tags
        $pdo->prepare("DELETE FROM post_tags WHERE post_id = ?")->execute([$post_id]);
        
        // Delete post
        $stmt = $pdo->prepare("DELETE FROM blog_posts WHERE id = ?");
        $stmt->execute([$post_id]);
        
        // Log the activity
        $pdo->prepare("INSERT INTO activities (
            user_id, activity_type, description, created_at
        ) VALUES (?, ?, ?, NOW())")->execute([
            $_SESSION['user_id'],
            "blog_post_deleted",
            "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} deleted blog post ID: {$post_id}"
        ]);
        
        // Commit transaction
        $pdo->commit();
        
        $success = "Blog post deleted successfully!";
        header('Location: admin-blog-posts.php?success=deleted');
        exit;
        
    } catch (Exception $e) {
        $pdo->rollback();
        $error = "Failed to delete blog post. Please try again.";
    }
}

// Get blog posts with proper joins
try {
    $sql = "SELECT bp.*, c.name as category_name, 
                   u.first_name, u.last_name
            FROM blog_posts bp
            JOIN categories c ON bp.category_id = c.id
            JOIN users u ON bp.author_id = u.id";
    
    $conditions = [];
    $params = [];
    
    // Filter by status
    $status_filter = $_GET['status'] ?? '';
    if ($status_filter) {
        $conditions[] = "bp.status = ?";
        $params[] = $status_filter;
    }
    
    // Search
    $search = $_GET['search'] ?? '';
    if ($search) {
        $conditions[] = "(bp.title LIKE ? OR bp.excerpt LIKE ? OR bp.content LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }
    
    if ($conditions) {
        $sql .= " WHERE " . implode(" AND ", $conditions);
    }
    
    $sql .= " ORDER BY bp.created_at DESC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get stats
    $stats = [
        'total' => $pdo->query("SELECT COUNT(*) FROM blog_posts")->fetchColumn(),
        'published' => $pdo->query("SELECT COUNT(*) FROM blog_posts WHERE status = 'published'")->fetchColumn(),
        'draft' => $pdo->query("SELECT COUNT(*) FROM blog_posts WHERE status = 'draft'")->fetchColumn(),
    ];
    
    // Get categories for filter
    $stmt = $pdo->query("SELECT * FROM categories ORDER BY name");
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $error = "Database error: " . $e->getMessage();
    $posts = [];
    $stats = ['total' => 0, 'published' => 0, 'draft' => 0];
    $categories = [];
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Manage Blog Posts - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .stat-card {
            border-left: 5px solid #3fb7fe;
            margin-bottom: 20px;
        }
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9em;
        }
        .status-draft {
            background: #ffc107;
            color: #1a1a1a;
        }
        .status-published {
            background: #28a745;
            color: white;
        }
        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        .table td {
            vertical-align: middle;
        }
        .table img {
            height: 40px;
            width: 40px;
            object-fit: cover;
            border-radius: 5px;
        }
        .featured-badge {
            background: #3fb7fe;
            color: white;
            padding: 3px 8px;
            border-radius: 15px;
            font-size: 0.8em;
        }
        .author-name {
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <?php include 'admin-navbar.php'; ?>
    
    <div class="container py-5">
        <div class="section-title position-relative mb-4">
            <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Content Management</h6>
            <h1 class="display-5">Manage Blog Posts</h1>
        </div>
        
        <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        
        <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>
        
        <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success">
            <?php if ($_GET['success'] == 'created'): ?>
            Blog post created successfully!
            <?php elseif ($_GET['success'] == 'updated'): ?>
            Blog post updated successfully!
            <?php elseif ($_GET['success'] == 'deleted'): ?>
            Blog post deleted successfully!
            <?php elseif ($_GET['success'] == 'status'): ?>
            Post status updated successfully!
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
        <!-- Stats -->
        <div class="row mb-4">
            <div class="col-md-3 mb-3">
                <div class="stat-card">
                    <div class="card-body">
                        <h6>Total Posts</h6>
                        <h3><?= $stats['total'] ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stat-card" style="border-left-color: #28a745;">
                    <div class="card-body">
                        <h6>Published</h6>
                        <h3><?= $stats['published'] ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stat-card" style="border-left-color: #ffc107;">
                    <div class="card-body">
                        <h6>Draft</h6>
                        <h3><?= $stats['draft'] ?></h3>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Search and Filter -->
        <div class="row mb-4">
            <div class="col-lg-8">
                <form method="GET" class="d-flex">
                    <div class="flex-grow-1 mr-2">
                        <input type="text" name="search" class="form-control" placeholder="Search by title, excerpt, or content" value="<?= htmlspecialchars($search ?? '') ?>">
                    </div>
                    <button type="submit" class="btn btn-primary">Search</button>
                </form>
            </div>
            <div class="col-lg-4">
                <div class="row">
                    <div class="col-md-6 mb-2">
                        <select name="status" class="form-control" onchange="window.location='admin-blog-posts.php?status='+this.value<?= $search ? '&search='.urlencode($search) : '' ?>">
                            <option value="">All Statuses</option>
                            <option value="published" <?= $status_filter === 'published' ? 'selected' : '' ?>>Published</option>
                            <option value="draft" <?= $status_filter === 'draft' ? 'selected' : '' ?>>Draft</option>
                        </select>
                    </div>
                    <div class="col-md-6 mb-2">
                        <button type="button" class="btn btn-primary btn-block" data-toggle="modal" data-target="#createPostModal">Create Post</button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Posts Table -->
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Author</th>
                        <th>Category</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($posts)): ?>
                    <tr>
                        <td colspan="6" class="text-center">No blog posts found.</td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($posts as $post): ?>
                    <tr>
                        <td style="max-width: 300px;">
                            <div class="d-flex align-items-center">
                                <?php if ($post['featured_image']): ?>
                                <img src="<?= htmlspecialchars($post['featured_image']) ?>" alt="<?= htmlspecialchars($post['title']) ?>">
                                <?php else: ?>
                                <div style="width: 40px; height: 40px; background: #eee; border-radius: 5px;"></div>
                                <?php endif; ?>
                                <div class="ml-3">
                                    <?= htmlspecialchars($post['title']) ?>
                                    <?php if ($post['is_featured']): ?>
                                    <span class="featured-badge ml-2">Featured</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </td>
                        <td class="author-name"><?= htmlspecialchars($post['first_name'] . ' ' . htmlspecialchars($post['last_name']) ?></td>
                        <td><?= htmlspecialchars($post['category_name']) ?></td>
                        <td>
                            <span class="status-badge status-<?= strtolower($post['status']) ?>">
                                <?= ucfirst($post['status']) ?>
                            </span>
                        </td>
                        <td><?= date('M j, Y', strtotime($post['created_at'])) ?></td>
                        <td>
                            <div class="btn-group">
                                <a href="admin-edit-blog.php?id=<?= $post['id'] ?>" class="btn btn-sm btn-primary">Edit</a>
                                <?php if ($post['status'] === 'draft'): ?>
                                <a href="admin-blog-posts.php?publish=<?= $post['id'] ?>" class="btn btn-sm btn-success" onclick="return confirm('Are you sure you want to publish this post?')">Publish</a>
                                <?php else: ?>
                                <a href="admin-blog-posts.php?unpublish=<?= $post['id'] ?>" class="btn btn-sm btn-warning" onclick="return confirm('Are you sure you want to unpublish this post?')">Unpublish</a>
                                <?php endif; ?>
                                <button class="btn btn-sm btn-danger" onclick="confirmDelete(<?= $post['id'] ?>)">Delete</button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Create Post Modal -->
    <div class="modal fade" id="createPostModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Create New Blog Post</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="POST" enctype="multipart/form-data">
                    <div class="modal-body">
                        <div class="form-group">
                            <label>Title *</label>
                            <input type="text" name="title" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label>Slug (URL)</label>
                            <input type="text" name="slug" class="form-control" placeholder="auto-generated from title if empty">
                            <small class="form-text text-muted">This will be part of the URL (e.g., yourdomain.com/blog/slug)</small>
                        </div>
                        <div class="form-group">
                            <label>Excerpt</label>
                            <textarea name="excerpt" class="form-control" rows="3" placeholder="Brief summary of the post"></textarea>
                        </div>
                        <div class="form-group">
                            <label>Content *</label>
                            <textarea name="content" class="form-control" rows="10" required></textarea>
                        </div>
                        <div class="form-group">
                            <label>Featured Image</label>
                            <div class="custom-file">
                                <input type="file" name="featured_image" class="custom-file-input" accept="image/*">
                                <label class="custom-file-label">Choose image...</label>
                            </div>
                            <small class="form-text text-muted">JPG, PNG (max 5MB)</small>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label>Category *</label>
                                <select name="category_id" class="form-control" required>
                                    <option value="">Select Category</option>
                                    <?php foreach ($categories as $category): ?>
                                    <option value="<?= $category['id'] ?>"><?= htmlspecialchars($category['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>Status</label>
                                <select name="status" class="form-control">
                                    <option value="draft">Draft</option>
                                    <option value="published">Published</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" name="is_featured" id="is_featured">
                                <label class="custom-control-label" for="is_featured">Mark as Featured Post</label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>Tags</label>
                            <input type="text" name="tags" class="form-control" placeholder="scholarships, usa, 2023 (comma separated)">
                            <small class="form-text text-muted">Separate tags with commas</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" name="create_post" class="btn btn-primary">Create Post</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'footer.php'; ?>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
    <script>
        // Update custom file input label
        $('.custom-file-input').on('change', function() {
            let fileName = $(this).val().split('\\').pop();
            $(this).next('.custom-file-label').addClass("selected").html(fileName);
        });
        
        function confirmDelete(postId) {
            if (confirm('Are you sure you want to delete this blog post? This action cannot be undone.')) {
                window.location.href = 'admin-blog-posts.php?delete_post=' + postId;
            }
        }
    </script>
</body>
</html>