<?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.");
}

// Get post ID
$post_id = $_GET['id'] ?? null;

if (!$post_id) {
    die("Post ID is required.");
}

// Get post data with proper joins to get author name
try {
    $sql = "SELECT bp.*, c.name as category_name, 
                   COALESCE(a.first_name, co.first_name, s.first_name) as author_first_name,
                   COALESCE(a.last_name, co.last_name, s.last_name) as author_last_name
            FROM blog_posts bp
            JOIN categories c ON bp.category_id = c.id
            JOIN users u ON bp.author_id = u.id
            LEFT JOIN admins a ON u.id = a.id
            LEFT JOIN counselors co ON u.id = co.id
            LEFT JOIN students s ON u.id = s.id
            WHERE bp.id = ?";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$post_id]);
    $post = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$post) {
        die("Blog post not found.");
    }
} catch(PDOException $e) {
    die("Database error: " . $e->getMessage());
}

// Get categories
$stmt = $pdo->query("SELECT * FROM categories ORDER BY name");
$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get tags for this post
$stmt = $pdo->prepare("SELECT bt.tag 
                      FROM blog_tags bt
                      JOIN post_tags pt ON bt.id = pt.tag_id
                      WHERE pt.post_id = ?");
$stmt->execute([$post_id]);
$post_tags = $stmt->fetchAll(PDO::FETCH_COLUMN);

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_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();
            
            // Check if slug is unique (excluding current post)
            if (!empty($slug)) {
                $check_slug = $pdo->prepare("SELECT COUNT(*) FROM blog_posts WHERE slug = ? AND id != ?");
                $check_slug->execute([$slug, $post_id]);
                if ($check_slug->fetchColumn() > 0) {
                    $error = "Slug already exists. Please choose a different one.";
                    throw new Exception("Slug already exists");
                }
            } else {
                // Generate slug from title if not provided
                $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));
                $check_slug = $pdo->prepare("SELECT COUNT(*) FROM blog_posts WHERE slug = ? AND id != ?");
                $check_slug->execute([$slug, $post_id]);
                if ($check_slug->fetchColumn() > 0) {
                    $slug = $slug . '-' . time();
                }
            }
            
            // Update post
            $stmt = $pdo->prepare("UPDATE blog_posts SET 
                title = ?, slug = ?, excerpt = ?, content = ?, category_id = ?, 
                status = ?, is_featured = ?, updated_at = NOW()
                WHERE id = ?");
            
            $stmt->execute([
                $title, $slug, $excerpt, $content, $category_id, $status, $is_featured, $post_id
            ]);
            
            // 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]);
                        }
                    }
                }
            }
            
            // Clear existing tags
            $pdo->prepare("DELETE FROM post_tags WHERE post_id = ?")->execute([$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_updated",
                "Admin {$admin['first_name']} {$admin['last_name']} updated blog post: {$title}"
            ]);
            
            // Commit transaction
            $pdo->commit();
            
            $success = "Blog post updated successfully!";
            header('Location: admin-blog-posts.php?success=updated');
            exit;
            
        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Failed to update blog post. Please try again.";
        }
    }
}

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Edit Blog Post - 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">
    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.css" rel="stylesheet">
    <style>
        .post-status {
            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;
        }
        .status-scheduled {
            background: #17a2b8;
            color: white;
        }
        .form-section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        .form-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        .section-title {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #3fb7fe;
        }
        .file-upload {
            position: relative;
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
        }
        .file-upload:hover {
            border-color: #3fb7fe;
            background: #f8f9fa;
        }
        .file-input {
            display: none;
        }
        .tag-input {
            display: flex;
            flex-wrap: wrap;
            border: 1px solid #ced4da;
            border-radius: 5px;
            padding: 5px;
            min-height: 40px;
        }
        .tag-input span {
            background: #3fb7fe;
            color: white;
            padding: 5px 10px;
            border-radius: 20px;
            margin: 2px;
            display: inline-flex;
            align-items: center;
        }
        .tag-input span i {
            margin-left: 5px;
            cursor: pointer;
        }
        .tag-input input {
            border: none;
            outline: none;
            flex: 1;
            padding: 5px;
        }
        .current-image {
            margin: 10px 0;
            max-width: 300px;
        }
        .current-image img {
            max-width: 100%;
            border-radius: 5px;
        }
    </style>
</head>
<body>

<?php include 'admin-navbar.php'; ?>

