<?php
/**
 * Script to add sample blog posts
 * Run this file once to populate the database with sample blog posts
 */
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) {
    die('Access denied. Admin login required.');
}

// Get 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.');
}

// Sample blog posts data
$sampleBlogs = [
    [
        'title' => 'The Latest Fashion Trends for 2026',
        'content' => '<p>Fashion is constantly evolving, and 2026 brings exciting new trends that are reshaping the industry. From sustainable fashion to bold color choices, this year promises to be transformative.</p><p>One of the most significant trends is the shift towards eco-friendly materials and ethical production practices. Consumers are becoming more conscious about their purchases, leading brands to adopt sustainable practices.</p><p>Another major trend is the return of vintage styles with a modern twist. Classic designs are being reimagined with contemporary elements, creating unique and timeless pieces.</p>',
        'excerpt' => 'Discover the hottest fashion trends for 2026, from sustainable fashion to vintage-inspired designs.',
        'category' => 'Fashion',
        'tags' => ['fashion', 'trends', '2026', 'style'],
        'image_orientation' => 'landscape',
        'image_size' => 'medium'
    ],
    [
        'title' => 'How to Build a Sustainable Wardrobe',
        'content' => '<p>Building a sustainable wardrobe is not just about buying eco-friendly clothes; it\'s about making conscious choices that benefit both you and the environment.</p><p>Start by assessing your current wardrobe. Identify pieces you love and wear frequently, and consider donating or recycling items you no longer need.</p><p>When shopping, look for quality over quantity. Invest in well-made pieces that will last for years rather than fast fashion items that wear out quickly.</p>',
        'excerpt' => 'Learn how to build a sustainable wardrobe with practical tips and advice for conscious shopping.',
        'category' => 'Lifestyle',
        'tags' => ['sustainable', 'wardrobe', 'eco-friendly', 'lifestyle'],
        'image_orientation' => 'landscape',
        'image_size' => 'large'
    ],
    [
        'title' => 'Top 10 Must-Have Accessories This Season',
        'content' => '<p>Accessories can make or break an outfit. This season, we\'re seeing some exciting new accessory trends that are perfect for elevating any look.</p><p>Statement bags are making a comeback, with bold colors and unique shapes taking center stage. Whether you prefer a classic tote or a trendy crossbody, there\'s something for everyone.</p><p>Jewelry is also having a moment, with layered necklaces and chunky bracelets being particularly popular. Don\'t be afraid to mix metals and styles for a personalized look.</p>',
        'excerpt' => 'Discover the top 10 must-have accessories that will elevate your style this season.',
        'category' => 'Accessories',
        'tags' => ['accessories', 'jewelry', 'bags', 'style'],
        'image_orientation' => 'portrait',
        'image_size' => 'medium'
    ],
    [
        'title' => 'Fashion Tips for Every Body Type',
        'content' => '<p>Fashion should be inclusive and celebrate all body types. Here are some tips to help you dress confidently, regardless of your shape or size.</p><p>Understanding your body type is the first step to dressing well. Whether you\'re pear-shaped, apple-shaped, or hourglass, there are styles that will flatter your figure.</p><p>Remember, the most important thing is to wear what makes you feel confident and comfortable. Fashion rules are meant to be broken, so don\'t be afraid to experiment.</p>',
        'excerpt' => 'Learn how to dress for your body type with these helpful fashion tips and style advice.',
        'category' => 'Fashion',
        'tags' => ['body type', 'fashion tips', 'style', 'confidence'],
        'image_orientation' => 'square',
        'image_size' => 'small'
    ],
    [
        'title' => 'The Art of Mixing Patterns and Colors',
        'content' => '<p>Mixing patterns and colors can seem intimidating, but with the right approach, you can create stunning, eye-catching outfits.</p><p>Start with a neutral base and add one or two patterned pieces. Keep the color palette cohesive, and don\'t be afraid to experiment with different scales of patterns.</p><p>Remember, confidence is key. If you feel good in what you\'re wearing, you\'ll look good too. Trust your instincts and have fun with your style.</p>',
        'excerpt' => 'Master the art of mixing patterns and colors to create stylish, cohesive outfits.',
        'category' => 'Fashion',
        'tags' => ['patterns', 'colors', 'styling', 'fashion'],
        'image_orientation' => 'landscape',
        'image_size' => 'medium'
    ]
];

