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

// Check if user is admin
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    header('Location: admin_login.php');
    exit;
}

// Check if blog tables exist
$blogsTableExists = false;
if ($conn) {
    $result = $conn->query("SHOW TABLES LIKE 'blogs'");
    $blogsTableExists = $result && $result->num_rows > 0;
}

if (!$blogsTableExists) {
    $errorMsg = '<style>body{font-family:Arial;margin:40px;background:#f5f5f5;}.container{max-width:600px;margin:0 auto;background:#fff;padding:30px;border-radius:8px;box-shadow:0 2px 4px rgba(0,0,0,0.1);}.warning{background:#fff3cd;color:#856404;padding:15px;border-radius:4px;margin:20px 0;border:1px solid #ffeeba;}.btn{background:#007bff;color:white;padding:10px 20px;border-radius:4px;text-decoration:none;display:inline-block;margin-top:15px;}</style><div class="container"><div class="warning"><h2>⚙️ Setup Required</h2><p>The blog module needs to be initialized first.</p><p><strong>Click below to create database tables:</strong></p><a href="run_blog_migration.php" class="btn">▶ Setup Blog Module</a><br><a href="admin_blogs.php" style="margin-left:10px;">← Back</a></div></div>';
    die($errorMsg);
}

// Get admin ID from user_id - session stores user_id, not admin_id
$adminId = null;
if (isset($_SESSION['user_id'])) {
    $stmt = $conn->prepare("SELECT id FROM admins WHERE user_id = ? LIMIT 1");
    $stmt->bind_param('i', $_SESSION['user_id']);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res && $res->num_rows > 0) {
        $row = $res->fetch_assoc();
        $adminId = $row['id'];
    }
    $stmt->close();
}

if (!$adminId) {
    die('Error: Could not retrieve admin ID. Please log in again.');
}
$message = '';
$msgType = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $slug = generateSlug($title);
    $content = $_POST['content'] ?? '';
    $excerpt = $_POST['excerpt'] ?? '';
    $categoryId = $_POST['category_id'] ?? null;
    $status = $_POST['status'] ?? 'draft';
    $publishDate = $_POST['publish_date'] ?? null;
    $metaTitle = $_POST['meta_title'] ?? '';
    $metaDescription = $_POST['meta_description'] ?? '';
    $showOnHome = isset($_POST['show_on_home']) ? 1 : 0;
    
    // Handle tags - convert comma-separated input to tag IDs
    $tagsInput = $_POST['tags_input'] ?? '';
    $tags = [];
    if (!empty($tagsInput)) {
        $tagNames = array_map('trim', explode(',', $tagsInput));
        foreach ($tagNames as $tagName) {
            if (!empty($tagName)) {
                $tagSlug = generateSlug($tagName);
                // Check if tag exists, if not create it
                $checkTag = $conn->prepare("SELECT id FROM blog_tags WHERE slug = ?");
                $checkTag->bind_param('s', $tagSlug);
                $checkTag->execute();
                $result = $checkTag->get_result();
                if ($result && $result->num_rows > 0) {
                    $tagRow = $result->fetch_assoc();
                    $tags[] = $tagRow['id'];
                } else {
                    // Create new tag
                    $stmt = $conn->prepare("INSERT INTO blog_tags (name, slug) VALUES (?, ?)");
                    $stmt->bind_param('ss', $tagName, $tagSlug);
                    if ($stmt->execute()) {
                        $tags[] = $conn->insert_id;
                    }
                }
            }
        }
    }
    
    // Validation
    $errors = validateBlogInput(['title' => $title, 'content' => $content, 'category_id' => $categoryId]);
    
    // Check slug uniqueness
    if (slugExists($slug, $conn)) {
        $errors[] = 'A blog with this title already exists';
    }
    
    if (empty($errors)) {
        // Handle featured image upload
        $featuredImage = null;
        if (isset($_FILES['featured_image']) && $_FILES['featured_image']['size'] > 0) {
            $uploadResult = uploadBlogImage($_FILES['featured_image']);
            if ($uploadResult['success']) {
                $featuredImage = $uploadResult['filename'];
            } else {
                $errors[] = $uploadResult['message'];
            }
        }
        
        if (empty($errors)) {
            // Get image orientation and size
            $imageOrientation = $_POST['image_orientation'] ?? 'landscape';
            $imageSize = $_POST['image_size'] ?? 'medium';
            
            // Insert blog
            $stmt = $conn->prepare("
                INSERT INTO blogs (title, slug, content, excerpt, featured_image, image_orientation, image_size, category_id, author_id, status, publish_date, meta_title, meta_description, show_on_home)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->bind_param(
                'sssssssississi',
                $title, $slug, $content, $excerpt, $featuredImage, $imageOrientation, $imageSize, $categoryId, $adminId, $status, $publishDate, $metaTitle, $metaDescription, $showOnHome
            );
            
            if ($stmt->execute()) {
                $blogId = $conn->insert_id;
                
                // Save tags
                if (!empty($tags) && is_array($tags)) {
                    saveBlogTags($blogId, $tags, $conn);
                }
                
                $message = 'Blog published successfully!';
                $msgType = 'success';
                
                // Redirect after 2 seconds
                echo "<script>
                    setTimeout(function() {
                        window.location.href = 'admin_blogs.php';
                    }, 2000);
                </script>";
            } else {
                $errors[] = 'Failed to create blog: ' . $conn->error;
            }
        }
    }
    
    if (!empty($errors)) {
        $message = implode('<br>', $errors);
        $msgType = 'error';
    }
}

