<?php
// inc_functions.php
require_once __DIR__ . '/inc_db.php';

/**
 * Fetch latest published blogs
 */
function get_latest_blogs(PDO $pdo, int $limit = 6): array {
    $stmt = $pdo->prepare("
        SELECT id, title, slug, excerpt, image_path, category, published_at
        FROM blogs
        WHERE is_published = 1
        ORDER BY published_at DESC
        LIMIT :lim
    ");
    $stmt->bindValue(':lim', $limit, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll();
}

/**
 * Fetch popular blogs (fallback: latest)
 */
function get_popular_blogs(PDO $pdo, int $limit = 4): array {
    // If you have a views column, replace ORDER BY below with `ORDER BY views DESC`
    $stmt = $pdo->prepare("
        SELECT id, title, slug, excerpt, image_path, category, published_at
        FROM blogs
        WHERE is_published = 1
        ORDER BY published_at DESC
        LIMIT :lim
    ");
    $stmt->bindValue(':lim', $limit, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll();
}

/**
 * Save contact form submission
 */
function save_contact(PDO $pdo, array $data): int {
    $stmt = $pdo->prepare("
        INSERT INTO contacts (name, email, phone, subject, message, created_at)
        VALUES (:name, :email, :phone, :subject, :message, NOW())
    ");
    $stmt->execute([
        ':name'    => $data['name'] ?? '',
        ':email'   => $data['email'] ?? '',
        ':phone'   => $data['phone'] ?? '',
        ':subject' => $data['subject'] ?? '',
        ':message' => $data['message'] ?? '',
    ]);

    return (int)$pdo->lastInsertId();
}
