<?php
/**
 * Tax Helper Functions for ITRPOS
 * Supports both item-wise and payment method-based tax calculations
 */

/**
 * Get system setting value
 * @param mysqli $conn Database connection
 * @param string $code Setting code
 * @param string $default Default value if setting not found
 * @return string Setting value
 */
function getSetting($conn, $code, $default = '') {
    $stmt = $conn->prepare("SELECT value FROM settings WHERE code = ? AND is_active = 1");
    $stmt->bind_param("s", $code);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    return $row ? $row['value'] : $default;
}

/**
 * Get current tax calculation method
 * @param mysqli $conn Database connection
 * @return string 'item_wise' or 'payment_method'
 */
function getTaxCalculationMethod($conn) {
    return getSetting($conn, 'tax_calculation_method', 'item_wise');
}

/**
 * Get payment method tax rate
 * @param mysqli $conn Database connection
 * @param string $payment_method Payment method name
 * @return float Tax rate percentage
 */
function getPaymentMethodTaxRate($conn, $payment_method) {
    $stmt = $conn->prepare("SELECT tax_rate FROM payment_method_tax_rates WHERE payment_method = ? AND is_active = 1");
    $stmt->bind_param("s", $payment_method);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    return $row ? (float)$row['tax_rate'] : 0.00;
}

/**
 * Get all payment method tax rates
 * @param mysqli $conn Database connection
 * @return array Array of payment methods with their tax rates
 */
function getAllPaymentMethodTaxRates($conn) {
    $rates = [];
    $result = $conn->query("SELECT payment_method, tax_rate FROM payment_method_tax_rates WHERE is_active = 1 ORDER BY payment_method");
    while ($row = $result->fetch_assoc()) {
        $rates[$row['payment_method']] = (float)$row['tax_rate'];
    }
    return $rates;
}

/**
 * Calculate tax based on current system setting
 * @param mysqli $conn Database connection
 * @param array $cart_items Array of cart items
 * @param string $payment_method Payment method (only used if payment method tax is enabled)
 * @return array Array with 'tax_amount', 'subtotal', 'total' keys
 */
function calculateTax($conn, $cart_items, $payment_method = 'cash') {
    $tax_method = getTaxCalculationMethod($conn);
    
    if ($tax_method === 'payment_method') {
        return calculatePaymentMethodTax($conn, $cart_items, $payment_method);
    } else {
        return calculateItemWiseTax($conn, $cart_items);
    }
}

/**
 * Calculate tax using payment method rates
 * @param mysqli $conn Database connection
 * @param array $cart_items Array of cart items
 * @param string $payment_method Payment method
 * @return array Array with 'tax_amount', 'subtotal', 'total' keys
 */
function calculatePaymentMethodTax($conn, $cart_items, $payment_method) {
    $payment_tax_rate = getPaymentMethodTaxRate($conn, $payment_method);
    $taxable_subtotal = 0;
    $nil_tax_subtotal = 0;
    
    // Separate taxable and nil-tax items
    foreach ($cart_items as $item) {
        $price = (float)$item['price'];
        $qty = (int)$item['qty'];
        $tax_type = $item['tax_type'] ?? 'excluded';
        $item_tax_rate = (float)($item['tax_rate'] ?? 0);
        
        if ($tax_type === 'nil') {
            // Nil tax items are completely tax-exempt
            $nil_tax_subtotal += $price * $qty;
        } elseif ($tax_type === 'included') {
            // If tax is included in price, extract the base price for payment method tax calculation
            $base_price = $price / (1 + ($item_tax_rate / 100));
            $taxable_subtotal += $base_price * $qty;
        } else {
            // If tax is excluded, use the price as is for payment method tax calculation
            $taxable_subtotal += $price * $qty;
        }
    }
    
    // Calculate tax only on taxable items (exclude nil-tax items)
    $tax_amount = $taxable_subtotal * ($payment_tax_rate / 100);
    $total_subtotal = $taxable_subtotal + $nil_tax_subtotal;
    $total = $total_subtotal + $tax_amount;
    
    return [
        'tax_amount' => round($tax_amount, 2),
        'subtotal' => round($total_subtotal, 2),
        'total' => round($total, 2),
        'tax_rate' => $payment_tax_rate,
        'taxable_subtotal' => round($taxable_subtotal, 2),
        'nil_tax_subtotal' => round($nil_tax_subtotal, 2)
    ];
}

