<?php
// Blog Helper Functions
// Include this file in pages that need blog functionality

/**
 * Generate slug from title
 */
function generateSlug($title) {
    $slug = strtolower(trim($title));
    $slug = preg_replace('/[^a-z0-9-]/', '-', $slug);
    $slug = preg_replace('/-+/', '-', $slug);
    $slug = trim($slug, '-');
    return $slug;
}

/**
 * Check if slug exists (for unique validation)
 */
function slugExists($slug, $db, $excludeId = null) {
    $query = "SELECT id FROM blogs WHERE slug = ?";
    $types = 's';
    $params = [$slug];
    
    if ($excludeId) {
        $query .= " AND id != ?";
        $types .= 'i';
        $params[] = $excludeId;
    }
    
    $stmt = $db->prepare($query);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    return $stmt->get_result()->num_rows > 0;
}

/**
 * Upload featured image
 */
function uploadBlogImage($file, $uploadDir = 'uploads/blog/') {
    // Create directory if it doesn't exist
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $maxSize = 5 * 1024 * 1024; // 5MB
    
    if (!isset($file['tmp_name']) || $file['error'] !== UPLOAD_ERR_OK) {
        return ['success' => false, 'message' => 'File upload error'];
    }
    
    if (!in_array($file['type'], $allowedTypes)) {
        return ['success' => false, 'message' => 'Invalid file type. Only JPEG, PNG, GIF, and WebP allowed'];
    }
    
    if ($file['size'] > $maxSize) {
        return ['success' => false, 'message' => 'File too large. Maximum 5MB allowed'];
    }
    
    // Check image dimensions - must be landscape (width > height)
    $imageInfo = @getimagesize($file['tmp_name']);
    if ($imageInfo === false) {
        return ['success' => false, 'message' => 'Could not read image file'];
    }
    
    $width = $imageInfo[0];
    $height = $imageInfo[1];
    
    if ($width <= $height) {
        return ['success' => false, 'message' => 'Blog image must be landscape format (width greater than height). Please upload a landscape image instead of portrait.'];
    }
    
    $filename = time() . '_' . preg_replace('/[^a-z0-9._-]/i', '', basename($file['name']));
    $filepath = $uploadDir . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return ['success' => true, 'filename' => $filename, 'path' => $filepath];
    }
    
    return ['success' => false, 'message' => 'Failed to upload file'];
}

/**
 * Get blog by slug
 */
