<?php
/**
 * Product Class
 * Handles product operations
 */

require_once __DIR__ . '/Database.php';

class Product {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance();
    }

    /**
     * Get product by ID
     */
    public function getProductById($productId) {
        return $this->db->fetchOne(
            "SELECT p.*, c.name as category_name, c.slug as category_slug,
                    s.name as supplier_name
             FROM products p
             LEFT JOIN categories c ON p.category_id = c.id
             LEFT JOIN suppliers s ON p.supplier_id = s.id
             WHERE p.id = ? AND p.is_active = 1",
            [$productId]
        );
    }

    /**
     * Get product by slug
     */
    public function getProductBySlug($slug, $includeInactive = false) {
        $sql = "SELECT p.*, c.name as category_name, c.slug as category_slug,
                    s.name as supplier_name
             FROM products p
             LEFT JOIN categories c ON p.category_id = c.id
             LEFT JOIN suppliers s ON p.supplier_id = s.id
             WHERE p.slug = ?";
        if (!$includeInactive) {
            $sql .= " AND p.is_active = 1";
        }
        return $this->db->fetchOne($sql, [$slug]);
    }

    /**
     * Generate slug from product name
     */
    public function generateSlug($name) {
        // Convert to lowercase
        $slug = strtolower($name);
        
        // Replace Romanian characters
        $romanian = ['ă', 'â', 'î', 'ș', 'ț', 'Ă', 'Â', 'Î', 'Ș', 'Ț'];
        $replace = ['a', 'a', 'i', 's', 't', 'a', 'a', 'i', 's', 't'];
        $slug = str_replace($romanian, $replace, $slug);
        
        // Replace spaces and special characters with hyphens
        $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
        
        // Remove leading/trailing hyphens
        $slug = trim($slug, '-');
        
        // Ensure uniqueness
        $baseSlug = $slug;
        $counter = 1;
        while ($this->db->fetchOne("SELECT id FROM products WHERE slug = ?", [$slug])) {
            $slug = $baseSlug . '-' . $counter;
            $counter++;
        }
        
        return $slug;
    }

    /**
     * Get products with filters
     */
    public function getProducts($filters = []) {
        $sql = "SELECT p.*, c.name as category_name, c.slug as category_slug
                FROM products p
                LEFT JOIN categories c ON p.category_id = c.id
                WHERE p.is_active = 1";
        
        $params = [];

        // Category filter
        if (!empty($filters['category_id'])) {
            $sql .= " AND p.category_id = ?";
            $params[] = $filters['category_id'];
        }

        // Search filter
        if (!empty($filters['search'])) {
            $sql .= " AND (p.name LIKE ? OR p.description LIKE ? OR p.sku LIKE ?)";
            $searchTerm = '%' . $filters['search'] . '%';
            $params[] = $searchTerm;
            $params[] = $searchTerm;
            $params[] = $searchTerm;
        }

        // Price range
        if (!empty($filters['min_price'])) {
            $sql .= " AND (COALESCE(p.sale_price, p.price) >= ?)";
            $params[] = $filters['min_price'];
        }
        if (!empty($filters['max_price'])) {
            $sql .= " AND (COALESCE(p.sale_price, p.price) <= ?)";
            $params[] = $filters['max_price'];
        }

        // In stock filter
        if (isset($filters['in_stock']) && $filters['in_stock']) {
            $sql .= " AND p.stock_quantity > 0";
        }

        // Order by
        $orderBy = $filters['order_by'] ?? 'created_at';
        $orderDir = $filters['order_dir'] ?? 'DESC';
        $sql .= " ORDER BY p.{$orderBy} {$orderDir}";

        // Pagination
        $page = $filters['page'] ?? 1;
        $perPage = $filters['per_page'] ?? PRODUCTS_PER_PAGE;
        $offset = ($page - 1) * $perPage;
        $sql .= " LIMIT {$perPage} OFFSET {$offset}";

        return $this->db->fetchAll($sql, $params);
    }

    /**
     * Get products count (for pagination)
     */
    public function getProductsCount($filters = []) {
        $sql = "SELECT COUNT(*) as total FROM products p WHERE p.is_active = 1";
        $params = [];

        if (!empty($filters['category_id'])) {
            $sql .= " AND p.category_id = ?";
            $params[] = $filters['category_id'];
        }

        if (!empty($filters['search'])) {
            $sql .= " AND (p.name LIKE ? OR p.description LIKE ? OR p.sku LIKE ?)";
            $searchTerm = '%' . $filters['search'] . '%';
            $params[] = $searchTerm;
            $params[] = $searchTerm;
            $params[] = $searchTerm;
        }

        if (!empty($filters['min_price'])) {
            $sql .= " AND (COALESCE(p.sale_price, p.price) >= ?)";
            $params[] = $filters['min_price'];
        }
        if (!empty($filters['max_price'])) {
            $sql .= " AND (COALESCE(p.sale_price, p.price) <= ?)";
            $params[] = $filters['max_price'];
        }

        if (isset($filters['in_stock']) && $filters['in_stock']) {
            $sql .= " AND p.stock_quantity > 0";
        }

        $result = $this->db->fetchOne($sql, $params);
        return $result['total'] ?? 0;
    }

    /**
     * Get featured products
     */
    public function getFeaturedProducts($limit = 8) {
        return $this->db->fetchAll(
            "SELECT p.*, c.name as category_name, c.slug as category_slug
             FROM products p
             LEFT JOIN categories c ON p.category_id = c.id
             WHERE p.is_active = 1
             ORDER BY p.created_at DESC
             LIMIT ?",
            [$limit]
        );
    }

    /**
     * Get product price (considering sale price and B2B discount)
     * @deprecated Use B2B::calculateProductPrice() instead for full B2B support
     */
    public function getProductPrice($product, $b2bGroup = null, $userId = null) {
        $price = $product['sale_price'] ?? $product['price'];
        
        // If userId is provided, use B2B class for full calculation
        if ($userId) {
            require_once __DIR__ . '/B2B.php';
            $b2b = new B2B();
            return $b2b->calculateProductPrice($product, $userId);
        }
        
        // Apply B2B discount if applicable (legacy support)
        if ($b2bGroup && $b2bGroup['discount_percentage'] > 0) {
            $discount = ($price * $b2bGroup['discount_percentage']) / 100;
            $price = $price - $discount;
        }

        return $price;
    }

    /**
     * Check if product is in stock
     */
    public function isInStock($productId, $quantity = 1) {
        $product = $this->getProductById($productId);
        return $product && $product['stock_quantity'] >= $quantity;
    }

    /**
     * Update stock
     */
    public function updateStock($productId, $quantity) {
        return $this->db->execute(
            "UPDATE products SET stock_quantity = stock_quantity - ?, updated_at = NOW() WHERE id = ?",
            [$quantity, $productId]
        );
    }

    /**
     * Get categories
     */
    public function getCategories($parentId = null) {
        $sql = "SELECT * FROM categories WHERE 1=1";
        $params = [];

        if ($parentId === null) {
            $sql .= " AND parent_id IS NULL";
        } else {
            $sql .= " AND parent_id = ?";
            $params[] = $parentId;
        }

        $sql .= " ORDER BY sort_order ASC, name ASC";
        
        return $this->db->fetchAll($sql, $params);
    }

    /**
     * Get category by slug
     */
    public function getCategoryBySlug($slug) {
        return $this->db->fetchOne(
            "SELECT * FROM categories WHERE slug = ?",
            [$slug]
        );
    }
}
?>

