<?php
/**
 * Seed at least 6 blog posts using images from pics_ecom/
 * Run while logged in as admin: http://localhost/ecoms/add_more_blogs.php
 */
session_start();
require_once __DIR__ . '/db_config.php';
require_once __DIR__ . '/blog_helpers.php';

if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    die('Access denied. Please log in as admin.');
}

// 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) {
        $adminId = $res->fetch_assoc()['id'];
    }
    $stmt->close();
}
if (!$adminId) {
    die('Could not resolve admin id. Please re-login.');
}

$sourceDir = __DIR__ . '/pics_ecom';
$destDir   = __DIR__ . '/uploads/blog';
if (!is_dir($destDir)) {
    mkdir($destDir, 0755, true);
}

// Pick 6 images from pics_ecom
$images = glob($sourceDir . '/*.{jpg,jpeg,png,webp}', GLOB_BRACE);
shuffle($images);
$images = array_slice($images, 0, 6);

if (count($images) < 6) {
    die('Not enough images in pics_ecom to seed 6 blogs.');
}

$samplePosts = [
    [
        'title' => 'Spring Florals Lookbook',
        'excerpt' => 'Fresh florals, soft palettes, and airy layers for the new season.',
        'category' => 'Fashion',
        'tags' => ['floral', 'lookbook', 'spring', 'style'],
        'orientation' => 'landscape',
        'size' => 'large'
    ],
    [
        'title' => 'Minimal Beauty Essentials',
        'excerpt' => 'Less is more: the curated beauty kit that travels light.',
        'category' => 'Beauty',
        'tags' => ['beauty', 'minimal', 'skincare'],
        'orientation' => 'portrait',
        'size' => 'medium'
    ],
    [
        'title' => 'Pink Tones for Everyday',
        'excerpt' => 'Soft pink fits every closet—here is how to style it daily.',
        'category' => 'Lifestyle',
        'tags' => ['pink', 'dailywear', 'outfits'],
        'orientation' => 'portrait',
        'size' => 'medium'
    ],
    [
        'title' => 'Classic Layering Guide',
        'excerpt' => 'Tailored coats, neutral knits, and the art of layered elegance.',
        'category' => 'Fashion',
        'tags' => ['layering', 'coats', 'neutrals'],
        'orientation' => 'landscape',
        'size' => 'large'
    ],
    [
        'title' => 'Accessorize with Intent',
        'excerpt' => 'Statement pieces that elevate a simple look effortlessly.',
        'category' => 'Accessories',
        'tags' => ['accessories', 'statement', 'styling'],
        'orientation' => 'square',
        'size' => 'small'
    ],
    [
        'title' => 'Weekend Comfort Edit',
        'excerpt' => 'Relaxed silhouettes and cozy textures for off-duty days.',
        'category' => 'Lifestyle',
        'tags' => ['comfort', 'weekend', 'casual'],
        'orientation' => 'landscape',
        'size' => 'medium'
    ],
];

// Ensure categories exist and map id
$categories = [];
$catRes = $conn->query("SELECT id, name FROM blog_categories");
while ($row = $catRes->fetch_assoc()) {
    $categories[strtolower($row['name'])] = $row['id'];
}

$inserted = 0;
$errors = [];

foreach ($samplePosts as $index => $post) {
    $title = $post['title'];
    $slug  = generateSlug($title);
    if (slugExists($slug, $conn)) {
        $errors[] = "Skipped existing: {$title}";
        continue;
    }

    $categoryName = $post['category'];
    $categoryId = $categories[strtolower($categoryName)] ?? null;
    if (!$categoryId) {
        $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;
    }

    // Copy image to uploads/blog
    $src = $images[$index];
    $ext = pathinfo($src, PATHINFO_EXTENSION);
    $destFile = time() . '_' . $index . '.' . $ext;
    $destPath = $destDir . '/' . $destFile;
    if (!copy($src, $destPath)) {
        $errors[] = "Failed to copy image for {$title}";
        continue;
    }

    $content = "<p>{$post['excerpt']}</p><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus blandit, nibh sit amet malesuada porta, lorem mauris posuere lorem, vitae dignissim sem velit sed magna.</p>";
    $publishDate = date('Y-m-d H:i:s', strtotime('-' . rand(1, 20) . ' days'));

    $stmt = $conn->prepare("
        INSERT INTO blogs (title, slug, content, excerpt, featured_image, image_orientation, image_size, category_id, author_id, status, publish_date, show_on_home)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'published', ?, 0)
    ");
    $stmt->bind_param(
        'sssssissis',
        $title,
        $slug,
        $content,
        $post['excerpt'],
        $destFile,
        $post['orientation'],
        $post['size'],
        $categoryId,
        $adminId,
        $publishDate
    );

    if ($stmt->execute()) {
        $blogId = $conn->insert_id;
        foreach ($post['tags'] as $tagName) {
            $tagSlug = generateSlug($tagName);
            $check = $conn->prepare("SELECT id FROM blog_tags WHERE slug = ?");
            $check->bind_param('s', $tagSlug);
            $check->execute();
            $r = $check->get_result();
            if ($r && $r->num_rows) {
                $tagId = $r->fetch_assoc()['id'];
            } else {
                $insTag = $conn->prepare("INSERT INTO blog_tags (name, slug) VALUES (?, ?)");
                $insTag->bind_param('ss', $tagName, $tagSlug);
                $insTag->execute();
                $tagId = $conn->insert_id;
                $insTag->close();
            }
            $check->close();

            $link = $conn->prepare("INSERT IGNORE INTO blog_tag_relations (blog_id, tag_id) VALUES (?, ?)");
            $link->bind_param('ii', $blogId, $tagId);
            $link->execute();
            $link->close();
        }
        $inserted++;
    } else {
        $errors[] = "DB insert failed for {$title}: " . $conn->error;
    }
    $stmt->close();
}

echo "<!DOCTYPE html><html><head><title>Blog Seeder</title><style>body{font-family:Arial;padding:30px;background:#f5f5f5;} .card{max-width:700px;margin:0 auto;background:#fff;padding:25px;border-radius:8px;box-shadow:0 2px 6px rgba(0,0,0,0.1);} .ok{color:#155724;background:#d4edda;padding:12px;border-radius:4px;margin-bottom:12px;} .err{color:#721c24;background:#f8d7da;padding:12px;border-radius:4px;margin-bottom:12px;}</style></head><body><div class='card'>";
echo "<h2>Blog Seed Complete</h2>";
echo "<div class='ok'>Inserted {$inserted} blog(s).</div>";
if ($errors) {
    echo "<div class='err'><strong>Notes:</strong><ul>";
    foreach ($errors as $e) {
        echo "<li>" . htmlspecialchars($e) . "</li>";
    }
    echo "</ul></div>";
}
echo "<p><a href='blogs.php'>View Blogs</a> | <a href='admin_blogs.php'>Admin Blogs</a></p>";
echo "</div></body></html>";