// Get categories for dropdown
$categories = getBlogCategories($conn);
$allTags = getBlogAllTags($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create New Blog Post - Admin</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f5f5;
            color: #333;
        }
        
        .container {
            display: flex;
            min-height: 100vh;
        }
        
        .admin-header {
            background: white;
            border-bottom: 3px solid #c76b8a;
            padding: 20px;
            margin-bottom: 0;
        }
        
        .admin-header h1 {
            color: #c76b8a;
            font-size: 28px;
            margin: 0;
        }
        
        .main-content {
            flex: 1;
            padding: 20px;
            display: flex; 
            justify-content: center;
        }
        
        .form-container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            max-width: 900px;
            
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            /* color: #c76b8a; */
        }
        
        .form-group input[type="text"],
        .form-group input[type="datetime-local"],
        .form-group input[type="email"],
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-family: inherit;
            font-size: 14px;
            background-color: white;
            color: #333;
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="%23333"><path d="M7 8l5 5 5-5z"/></svg>');
            background-repeat: no-repeat;
            background-position: right 8px center;
            background-size: 20px;
            padding-right: 36px;
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 150px;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-top: 10px;
        }
        
        .checkbox-group input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }
        
        .tags-input {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: #fafafa;
        }
        
        .tag-item {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: #c76b8a;
            color: white;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 14px;
        }
        
        .tag-item input[type="checkbox"] {
            width: auto;
            margin: 0;
        }
        
        .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;
        }
        
        .btn-group {
            display: flex;
            gap: 10px;
            margin-top: 30px;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background: #c76b8a;
            color: white;
        }
        
        .btn-primary:hover {
            background: #b35975;
        }
        
        .btn-secondary {
            background: #d3d3d3;
            color: #333;
        }
        
        .btn-secondary:hover {
            background: #bbb;
        }
        
        .file-input-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
        }
        
        .file-input-wrapper input[type="file"] {
            position: absolute;
            left: -9999px;
        }
        
        .file-label {
            display: inline-block;
            padding: 10px 20px;
            background: #c76b8a;
            color: white;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 600;
            transition: background 0.3s;
        }
        
        .file-label:hover {
            background: #b35975;
        }
        
        .file-name {
            display: inline-block;
            margin-left: 10px;
            color: #555;
        }
        
        @media (max-width: 600px) {
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .btn-group {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="admin-header">
        <h1>Add New Blog Post</h1>
    </div>
    
    <div class="main-content">
        <div class="form-container">
            <?php if (!empty($message)): ?>
                <div class="message <?php echo $msgType; ?>">
                    <?php echo $message; ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" enctype="multipart/form-data">
                <!-- Title -->
                <div class="form-group">
                    <label for="title">Blog Title *</label>
                    <input type="text" id="title" name="title" required placeholder="Enter blog title">
                </div>
                
                <!-- Category and Status Row -->
                <div class="form-row">
                    <div class="form-group">
                        <label for="category_id">Category *</label>
                        <select id="category_id" name="category_id" required>
                            <option value="">Select Category</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>">
                                    <?php echo htmlspecialchars($cat['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="status">Status</label>
                        <select id="status" name="status">
                            <option value="draft">Draft</option>
                            <option value="published">Published</option>
                        </select>
                    </div>
                </div>
                
                <!-- Excerpt -->
                <div class="form-group">
                    <label for="excerpt">Excerpt (Short Description)</label>
                    <textarea id="excerpt" name="excerpt" placeholder="Write a short excerpt (max 500 characters)"></textarea>
                </div>
                
                <!-- Featured Image -->
                <div class="form-group">
                    <label>Featured Image</label>
                    <div class="file-input-wrapper">
                        <label for="featured_image" class="file-label">Choose Image</label>
                        <input type="file" id="featured_image" name="featured_image" accept="image/*">
                        <span class="file-name" id="fileName"></span>
                    </div>
                    <small style="display: block; margin-top: 5px; color: #666;">
                        Supported formats: JPEG, PNG, GIF, WebP (Max 5MB)
                    </small>
                </div>
                
                <!-- Image Orientation and Size -->
                <div class="form-row">
                    <div class="form-group">
                        <label for="image_orientation">Image Orientation</label>
                        <select id="image_orientation" name="image_orientation">
                            <option value="landscape" selected>Landscape (Wider than tall)</option>
                            <option value="portrait">Portrait (Taller than wide)</option>
                            <option value="square">Square (Equal width and height)</option>
                        </select>
                        <small style="display: block; margin-top: 5px; color: #666;">
                            Choose how the image should be displayed
                        </small>
                    </div>
                    
                    <div class="form-group">
                        <label for="image_size">Image Size</label>
                        <select id="image_size" name="image_size">
                            <option value="small">Small</option>
                            <option value="medium" selected>Medium</option>
                            <option value="large">Large</option>
                        </select>
                        <small style="display: block; margin-top: 5px; color: #666;">
                            Choose the display size of the image
                        </small>
                    </div>
                </div>
                
                <!-- Main Content -->
                <div class="form-group">
                    <label for="content">Content *</label>
                    <textarea id="content" name="content" required placeholder="Write your blog content..."></textarea>
                    <small style="display: block; margin-top: 5px; color: #666;">
                        You can use HTML tags for formatting
                    </small>
                </div>
                
                <!-- Tags Selection -->
                <div class="form-group">
                    <label>Tags (Optional)</label>
                    <input type="text" name="tags_input" placeholder="Enter tags separated by commas (e.g., summer, casual, trending)">
                    <small style="display: block; margin-top: 5px; color: #666;">
                        You can add custom tags for better organization
                    </small>
                </div>
                
                <!-- Publish Date -->
                <div class="form-group">
                    <label for="publish_date">Publish Date & Time</label>
                    <input type="datetime-local" id="publish_date" name="publish_date">
                    <small style="display: block; margin-top: 5px; color: #666;">
                        Leave empty to publish immediately
                    </small>
                </div>
                
                <!-- SEO Fields -->
                <div class="form-group">
                    <label for="meta_title">SEO Meta Title</label>
                    <input type="text" id="meta_title" name="meta_title" placeholder="SEO title (max 60 characters)" maxlength="60">
                </div>
                
                <div class="form-group">
                    <label for="meta_description">SEO Meta Description</label>
                    <textarea id="meta_description" name="meta_description" placeholder="Meta description (max 160 characters)" maxlength="160" style="min-height: 60px;"></textarea>
                </div>
                
                <!-- Show on Homepage -->
                <div class="form-group">
                    <label for="show_on_home">
                        <div class="checkbox-group">
                            <input type="checkbox" id="show_on_home" name="show_on_home" value="1">
                            <span>Show this post on homepage</span>
                        </div>
                    </label>
                </div>
                
                <!-- Submit Buttons -->
                <div class="btn-group">
                    <button type="submit" class="btn btn-primary">Publish Blog</button>
                    <a href="admin_blogs.php" class="btn btn-secondary" style="text-decoration: none;">Cancel</a>
                    <a href="admin_dashboard.php" class="btn btn-secondary" style="text-decoration: none;">← Back to Dashboard</a>
                </div>
            </form>
        </div>
    </div>
   
    <script>
        // Update file name display
        document.getElementById('featured_image').addEventListener('change', function(e) {
            const fileName = this.files[0]?.name || '';
            document.getElementById('fileName').textContent = fileName;
        });
    </script>

</body>
</html>