<div class="container-fluid py-5">
    <div class="container py-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1>Edit Blog Post</h1>
            <a href="admin-blog-posts.php" class="btn btn-secondary">Back to Posts</a>
        </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; ?>
        
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="post_id" value="<?= $post['id'] ?>">
            
            <div class="form-section">
                <h5 class="section-title">Post Information</h5>
                <div class="form-group">
                    <label>Title *</label>
                    <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($post['title']) ?>" required>
                </div>
                <div class="form-group">
                    <label>Slug (URL)</label>
                    <input type="text" name="slug" class="form-control" value="<?= htmlspecialchars($post['slug']) ?>" 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"><?= htmlspecialchars($post['excerpt']) ?></textarea>
                </div>
            </div>
            
            <div class="form-section">
                <h5 class="section-title">Content</h5>
                <div class="form-group">
                    <label>Content *</label>
                    <textarea name="content" class="form-control summernote" rows="10" required><?= htmlspecialchars($post['content']) ?></textarea>
                </div>
            </div>
            
            <div class="form-section">
                <h5 class="section-title">Media & SEO</h5>
                <div class="form-group">
                    <label>Featured Image</label>
                    <?php if ($post['featured_image']): ?>
                    <div class="current-image">
                        <img src="<?= htmlspecialchars($post['featured_image']) ?>" alt="Current featured image">
                        <small>Current image</small>
                    </div>
                    <?php endif; ?>
                    <div class="file-upload" id="imageUpload">
                        <i class="fas fa-file-upload fa-3x mb-3" style="color: #3fb7fe;"></i>
                        <h6>Upload New Featured Image</h6>
                        <p class="text-muted small">JPG, PNG (max 5MB)</p>
                        <input type="file" name="featured_image" id="imageFile" class="file-input" accept="image/*">
                    </div>
                </div>
            </div>
            
            <div class="form-section">
                <h5 class="section-title">Settings</h5>
                <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'] ?>" <?= ($category['id'] == $post['category_id']) ? 'selected' : '' ?>>
                                <?= 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" <?= ($post['status'] === 'draft') ? 'selected' : '' ?>>Draft</option>
                            <option value="published" <?= ($post['status'] === 'published') ? 'selected' : '' ?>>Published</option>
                            <option value="scheduled" <?= ($post['status'] === 'scheduled') ? 'selected' : '' ?>>Scheduled</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" <?= $post['is_featured'] ? 'checked' : '' ?>>
                        <label class="custom-control-label" for="is_featured">Mark as Featured Post</label>
                    </div>
                </div>
                <div class="form-group">
                    <label>Tags</label>
                    <div class="tag-input" id="tagInput">
                        <?php foreach ($post_tags as $tag): ?>
                        <span><?= htmlspecialchars($tag) ?><i class="fas fa-times"></i></span>
                        <?php endforeach; ?>
                        <input type="text" placeholder="Add tags..." id="tagText">
                    </div>
                    <input type="hidden" name="tags" id="tagsField" value="<?= htmlspecialchars(implode(',', $post_tags)) ?>">
                    <small class="form-text text-muted">Separate tags with commas</small>
                </div>
            </div>
            
            <div class="text-center">
                <button type="submit" name="update_post" class="btn btn-primary btn-lg px-5">Update Post</button>
            </div>
            
            <div class="text-center mt-3">
                <a href="admin-blog-posts.php" class="btn btn-outline-primary">Cancel</a>
            </div>
        </form>
    </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 src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.js"></script>
<script>
    // Logo upload functionality
    document.getElementById('imageUpload').addEventListener('click', function() {
        document.getElementById('imageFile').click();
    });
    
    document.getElementById('imageFile').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            document.getElementById('imageUpload').innerHTML = `
                <i class="fas fa-file-alt fa-3x mb-3" style="color: #3fb7fe;"></i>
                <h6>${file.name}</h6>
                <p class="text-muted small">${(file.size / 1024 / 1024).toFixed(2)} MB</p>
                <p class="text-success">Ready to upload</p>
            `;
        }
    });
    
    // Tag input functionality
    document.addEventListener('DOMContentLoaded', function() {
        const tagInput = document.getElementById('tagInput');
        const tagText = document.getElementById('tagText');
        const tagsField = document.getElementById('tagsField');
        let tags = <?= json_encode($post_tags) ?>;
        
        function updateTagsField() {
            tagsField.value = tags.join(',');
        }
        
        // Initialize with existing tags
        updateTagsField();
        
        tagText.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' || e.key === ',') {
                e.preventDefault();
                const value = tagText.value.trim();
                if (value && !tags.includes(value)) {
                    tags.push(value);
                    const tagSpan = document.createElement('span');
                    tagSpan.textContent = value;
                    tagSpan.innerHTML += '<i class="fas fa-times"></i>';
                    tagSpan.querySelector('i').addEventListener('click', function() {
                        tags = tags.filter(t => t !== value);
                        tagSpan.remove();
                        updateTagsField();
                    });
                    tagInput.insertBefore(tagSpan, tagText);
                    tagText.value = '';
                    updateTagsField();
                }
            }
        });
        
        // Remove tags when clicking the X
        tagInput.addEventListener('click', function(e) {
            if (e.target.tagName === 'I') {
                const tagSpan = e.target.parentElement;
                const tagValue = tagSpan.textContent.replace('×', '').trim();
                tags = tags.filter(t => t !== tagValue);
                tagSpan.remove();
                updateTagsField();
            }
        });
        
        // Initialize Summernote
        $('.summernote').summernote({
            height: 300,
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'underline', 'clear']],
                ['fontname', ['fontname']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture', 'video']],
                ['view', ['fullscreen', 'codeview', 'help']]
            ]
        });
    });
</script>
</body>
</html>