// Get categories
$categories = [];
$catResult = $conn->query("SELECT id, name FROM blog_categories");
while ($row = $catResult->fetch_assoc()) {
    $categories[strtolower($row['name'])] = $row['id'];
}

// Insert sample blogs
$inserted = 0;
$errors = [];

foreach ($sampleBlogs as $blogData) {
    $title = $blogData['title'];
    $slug = generateSlug($title);
    
    // Check if blog already exists
    if (slugExists($slug, $conn)) {
        $errors[] = "Blog '$title' already exists. Skipping.";
        continue;
    }
    
    $content = $blogData['content'];
    $excerpt = $blogData['excerpt'];
    $categoryName = $blogData['category'];
    $categoryId = $categories[strtolower($categoryName)] ?? null;
    
    if (!$categoryId) {
        // Create category if it doesn't exist
        $catSlug = generateSlug($categoryName);
        // Check if category already exists
        $checkStmt = $conn->prepare("SELECT id FROM blog_categories WHERE slug = ? LIMIT 1");
        $checkStmt->bind_param('s', $catSlug);
        $checkStmt->execute();
        $res = $checkStmt->get_result();
        if ($res && $res->num_rows > 0) {
            $categoryId = $res->fetch_assoc()['id'];
        } else {
            $stmt = $conn->prepare("INSERT INTO blog_categories (name, slug) VALUES (?, ?)");
            $stmt->bind_param('ss', $categoryName, $catSlug);
            if ($stmt->execute()) {
                $categoryId = $conn->insert_id;
            }
            $stmt->close();
        }
        $checkStmt->close();
        $categories[strtolower($categoryName)] = $categoryId;
    }
    
    $imageOrientation = $blogData['image_orientation'];
    $imageSize = $blogData['image_size'];
    $publishDate = date('Y-m-d H:i:s', strtotime('-' . rand(1, 30) . ' days'));
    
    // Insert blog
    $stmt = $conn->prepare("
        INSERT INTO blogs (title, slug, content, excerpt, image_orientation, image_size, category_id, author_id, status, publish_date, show_on_home)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'published', ?, 0)
    ");
    
    $stmt->bind_param(
        'ssssssiss',
        $title, $slug, $content, $excerpt, $imageOrientation, $imageSize, $categoryId, $adminId, $publishDate
    );
    
    if ($stmt->execute()) {
        $blogId = $conn->insert_id;
        
        // Add tags
        foreach ($blogData['tags'] as $tagName) {
            $tagSlug = generateSlug($tagName);
            $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();
                $tagId = $tagRow['id'];
            } else {
                $insertTag = $conn->prepare("INSERT INTO blog_tags (name, slug) VALUES (?, ?)");
                $insertTag->bind_param('ss', $tagName, $tagSlug);
                if ($insertTag->execute()) {
                    $tagId = $conn->insert_id;
                } else {
                    continue;
                }
                $insertTag->close();
            }
            
            // Link tag to blog
            $linkTag = $conn->prepare("INSERT IGNORE INTO blog_tag_relations (blog_id, tag_id) VALUES (?, ?)");
            $linkTag->bind_param('ii', $blogId, $tagId);
            $linkTag->execute();
            $linkTag->close();
            
            $checkTag->close();
        }
        
        $inserted++;
    } else {
        $errors[] = "Failed to insert '$title': " . $conn->error;
    }
    
    $stmt->close();
}

echo "<!DOCTYPE html><html><head><title>Sample Blogs Added</title><style>body{font-family:Arial;padding: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);} .success{color:#155724;background:#d4edda;padding:15px;border-radius:4px;margin:20px 0;} .error{color:#721c24;background:#f8d7da;padding:15px;border-radius:4px;margin:20px 0;}</style></head><body><div class='container'><h1>Sample Blogs Added</h1>";
echo "<div class='success'>Successfully added $inserted blog post(s).</div>";
if (!empty($errors)) {
    echo "<div class='error'><strong>Errors:</strong><ul>";
    foreach ($errors as $error) {
        echo "<li>$error</li>";
    }
    echo "</ul></div>";
}
echo "<p><a href='admin_blogs.php'>← Back to Blog Management</a></p></div></body></html>";