/**
 * Calculate tax using item-wise rates (current system)
 * @param mysqli $conn Database connection
 * @param array $cart_items Array of cart items
 * @return array Array with 'tax_amount', 'subtotal', 'total' keys
 */
function calculateItemWiseTax($conn, $cart_items) {
    $subtotal = 0;
    $total_tax = 0;
    $grand_total = 0;
    
    foreach ($cart_items as $item) {
        $price = (float)$item['price'];
        $qty = (int)$item['qty'];
        $tax_type = $item['tax_type'] ?? 'excluded';
        $tax_rate = (float)($item['tax_rate'] ?? 0);
        
        $base_price = 0;
        $tax_amount = 0;
        $item_total = 0;
        
        if ($tax_type === 'excluded') {
            $base_price = $price * $qty;
            $tax_amount = $base_price * ($tax_rate / 100);
            $item_total = $base_price + $tax_amount;
        } elseif ($tax_type === 'included') {
            $item_total = $price * $qty;
            $base_price = $item_total / (1 + ($tax_rate / 100));
            $tax_amount = $item_total - $base_price;
        } else {
            // nil tax
            $base_price = $price * $qty;
            $tax_amount = 0;
            $item_total = $base_price;
        }
        
        $subtotal += $base_price;
        $total_tax += $tax_amount;
        $grand_total += $item_total;
    }
    
    return [
        'tax_amount' => round($total_tax, 2),
        'subtotal' => round($subtotal, 2),
        'total' => round($grand_total, 2),
        'tax_rate' => 0 // Not applicable for item-wise tax
    ];
}

/**
 * Check if payment method tax preview is enabled
 * @param mysqli $conn Database connection
 * @return bool True if enabled
 */
function isTaxPreviewEnabled($conn) {
    return getSetting($conn, 'enable_tax_preview_on_payment', '1') === '1';
}

/**
 * Check if payment method tax rates should be shown on POS
 * @param mysqli $conn Database connection
 * @return bool True if should be shown
 */
function shouldShowPaymentMethodTaxRates($conn) {
    return getSetting($conn, 'show_payment_method_tax_rates', '1') === '1';
}

/**
 * Get tax calculation method display name
 * @param string $method Tax calculation method
 * @return string Display name
 */
function getTaxMethodDisplayName($method) {
    switch ($method) {
        case 'item_wise':
            return 'Item-wise Tax';
        case 'payment_method':
            return 'Payment Method Tax';
        default:
            return 'Unknown';
    }
}

/**
 * Validate payment method tax rate
 * @param float $rate Tax rate
 * @return bool True if valid
 */
function isValidTaxRate($rate) {
    return is_numeric($rate) && $rate >= 0 && $rate <= 100;
}

/**
 * Format tax rate for display
 * @param float $rate Tax rate
 * @return string Formatted rate
 */
function formatTaxRate($rate) {
    return number_format($rate, 2) . '%';
}

/**
 * Check if an item is tax exempt (nil tax type)
 * @param string $tax_type Tax type ('included', 'excluded', 'nil')
 * @return bool True if tax exempt
 */
function isTaxExempt($tax_type) {
    return $tax_type === 'nil';
}

/**
 * Get tax status description for display
 * @param string $tax_type Tax type
 * @param float $tax_rate Tax rate percentage
 * @return string Human readable tax status
 */
function getTaxStatusDescription($tax_type, $tax_rate = 0) {
    switch ($tax_type) {
        case 'nil':
            return 'Tax Exempt (Nil)';
        case 'included':
            return 'Tax Included (' . formatTaxRate($tax_rate) . ')';
        case 'excluded':
            return 'Tax Excluded (' . formatTaxRate($tax_rate) . ')';
        default:
            return 'Unknown Tax Status';
    }
}
?>
