<?php

if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}

function updatePartnerVariationProfit(int $partner_user_id, int $variation_id, string $extra_price, bool $is_active): bool {
    try {
        $sql = "INSERT INTO partner_variation_profits (partner_user_id, variation_id, extra_price, is_active, updated_at) 
                VALUES (?, ?, ?, ?, NOW())
                ON DUPLICATE KEY UPDATE 
                extra_price = VALUES(extra_price), 
                is_active = VALUES(is_active), 
                updated_at = NOW()";
        
        $stmt = pdo()->prepare($sql);
        return $stmt->execute([$partner_user_id, $variation_id, $extra_price, $is_active]);
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error updating partner variation profit (Partner: {$partner_user_id}, Var: {$variation_id}): " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}

function getPartnerVariationProfit(int $partner_user_id, int $variation_id): ?array {
    try {
        $stmt = pdo()->prepare("SELECT * FROM partner_variation_profits 
                                      WHERE partner_user_id = ? AND variation_id = ?");
        $stmt->execute([$partner_user_id, $variation_id]);
        return $stmt->fetch() ?: null;
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting partner variation profit (Partner: {$partner_user_id}, Var: {$variation_id}): " . $e->getMessage() . "\n", FILE_APPEND);
        return null;
    }
}

function getPartnerVariationProfitsForProduct(int $partner_user_id, int $product_id): array {
    try {
        $stmt = pdo()->prepare("SELECT pvp.* FROM partner_variation_profits pvp
                                      JOIN product_variations pv ON pvp.variation_id = pv.id
                                      WHERE pvp.partner_user_id = ? AND pv.product_id = ?");
        $stmt->execute([$partner_user_id, $product_id]);
        
        $profits = [];
        while ($row = $stmt->fetch()) {
            $profits[$row['variation_id']] = $row;
        }
        return $profits;
        
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting partner profits for product (Partner: {$partner_user_id}, Prod: {$product_id}): " . $e->getMessage() . "\n", FILE_APPEND);
        return [];
    }
}

?>