function getBlogBySlug($slug, $db) {
    $stmt = $db->prepare("
        SELECT b.*, bc.name as category_name, bc.slug as category_slug, u.username as author_name
        FROM blogs b
        LEFT JOIN blog_categories bc ON b.category_id = bc.id
        LEFT JOIN admins a ON b.author_id = a.id
        LEFT JOIN users u ON a.user_id = u.id
        WHERE b.slug = ? AND b.status = 'published' AND (b.publish_date IS NULL OR b.publish_date <= NOW())
    ");
    $stmt->bind_param('s', $slug);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

/**
 * Get blog by ID
 */
function getBlogById($id, $db, $checkPublished = false) {
    $query = "
        SELECT b.*, bc.name as category_name, bc.slug as category_slug, u.username as author_name
        FROM blogs b
        LEFT JOIN blog_categories bc ON b.category_id = bc.id
        LEFT JOIN admins a ON b.author_id = a.id
        LEFT JOIN users u ON a.user_id = u.id
        WHERE b.id = ?
    ";
    
    if ($checkPublished) {
        $query .= " AND b.status = 'published' AND (b.publish_date IS NULL OR b.publish_date <= NOW())";
    }
    
    $stmt = $db->prepare($query);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

/**
 * Get all blogs with filters
 */
function getBlogs($db, $filters = []) {
    $query = "
        SELECT b.*, bc.name as category_name, bc.slug as category_slug, u.username as author_name,
               GROUP_CONCAT(bt.name SEPARATOR ', ') as tags
        FROM blogs b
        LEFT JOIN blog_categories bc ON b.category_id = bc.id
        LEFT JOIN admins a ON b.author_id = a.id
        LEFT JOIN users u ON a.user_id = u.id
        LEFT JOIN blog_tag_relations btr ON b.id = btr.blog_id
        LEFT JOIN blog_tags bt ON btr.tag_id = bt.id
        WHERE 1=1
    ";
    
    $params = [];
    $types = '';
    
    // Default: only published blogs
    if (!isset($filters['include_drafts']) || !$filters['include_drafts']) {
        $query .= " AND b.status = 'published' AND (b.publish_date IS NULL OR b.publish_date <= NOW())";
    }
    
    if (isset($filters['category_id'])) {
        $query .= " AND b.category_id = ?";
        $params[] = $filters['category_id'];
        $types .= 'i';
    }
    
    if (isset($filters['tag_id'])) {
        $query .= " AND btr.tag_id = ?";
        $params[] = $filters['tag_id'];
        $types .= 'i';
    }
    
    if (isset($filters['search'])) {
        $query .= " AND (b.title LIKE ? OR b.content LIKE ? OR b.excerpt LIKE ?)";
        $searchTerm = '%' . $filters['search'] . '%';
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $types .= 'sss';
    }
    
    if (isset($filters['show_on_home'])) {
        $query .= " AND b.show_on_home = ?";
        $params[] = $filters['show_on_home'];
        $types .= 'i';
    }
    
    $query .= " GROUP BY b.id";
    
    if (isset($filters['order'])) {
        $query .= " ORDER BY " . $filters['order'];
    } else {
        $query .= " ORDER BY b.publish_date DESC, b.created_at DESC";
    }
    
    if (isset($filters['limit'])) {
        $query .= " LIMIT ?";
        $params[] = $filters['limit'];
        $types .= 'i';
        
        if (isset($filters['offset'])) {
            $query .= " OFFSET ?";
            $params[] = $filters['offset'];
            $types .= 'i';
        }
    }
    
    $stmt = $db->prepare($query);
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

/**
 * Get total count of blogs
 */
function getBlogCount($db, $filters = []) {
    $query = "SELECT COUNT(DISTINCT b.id) as total FROM blogs b";
    
    $where = " WHERE b.status = 'published' AND (b.publish_date IS NULL OR b.publish_date <= NOW())";
    
    if (isset($filters['category_id'])) {
        $where .= " AND b.category_id = ?";
    }
    
    if (isset($filters['tag_id'])) {
        $where .= " AND EXISTS (
            SELECT 1 FROM blog_tag_relations btr 
            WHERE btr.blog_id = b.id AND btr.tag_id = ?
        )";
    }
    
    $query .= $where;
    
    $params = [];
    $types = '';
    
    if (isset($filters['category_id'])) {
        $params[] = $filters['category_id'];
        $types .= 'i';
    }
    
    if (isset($filters['tag_id'])) {
        $params[] = $filters['tag_id'];
        $types .= 'i';
    }
    
    $stmt = $db->prepare($query);
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    return $result['total'];
}

/**
 * Get tags for a blog
 */
function getBlogTags($blogId, $db) {
    $stmt = $db->prepare("
        SELECT bt.* FROM blog_tags bt
        JOIN blog_tag_relations btr ON bt.id = btr.tag_id
        WHERE btr.blog_id = ?
    ");
    $stmt->bind_param('i', $blogId);
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

/**
 * Get all categories
 */
function getBlogCategories($db) {
    $stmt = $db->prepare("
        SELECT bc.*, COUNT(b.id) as count 
        FROM blog_categories bc
        LEFT JOIN blogs b ON bc.id = b.category_id AND b.status = 'published' AND (b.publish_date IS NULL OR b.publish_date <= NOW())
        GROUP BY bc.id
        ORDER BY bc.name ASC
    ");
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

/**
 * Get category by slug
 */
function getCategoryBySlug($slug, $db) {
    $stmt = $db->prepare("SELECT * FROM blog_categories WHERE slug = ?");
    $stmt->bind_param('s', $slug);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

/**
 * Get all tags
 */
function getBlogAllTags($db) {
    $stmt = $db->prepare("SELECT * FROM blog_tags ORDER BY name ASC");
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

/**
 * Get tag by slug
 */
function getTagBySlug($slug, $db) {
    $stmt = $db->prepare("SELECT * FROM blog_tags WHERE slug = ?");
    $stmt->bind_param('s', $slug);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

/**
 * Save blog tags
 */
function saveBlogTags($blogId, $tagIds, $db) {
    // Delete existing tags
    $stmt = $db->prepare("DELETE FROM blog_tag_relations WHERE blog_id = ?");
    $stmt->bind_param('i', $blogId);
    $stmt->execute();
    
    // Insert new tags
    if (!empty($tagIds)) {
        $stmt = $db->prepare("INSERT INTO blog_tag_relations (blog_id, tag_id) VALUES (?, ?)");
        foreach ($tagIds as $tagId) {
            $stmt->bind_param('ii', $blogId, $tagId);
            $stmt->execute();
        }
    }
}

/**
 * Get related posts
 */
function getRelatedPosts($blogId, $db, $limit = 3) {
    // First try to get by tags
    $stmt = $db->prepare("
        SELECT DISTINCT b.*, bc.name as category_name, bc.slug as category_slug
        FROM blogs b
        LEFT JOIN blog_categories bc ON b.category_id = bc.id
        JOIN blog_tag_relations btr ON b.id = btr.blog_id
        WHERE btr.tag_id IN (
            SELECT tag_id FROM blog_tag_relations WHERE blog_id = ?
        )
        AND b.id != ?
        AND b.status = 'published'
        AND (b.publish_date IS NULL OR b.publish_date <= NOW())
        ORDER BY b.publish_date DESC, b.created_at DESC
        LIMIT ?
    ");
    $stmt->bind_param('iii', $blogId, $blogId, $limit);
    $stmt->execute();
    $results = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    // If not enough results, get by category
    if (count($results) < $limit) {
        $blog = getBlogById($blogId, $db);
        if ($blog && $blog['category_id']) {
            $remaining = $limit - count($results);
            $existingIds = array_column($results, 'id');
            $existingIds[] = $blogId;
            $placeholders = implode(',', array_fill(0, count($existingIds), '?'));
            
            $stmt2 = $db->prepare("
                SELECT DISTINCT b.*, bc.name as category_name, bc.slug as category_slug
                FROM blogs b
                LEFT JOIN blog_categories bc ON b.category_id = bc.id
                WHERE b.category_id = ? 
                AND b.id NOT IN ($placeholders)
                AND b.status = 'published'
                AND (b.publish_date IS NULL OR b.publish_date <= NOW())
                ORDER BY b.publish_date DESC, b.created_at DESC
                LIMIT ?
            ");
            $types = 'i' . str_repeat('i', count($existingIds)) . 'i';
            $params = array_merge([$blog['category_id']], $existingIds, [$remaining]);
            $stmt2->bind_param($types, ...$params);
            $stmt2->execute();
            $categoryResults = $stmt2->get_result()->fetch_all(MYSQLI_ASSOC);
            $results = array_merge($results, $categoryResults);
        }
    }
    
    // If still not enough, get any recent posts
    if (count($results) < $limit) {
        $remaining = $limit - count($results);
        $existingIds = array_column($results, 'id');
        $existingIds[] = $blogId;
        $placeholders = implode(',', array_fill(0, count($existingIds), '?'));
        
        $stmt3 = $db->prepare("
            SELECT DISTINCT b.*, bc.name as category_name, bc.slug as category_slug
            FROM blogs b
            LEFT JOIN blog_categories bc ON b.category_id = bc.id
            WHERE b.id NOT IN ($placeholders)
            AND b.status = 'published'
            AND (b.publish_date IS NULL OR b.publish_date <= NOW())
            ORDER BY b.publish_date DESC, b.created_at DESC
            LIMIT ?
        ");
        $types = str_repeat('i', count($existingIds)) . 'i';
        $params = array_merge($existingIds, [$remaining]);
        $stmt3->bind_param($types, ...$params);
        $stmt3->execute();
        $recentResults = $stmt3->get_result()->fetch_all(MYSQLI_ASSOC);
        $results = array_merge($results, $recentResults);
    }
    
    return array_slice($results, 0, $limit);
}

/**
 * Increment blog views
 */
function incrementBlogViews($blogId, $db) {
    $stmt = $db->prepare("UPDATE blogs SET views = views + 1 WHERE id = ?");
    $stmt->bind_param('i', $blogId);
    return $stmt->execute();
}

/**
 * Get next/previous posts
 */
function getNavigationPosts($blogId, $db) {
    $stmt = $db->prepare("
        SELECT id, title, slug FROM blogs
        WHERE id < ? AND status = 'published' AND (publish_date IS NULL OR publish_date <= NOW())
        ORDER BY id DESC LIMIT 1
    ");
    $stmt->bind_param('i', $blogId);
    $stmt->execute();
    $prevPost = $stmt->get_result()->fetch_assoc();
    
    $stmt = $db->prepare("
        SELECT id, title, slug FROM blogs
        WHERE id > ? AND status = 'published' AND (publish_date IS NULL OR publish_date <= NOW())
        ORDER BY id ASC LIMIT 1
    ");
    $stmt->bind_param('i', $blogId);
    $stmt->execute();
    $nextPost = $stmt->get_result()->fetch_assoc();
    
    return ['prev' => $prevPost, 'next' => $nextPost];
}

/**
 * Delete blog
 */
function deleteBlog($blogId, $db) {
    // Delete tags relations first (foreign key constraint)
    $stmt = $db->prepare("DELETE FROM blog_tag_relations WHERE blog_id = ?");
    $stmt->bind_param('i', $blogId);
    if (!$stmt->execute()) {
        return false;
    }
    
    // Delete featured image if exists
    $blog = getBlogById($blogId, $db);
    if ($blog && $blog['featured_image']) {
        $imagePath = 'uploads/blog/' . $blog['featured_image'];
        if (file_exists($imagePath)) {
            @unlink($imagePath);
        }
    }
    
    // Delete blog
    $stmt = $db->prepare("DELETE FROM blogs WHERE id = ?");
    $stmt->bind_param('i', $blogId);
    return $stmt->execute();
}

/**
 * Sanitize user input
 */
function sanitizeInput($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

/**
 * Validate blog input
 */
function validateBlogInput($data) {
    $errors = [];
    
    if (empty($data['title'])) {
        $errors[] = 'Title is required';
    }
    
    if (empty($data['content'])) {
        $errors[] = 'Content is required';
    }
    
    if (empty($data['category_id'])) {
        $errors[] = 'Category is required';
    }
    
    return $errors;
}

/**
 * Get recent comments for sidebar
 */
function getRecentComments($db, $limit = 4) {
    // If comments table doesn't exist, return empty array
    // This is a placeholder - you may need to create a comments table
    try {
        $stmt = $db->prepare("
            SELECT c.*, b.title as blog_title, b.slug as blog_slug, u.username as author_name
            FROM blog_comments c
            LEFT JOIN blogs b ON c.blog_id = b.id
            LEFT JOIN users u ON c.user_id = u.id
            WHERE c.status = 'approved'
            ORDER BY c.created_at DESC
            LIMIT ?
        ");
        $stmt->bind_param('i', $limit);
        $stmt->execute();
        return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    } catch (Exception $e) {
        // Comments table might not exist yet
        return [];
    }
}

?>
