<?php
/**
 * Marketing Functions
 * Contains functions for handling discounts and advertisements
 */

// Function to get active discounts
function getActiveDiscounts($pdo) {
    $stmt = $pdo->prepare("
        SELECT d.*, p.name as product_name, p.price as original_price, p.image as product_image
        FROM discounts d
        LEFT JOIN products p ON d.product_id = p.id
        WHERE d.is_active = 1 
        AND (d.start_date IS NULL OR d.start_date <= NOW())
        AND (d.end_date IS NULL OR d.end_date >= NOW())
        ORDER BY d.created_at DESC
    ");
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Function to get discounted price
function getDiscountedPrice($original_price, $discount_percentage) {
    return $original_price * (1 - ($discount_percentage / 100));
}

// Function to get active advertisements for a specific position
function getActiveAdvertisements($pdo, $position = 'homepage') {
    $stmt = $pdo->prepare("
        SELECT *
        FROM advertisements
        WHERE is_active = 1 
        AND position = ?
        AND (start_date IS NULL OR start_date <= NOW())
        AND (end_date IS NULL OR end_date >= NOW())
        ORDER BY created_at DESC
    ");
    $stmt->execute([$position]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Function to get products with discounts
function getProductsWithDiscounts($pdo) {
    $stmt = $pdo->prepare("
        SELECT p.*, d.discount_percentage
        FROM products p
        LEFT JOIN discounts d ON p.id = d.product_id
        WHERE d.is_active = 1 
        AND (d.start_date IS NULL OR d.start_date <= NOW())
        AND (d.end_date IS NULL OR d.end_date >= NOW())
        ORDER BY d.created_at DESC
        LIMIT 8
    ");
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>