<?php
// sellbazar/includes/functions.php
// Complete fixed version
function get_user($pdo, $user_id) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    return $stmt->fetch();
}
function redirect($url) {
    header("Location: " . $url);
    exit();
}

// includes/functions.php - Update the isAdmin function
function isAdmin() {
    return isset($_SESSION['admin_id']) && isset($_SESSION['admin_role']) && $_SESSION['admin_role'] === 'admin';
}

// Add these functions if not already present
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function sanitize($input) {
    return htmlspecialchars(strip_tags(trim($input)));
}

function generateSlug($text) {
    $text = preg_replace('/[^a-zA-Z0-9\s-]/', '', strtolower($text));
    $text = preg_replace('/\s+/', '-', $text);
    return $text;
}

function generateInvoiceNo() {
    return 'INV-' . date('Ymd') . '-' . strtoupper(uniqid());
}

function getCategories($pdo) {
    $stmt = $pdo->query("SELECT * FROM categories WHERE status = 1 ORDER BY name");
    return $stmt->fetchAll();
}

function getSubcategories($pdo, $category_id) {
    $stmt = $pdo->prepare("SELECT * FROM subcategories WHERE category_id = ? AND status = 1 ORDER BY name");
    $stmt->execute([$category_id]);
    return $stmt->fetchAll();
}

function getProductBySlug($pdo, $slug) {
    $stmt = $pdo->prepare("SELECT * FROM products WHERE slug = ? AND status = 1");
    $stmt->execute([$slug]);
    return $stmt->fetch();
}

// FIXED: Use intval() and direct concatenation for LIMIT
function getFeaturedProducts($pdo, $limit = 8) {
    $limit = intval($limit);
    $stmt = $pdo->query("SELECT * FROM products WHERE status = 1 AND featured = 1 ORDER BY created_at DESC LIMIT " . $limit);
    return $stmt->fetchAll();
}

// FIXED: Use intval() and direct concatenation for LIMIT
function getNewProducts($pdo, $limit = 8) {
    $limit = intval($limit);
    $stmt = $pdo->query("SELECT * FROM products WHERE status = 1 AND new = 1 ORDER BY created_at DESC LIMIT " . $limit);
    return $stmt->fetchAll();
}

// FIXED: Use intval() and direct concatenation for LIMIT
function getTopSellingProducts($pdo, $limit = 8) {
    $limit = intval($limit);
    $stmt = $pdo->query("SELECT * FROM products WHERE status = 1 AND top_selling = 1 ORDER BY views DESC LIMIT " . $limit);
    return $stmt->fetchAll();
}

function getBanners($pdo) {
    $stmt = $pdo->query("SELECT * FROM banners WHERE status = 1 ORDER BY id");
    return $stmt->fetchAll();
}

// includes/functions.php
// Add this function if not exists

if (!function_exists('getSetting')) {
    function getSetting($pdo, $key) {
        try {
            $stmt = $pdo->prepare("SELECT value FROM settings WHERE `key` = ?");
            $stmt->execute([$key]);
            $result = $stmt->fetch();
            return $result ? $result['value'] : null;
        } catch (Exception $e) {
            return null;
        }
    }
}

if (!function_exists('updateSetting')) {
    function updateSetting($pdo, $key, $value) {
        try {
            $stmt = $pdo->prepare("INSERT INTO settings (`key`, `value`) VALUES (?, ?) 
                                  ON DUPLICATE KEY UPDATE `value` = ?");
            return $stmt->execute([$key, $value, $value]);
        } catch (Exception $e) {
            return false;
        }
    }
}

function getCartItems() {
    return isset($_SESSION['cart']) ? $_SESSION['cart'] : [];
}

function getCartCount() {
    $count = 0;
    if (isset($_SESSION['cart'])) {
        foreach ($_SESSION['cart'] as $item) {
            $count += $item['quantity'];
        }
    }
    return $count;
}

function getCartTotal() {
    $total = 0;
    if (isset($_SESSION['cart'])) {
        foreach ($_SESSION['cart'] as $item) {
            $total += $item['price'] * $item['quantity'];
        }
    }
    return $total;
}

// includes/functions.php - Update the addToCart function
function addToCart($pdo, $product_id, $quantity = 1, $attributes = []) {
    if (!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = [];
    }
    
    // Get product
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ? AND status = 1");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch();
    
    if (!$product) {
        error_log("Product not found: " . $product_id);
        return false;
    }
    
    $price = $product['sale_price'] ?: $product['price'];
    
    // Generate a unique key for this cart item
    $key = $product_id . '-' . md5(json_encode($attributes));
    
    if (isset($_SESSION['cart'][$key])) {
        $_SESSION['cart'][$key]['quantity'] += $quantity;
    } else {
        $_SESSION['cart'][$key] = [
            'product_id' => $product_id,
            'name' => $product['name'],
            'price' => floatval($price),
            'quantity' => intval($quantity),
            'image' => $product['image'],
            'attributes' => $attributes,
            'slug' => $product['slug']
        ];
    }
    
    error_log("Cart updated. Total items: " . count($_SESSION['cart']));
    return true;
}

function getMetaPixelScript() {
    global $pdo;
    $pixel_id = getSetting($pdo, 'facebook_pixel_id');
    if (!$pixel_id) return '';
    return '
    <script>
    !function(f,b,e,v,n,t,s)
    {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
    n.callMethod.apply(n,arguments):n.queue.push(arguments)};
    if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version="2.0";
    n.queue=[];t=b.createElement(e);t.async=!0;
    t.src=v;s=b.getElementsByTagName(e)[0];
    s.parentNode.insertBefore(t,s)}(window, document,"script",
    "https://connect.facebook.net/en_US/fbevents.js");
    fbq("init", "' . $pixel_id . '");
    fbq("track", "PageView");
    </script>
    <noscript><img height="1" width="1" style="display:none"
    src="https://www.facebook.com/tr?id=' . $pixel_id . '&ev=PageView&noscript=1"
    /></noscript>
    ';
}

