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

$error = '';
$success = '';
$upload_dir = 'uploads/blog/';

// Create upload directory if it doesn't exist
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

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

// Handle blog post creation
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']) {
                $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 {$admin['first_name']} {$admin['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.";
        }
    }
}

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Create 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>
        .form-section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        .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;
            transition: all 0.3s;
        }
        .file-upload:hover {
            border-color: #3fb7fe;
            background: #f8f9fa;
        }
        .file-input {
            display: none;
        }
        .preview-image {
            max-width: 100%;
            max-height: 150px;
            margin-top: 10px;
            border-radius: 5px;
            display: none;
        }
        .upload-info {
            margin-top: 10px;
            font-size: 0.8em;
            color: #666;
        }
    </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">Create New Blog Post</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; ?>
        
        <form method="POST" enctype="multipart/form-data">
            <!-- Post Information -->
            <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" 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>
            
            <!-- Content -->
            <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></textarea>
                </div>
            </div>
            
            <!-- Media & SEO -->
            <div class="form-section">
                <h5 class="section-title">Media & SEO</h5>
                <div class="form-group">
                    <label>Featured Image</label>
                    <div class="file-upload" id="imageUpload">
                        <i class="fas fa-file-upload fa-3x mb-3" style="color: #3fb7fe;"></i>
                        <h6>Upload Featured Image</h6>
                        <p class="text-muted small">JPG, PNG, GIF (max 5MB)</p>
                        <img id="imagePreview" class="preview-image" alt="Image preview">
                        <input type="file" name="featured_image" id="imageFile" class="file-input" accept="image/*">
                        <div class="upload-info" id="uploadInfo"></div>
                    </div>
                </div>
            </div>
            
            <!-- Settings -->
            <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'] ?>"><?= 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>
                            <option value="scheduled">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">
                        <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>
            
            <!-- Form Submission -->
            <div class="text-center">
                <button type="submit" name="create_post" class="btn btn-primary btn-lg px-5">Create Post</button>
                <a href="admin-blog-posts.php" class="btn btn-outline-secondary ml-2">Cancel</a>
            </div>
        </form>
    </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) {
                // Display file info
                document.getElementById('uploadInfo').innerHTML = `
                    <strong>File:</strong> ${file.name} <br>
                    <strong>Size:</strong> ${(file.size / 1024 / 1024).toFixed(2)} MB <br>
                    <strong>Type:</strong> ${file.type}
                `;
                
                // Show image preview if it's an image
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        document.getElementById('imagePreview').src = e.target.result;
                        document.getElementById('imagePreview').style.display = 'block';
                        document.getElementById('imageUpload').querySelectorAll('i, h6, p').forEach(el => {
                            el.style.display = 'none';
                        });
                    };
                    reader.readAsDataURL(file);
                }
            }
        });
        
        // 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>