<?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.');
}
$blogId = $_GET['id'] ?? null;
$message = '';
$msgType = '';

if (!$blogId) {
    header('Location: admin_blogs.php');
    exit;
}

// Get blog details
$blog = getBlogById($blogId, $conn, false);
if (!$blog) {
    header('Location: admin_blogs.php');
    exit;
}

// Get current tags
$currentTags = getBlogTags($blogId, $conn);
$currentTagIds = array_map(function($tag) { return $tag['id']; }, $currentTags);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['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;
                    }
                }
            }
        }
    }
    
    // Generate new slug
    $slug = generateSlug($title);
    
    // Validation
    $errors = validateBlogInput(['title' => $title, 'content' => $content, 'category_id' => $categoryId]);
    
    // Check slug uniqueness (exclude current blog)
    if (slugExists($slug, $conn, $blogId)) {
        $errors[] = 'A blog with this title already exists';
    }
    
    if (empty($errors)) {
        // Handle featured image upload
        $featuredImage = $blog['featured_image'];
        if (isset($_FILES['featured_image']) && $_FILES['featured_image']['size'] > 0) {
            // Delete old image
            if ($featuredImage && file_exists('uploads/blog/' . $featuredImage)) {
                unlink('uploads/blog/' . $featuredImage);
            }
            
            $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'] ?? ($blog['image_orientation'] ?? 'landscape');
            $imageSize = $_POST['image_size'] ?? ($blog['image_size'] ?? 'medium');
            
            // Update blog
            $stmt = $conn->prepare("
                UPDATE blogs SET
                    title = ?, slug = ?, content = ?, excerpt = ?, featured_image = ?,
                    image_orientation = ?, image_size = ?, category_id = ?, status = ?, publish_date = ?, meta_title = ?,
                    meta_description = ?, show_on_home = ?
                WHERE id = ?
            ");
            
            $stmt->bind_param(
                'sssssssississi',
                $title, $slug, $content, $excerpt, $featuredImage, $imageOrientation, $imageSize, $categoryId, $status, $publishDate, $metaTitle, $metaDescription, $showOnHome, $blogId
            );
            
            if ($stmt->execute()) {
                // Save tags
                if (!empty($tags) && is_array($tags)) {
                    saveBlogTags($blogId, $tags, $conn);
                } else {
                    // Delete all tags if none selected
                    $stmt = $conn->prepare("DELETE FROM blog_tag_relations WHERE blog_id = ?");
                    $stmt->bind_param('i', $blogId);
                    $stmt->execute();
                }
                
                $message = 'Blog updated successfully!';
                $msgType = 'success';
                
                // Refresh blog data
                $blog = getBlogById($blogId, $conn, false);
                $currentTags = getBlogTags($blogId, $conn);
                $currentTagIds = array_map(function($tag) { return $tag['id']; }, $currentTags);
            } else {
                $errors[] = 'Failed to update 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>Edit Blog - 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;
        }
        
        .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;
        }
        
        .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 textarea,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-family: inherit;
            font-size: 14px;
        }
        
        .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;
        }
        
        .featured-image-preview {
            margin-top: 10px;
            max-width: 200px;
        }
        
        .featured-image-preview img {
            width: 100%;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        
        .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>Edit 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 value="<?php echo htmlspecialchars($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 $blog['category_id'] == $cat['id'] ? 'selected' : ''; ?>>
                                    <?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" <?php echo $blog['status'] === 'draft' ? 'selected' : ''; ?>>Draft</option>
                            <option value="published" <?php echo $blog['status'] === 'published' ? 'selected' : ''; ?>>Published</option>
                        </select>
                    </div>
                </div>
                
                <!-- Excerpt -->
                <div class="form-group">
                    <label for="excerpt">Excerpt (Short Description)</label>
                    <textarea id="excerpt" name="excerpt"><?php echo htmlspecialchars($blog['excerpt']); ?></textarea>
                </div>
                
                <!-- Featured Image -->
                <div class="form-group">
                    <label>Featured Image</label>
                    <?php if ($blog['featured_image']): ?>
                        <div class="featured-image-preview">
                            <img src="uploads/blog/<?php echo htmlspecialchars($blog['featured_image']); ?>" alt="Featured Image">
                            <p style="margin-top: 10px; font-size: 12px; color: #666;">
                                Current image. Upload a new one to replace.
                            </p>
                        </div>
                    <?php endif; ?>
                    <div style="margin-top: 15px;">
                        <div class="file-input-wrapper">
                            <label for="featured_image" class="file-label">Choose New 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>
                </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" <?php echo ($blog['image_orientation'] ?? 'landscape') === 'landscape' ? 'selected' : ''; ?>>Landscape (Wider than tall)</option>
                            <option value="portrait" <?php echo ($blog['image_orientation'] ?? '') === 'portrait' ? 'selected' : ''; ?>>Portrait (Taller than wide)</option>
                            <option value="square" <?php echo ($blog['image_orientation'] ?? '') === 'square' ? 'selected' : ''; ?>>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" <?php echo ($blog['image_size'] ?? 'medium') === 'small' ? 'selected' : ''; ?>>Small</option>
                            <option value="medium" <?php echo ($blog['image_size'] ?? 'medium') === 'medium' ? 'selected' : ''; ?>>Medium</option>
                            <option value="large" <?php echo ($blog['image_size'] ?? 'medium') === 'large' ? 'selected' : ''; ?>>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><?php echo htmlspecialchars($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)" value="<?php echo htmlspecialchars(implode(', ', array_column($currentTags, 'name'))); ?>">
                    <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" 
                        value="<?php echo $blog['publish_date'] ? date('Y-m-d\TH:i', strtotime($blog['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" maxlength="60" 
                        value="<?php echo htmlspecialchars($blog['meta_title']); ?>">
                </div>
                
                <div class="form-group">
                    <label for="meta_description">SEO Meta Description</label>
                    <textarea id="meta_description" name="meta_description" maxlength="160" style="min-height: 60px;"><?php echo htmlspecialchars($blog['meta_description']); ?></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" 
                                <?php echo $blog['show_on_home'] ? 'checked' : ''; ?>>
                            <span>Show this post on homepage</span>
                        </div>
                    </label>
                </div>
                
                <!-- Submit Buttons -->
                <div class="btn-group">
                    <button type="submit" class="btn btn-primary">Update 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>
</html>
<?php
?>