// Get a single product
function getProduct($pdo, $id) {
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$id]);
    return $stmt->fetch();
}

// Get all products with pagination
function getProducts($pdo, $limit = null, $offset = 0) {
    $sql = "SELECT * FROM products WHERE status = 1 ORDER BY created_at DESC";
    if ($limit) {
        $limit = intval($limit);
        $offset = intval($offset);
        $sql .= " LIMIT " . $limit . " OFFSET " . $offset;
    }
    $stmt = $pdo->query($sql);
    return $stmt->fetchAll();
}

// Get products by category
function getProductsByCategory($pdo, $category_slug, $limit = null) {
    $sql = "SELECT p.* FROM products p 
            LEFT JOIN categories c ON p.category_id = c.id 
            WHERE p.status = 1 AND c.slug = ? 
            ORDER BY p.created_at DESC";
    if ($limit) {
        $limit = intval($limit);
        $sql .= " LIMIT " . $limit;
    }
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$category_slug]);
    return $stmt->fetchAll();
}

// Get product attributes
function getProductAttributes($pdo, $product_id) {
    $stmt = $pdo->prepare("SELECT * FROM product_attributes WHERE product_id = ?");
    $stmt->execute([$product_id]);
    return $stmt->fetchAll();
}

// Create order
function createOrder($pdo, $data) {
    try {
        $pdo->beginTransaction();
        
        $invoice_no = generateInvoiceNo();
        
        $stmt = $pdo->prepare("INSERT INTO orders (
            invoice_no, user_id, name, phone, email, address, city, subcity, note,
            subtotal, shipping_charge, discount, total, payment_method, 
            coupon_code, coupon_discount
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            $invoice_no,
            $data['user_id'] ?? null,
            $data['name'],
            $data['phone'],
            $data['email'] ?? null,
            $data['address'],
            $data['city'] ?? null,
            $data['subcity'] ?? null,
            $data['note'] ?? null,
            $data['subtotal'],
            $data['shipping_charge'] ?? 0,
            $data['discount'] ?? 0,
            $data['total'],
            $data['payment_method'] ?? 'cod',
            $data['coupon_code'] ?? null,
            $data['coupon_discount'] ?? 0
        ]);
        
        $order_id = $pdo->lastInsertId();
        
        foreach ($data['items'] as $item) {
            $stmt = $pdo->prepare("INSERT INTO order_items (
                order_id, product_id, product_name, product_code, attributes, quantity, price, total
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            
            $stmt->execute([
                $order_id,
                $item['product_id'],
                $item['name'],
                $item['product_code'] ?? null,
                json_encode($item['attributes'] ?? []),
                $item['quantity'],
                $item['price'],
                $item['price'] * $item['quantity']
            ]);
        }
        
        $pdo->commit();
        return $invoice_no;
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
}

// Get orders for a user
function getOrder($pdo, $invoice_no) {
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE invoice_no = ?");
    $stmt->execute([$invoice_no]);
    return $stmt->fetch();
}

function getOrderItems($pdo, $order_id) {
    $stmt = $pdo->prepare("SELECT * FROM order_items WHERE order_id = ?");
    $stmt->execute([$order_id]);
    return $stmt->fetchAll();
}

function getOrdersByUser($pdo, $user_id) {
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC");
    $stmt->execute([$user_id]);
    return $stmt->fetchAll();
}






?>