<?php
// includes/helpers.php

/**
 * Translates a status or payment method key into a human-readable string using the t() function.
 *
 * @param string $key The key to translate (e.g., 'pending_payment', 'bank_transfer').
 * @return string The translated string.
 */
function get_status_translation(string $key): string {
    // A set of known payment methods to prefix correctly.
    $payment_methods = ['bank_transfer', 'online', 'credit'];

    if (in_array($key, $payment_methods)) {
        // It's a payment method, use 'payment_' prefix.
        $translation_key = 'payment_' . $key;
    } else {
        // Assume it's an order status, use 'status_' prefix.
        $translation_key = 'status_' . $key;
    }

    $translated = t($translation_key);

    // If the translation key is returned, it means no translation was found.
    // In that case, we provide a clean fallback.
    if ($translated === $translation_key) {
        return ucfirst(str_replace('_', ' ', $key));
    }

    return $translated;
}

function get_item_status_translation(string $key): string {
    $translation_key = 'status_' . $key;
    $translated = t($translation_key);
    if ($translated === $translation_key) {
        return ucfirst(str_replace('_', ' ', $key));
    }
    return $translated;
}


function sanitize_filename($filename) {
    // Keep the original extension
    $extension = pathinfo($filename, PATHINFO_EXTENSION);
    $filename_without_ext = pathinfo($filename, PATHINFO_FILENAME);

    // Replace spaces and special characters with underscores in the filename part
    $sanitized_filename = preg_replace('/[\s\/:*?"<>|.]+/', '_', $filename_without_ext);

    // Remove any leading/trailing underscores
    $sanitized_filename = trim($sanitized_filename, '_');

    // Ensure the filename is not empty
    if (empty($sanitized_filename)) {
        $sanitized_filename = 'unnamed_file';
    }

    // Re-append the extension if it exists
    if (!empty($extension)) {
        return $sanitized_filename . '.' . $extension;
    }

    return $sanitized_filename;
}

function upload_error_message($error_code) {
    switch ($error_code) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        case UPLOAD_ERR_PARTIAL:
            return 'The uploaded file was only partially uploaded';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Missing a temporary folder';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Failed to write file to disk.';
        case UPLOAD_ERR_EXTENSION:
            return 'A PHP extension stopped the file upload.';
        default:
            return 'Unknown upload error';
    }
}

function getEffectivePrice(PDO $db, int $productId, ?int $clientId): array {
    $logFile = 'debug_price.log';
    $vatRate = 1.23;
    $net = null;
    $gross = null;
    $priceFound = false;

    file_put_contents($logFile, "---\nSTART getEffectivePrice for product $productId, client $clientId\n", FILE_APPEND);

    // Priority A: Try to fetch from client_prices
    if ($clientId) {
        $stmt = $db->prepare("SELECT price_net, price_gross FROM client_prices WHERE client_id = :client_id AND product_id = :product_id LIMIT 1");
        $stmt->execute(['client_id' => $clientId, 'product_id' => $productId]);
        $priceRow = $stmt->fetch(PDO::FETCH_ASSOC);
        file_put_contents($logFile, "Client price query executed. Found: " . ($priceRow ? json_encode($priceRow) : 'No') . "\n", FILE_APPEND);

        if ($priceRow) {
            $net = $priceRow['price_net'] !== null ? (float)$priceRow['price_net'] : null;
            $gross = $priceRow['price_gross'] !== null ? (float)$priceRow['price_gross'] : null;

            if ($net !== null || $gross !== null) {
                $priceFound = true;
                file_put_contents($logFile, "Found client price. Net: $net, Gross: $gross\n", FILE_APPEND);
            }
        }
    }

    // Priority B: Fallback to product base prices if no client-specific price was found
    if (!$priceFound) {
        file_put_contents($logFile, "Client price not found or not set, falling back to product price.\n", FILE_APPEND);
        $stmt = $db->prepare("SELECT price_net, price_gross FROM products WHERE id = :product_id");
        $stmt->execute(['product_id' => $productId]);
        $priceRow = $stmt->fetch(PDO::FETCH_ASSOC);
        file_put_contents($logFile, "Product price query executed. Found: " . ($priceRow ? json_encode($priceRow) : 'No') . "\n", FILE_APPEND);

        if ($priceRow) {
            $net = $priceRow['price_net'] !== null ? (float)$priceRow['price_net'] : null;
            $gross = $priceRow['price_gross'] !== null ? (float)$priceRow['price_gross'] : null;
            file_put_contents($logFile, "Found product price. Net: $net, Gross: $gross\n", FILE_APPEND);
        }
    }

    // If we have one price, calculate the other
    if ($gross !== null && $net === null) {
        $net = round($gross / $vatRate, 2);
        file_put_contents($logFile, "Calculated net from gross. New net: $net\n", FILE_APPEND);
    } elseif ($net !== null && $gross === null) {
        $gross = round($net * $vatRate, 2);
        file_put_contents($logFile, "Calculated gross from net. New gross: $gross\n", FILE_APPEND);
    }

    // Sanity check: gross must not be less than net. If so, log it and fix it.
    if ($gross !== null && $net !== null && $gross < $net) {
        error_log("Price inconsistency for product ID $productId: gross ($gross) is less than net ($net). Recalculating net from gross.");
        $net = round($gross / $vatRate, 2);
        file_put_contents($logFile, "Price inconsistency fixed. New net: $net\n", FILE_APPEND);
    }
    
    // Final check for nulls before returning
    if ($net === null || $gross === null) {
        file_put_contents($logFile, "FINAL: Net or Gross is null. Returning 0.0 for both.\n---\n", FILE_APPEND);
        return ['net' => 0.0, 'gross' => 0.0];
    }

    file_put_contents($logFile, "FINAL: Returning Net: $net, Gross: $gross\n---\n", FILE_APPEND);
    return ['net' => $net, 'gross' => $gross];
}

function get_site_url() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $host = $_SERVER['HTTP_HOST'];
    return $protocol . $host;
}