<?php
/**
 * B2B Class
 * Handles B2B groups, discounts, and product-specific pricing
 */

require_once __DIR__ . '/Database.php';

class B2B {
    private $db;

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

    /**
     * Get user B2B group
     */
    public function getUserB2BGroup($userId) {
        $group = $this->db->fetchOne(
            "SELECT bg.*, bg.discount_percent as discount_percentage FROM b2b_groups bg
             INNER JOIN b2b_group_users bgu ON bg.id = bgu.b2b_group_id
             WHERE bgu.user_id = ? AND bg.is_active = 1",
            [$userId]
        );
        // Ensure discount_percentage alias exists for backward compatibility
        if ($group && !isset($group['discount_percentage'])) {
            $group['discount_percentage'] = $group['discount_percent'] ?? 0;
        }
        return $group;
    }

    /**
     * Get product-specific price for a user
     * Returns array with 'price' and 'discount_percent' or null if no specific price
     */
    public function getProductPriceForUser($userId, $productId) {
        return $this->db->fetchOne(
            "SELECT * FROM b2b_product_prices
             WHERE user_id = ? AND product_id = ?",
            [$userId, $productId]
        );
    }

    /**
     * Calculate final price for a product considering:
     * 1. Product-specific price for user (highest priority)
     * 2. B2B group discount
     * 3. Regular/sale price
     */
    public function calculateProductPrice($product, $userId = null) {
        $basePrice = $product['sale_price'] ?? $product['price'];
        $finalPrice = $basePrice;

        if ($userId) {
            // Check for product-specific price (highest priority)
            $productPrice = $this->getProductPriceForUser($userId, $product['id']);
            
            if ($productPrice) {
                if ($productPrice['custom_price'] !== null) {
                    // Use custom price directly
                    return (float)$productPrice['custom_price'];
                } elseif ($productPrice['discount_percent'] !== null) {
                    // Apply discount percentage
                    $discount = ($basePrice * $productPrice['discount_percent']) / 100;
                    return $basePrice - $discount;
                }
            }

            // Check for B2B group discount (lower priority)
            $b2bGroup = $this->getUserB2BGroup($userId);
            $discountPercent = $b2bGroup['discount_percent'] ?? $b2bGroup['discount_percentage'] ?? 0;
            if ($b2bGroup && $discountPercent > 0) {
                $discount = ($basePrice * $discountPercent) / 100;
                $finalPrice = $basePrice - $discount;
            }
        }

        return $finalPrice;
    }

    /**
     * Get all B2B groups
     */
    public function getB2BGroups() {
        return $this->db->fetchAll(
            "SELECT * FROM b2b_groups ORDER BY name ASC"
        );
    }

    /**
     * Get B2B group by ID
     */
    public function getB2BGroupById($groupId) {
        return $this->db->fetchOne(
            "SELECT * FROM b2b_groups WHERE id = ?",
            [$groupId]
        );
    }

    /**
     * Create B2B group
     */
    public function createB2BGroup($data) {
        $this->db->execute(
            "INSERT INTO b2b_groups (name, discount_percent, description, is_active)
             VALUES (?, ?, ?, ?)",
            [
                $data['name'],
                $data['discount_percent'] ?? $data['discount_percentage'] ?? 0,
                $data['description'] ?? null,
                $data['is_active'] ?? 1
            ]
        );
        return $this->db->lastInsertId();
    }

    /**
     * Update B2B group
     */
    public function updateB2BGroup($groupId, $data) {
        return $this->db->execute(
            "UPDATE b2b_groups 
             SET name = ?, discount_percent = ?, description = ?, is_active = ?
             WHERE id = ?",
            [
                $data['name'],
                $data['discount_percent'] ?? $data['discount_percentage'] ?? 0,
                $data['description'] ?? null,
                $data['is_active'] ?? 1,
                $groupId
            ]
        );
    }

    /**
     * Delete B2B group
     */
    public function deleteB2BGroup($groupId) {
        return $this->db->execute(
            "DELETE FROM b2b_groups WHERE id = ?",
            [$groupId]
        );
    }

    /**
     * Add user to B2B group
     */
    public function addUserToGroup($userId, $groupId) {
        try {
            $this->db->execute(
                "INSERT INTO b2b_group_users (user_id, b2b_group_id)
                 VALUES (?, ?)
                 ON DUPLICATE KEY UPDATE b2b_group_id = ?",
                [$userId, $groupId, $groupId]
            );
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Remove user from B2B group
     */
    public function removeUserFromGroup($userId, $groupId) {
        return $this->db->execute(
            "DELETE FROM b2b_group_users WHERE user_id = ? AND b2b_group_id = ?",
            [$userId, $groupId]
        );
    }

    /**
     * Set product-specific price for user
     */
    public function setProductPriceForUser($userId, $productId, $data) {
        // Check if record exists
        $existing = $this->getProductPriceForUser($userId, $productId);
        
        if ($existing) {
            // Update existing
            return $this->db->execute(
                "UPDATE b2b_product_prices
                 SET discount_percent = ?, custom_price = ?, updated_at = NOW()
                 WHERE user_id = ? AND product_id = ?",
                [
                    $data['discount_percent'] ?? null,
                    $data['custom_price'] ?? null,
                    $userId,
                    $productId
                ]
            );
        } else {
            // Insert new
            $this->db->execute(
                "INSERT INTO b2b_product_prices (user_id, product_id, discount_percent, custom_price)
                 VALUES (?, ?, ?, ?)",
                [
                    $userId,
                    $productId,
                    $data['discount_percent'] ?? null,
                    $data['custom_price'] ?? null
                ]
            );
            return $this->db->lastInsertId();
        }
    }

    /**
     * Remove product-specific price for user
     */
    public function removeProductPriceForUser($userId, $productId) {
        return $this->db->execute(
            "DELETE FROM b2b_product_prices WHERE user_id = ? AND product_id = ?",
            [$userId, $productId]
        );
    }

    /**
     * Get all product-specific prices for a user
     */
    public function getUserProductPrices($userId) {
        return $this->db->fetchAll(
            "SELECT bpp.*, p.name as product_name, p.sku, p.price as base_price
             FROM b2b_product_prices bpp
             INNER JOIN products p ON bpp.product_id = p.id
             WHERE bpp.user_id = ?",
            [$userId]
        );
    }

    /**
     * Get all users in a B2B group
     */
    public function getGroupUsers($groupId) {
        return $this->db->fetchAll(
            "SELECT u.*, bgu.created_at as added_to_group_at
             FROM users u
             INNER JOIN b2b_group_users bgu ON u.id = bgu.user_id
             WHERE bgu.b2b_group_id = ?",
            [$groupId]
        );
    }
}
?>

