<?php
header('Content-Type: application/json');
include '../db.php';
include '../includes/tax_helpers.php';

// Get POST data
$cart_json = $_POST['cart_json'] ?? '[]';
$payment_method = $_POST['payment_method'] ?? 'cash';
$discount_value = floatval($_POST['discount_value'] ?? 0);
$discount_type = $_POST['discount_type'] ?? 'percent';

// Decode cart items
$cart_items = json_decode($cart_json, true);
if (!is_array($cart_items)) {
    $cart_items = [];
}

// Calculate tax based on current system setting
$tax_result = calculateTax($conn, $cart_items, $payment_method);

// Apply discount
$subtotal = $tax_result['subtotal'];
$discount_amount = 0;
$discount_id = null;

// Check if discount is from predefined discounts (has cap)
$discount_id_param = $_POST['discount_id'] ?? null;
if ($discount_id_param) {
    $discount_stmt = $conn->prepare("SELECT * FROM discounts WHERE id = ? AND is_active = 1");
    $discount_stmt->bind_param("i", $discount_id_param);
    $discount_stmt->execute();
    $discount_result = $discount_stmt->get_result();
    
    if ($discount_row = $discount_result->fetch_assoc()) {
        $discount_id = $discount_row['id'];
        
        if ($discount_row['discount_type'] === 'percentage') {
            $discount_amount = $subtotal * ($discount_row['discount_rate'] / 100);
        } else {
            $discount_amount = $discount_row['discount_rate'];
        }
        
        // Apply cap if exists
        if ($discount_row['discount_cap'] && $discount_amount > $discount_row['discount_cap']) {
            $discount_amount = $discount_row['discount_cap'];
        }
    }
    $discount_stmt->close();
} else {
    // Manual discount calculation
    if ($discount_type === 'percent') {
        $discount_amount = $subtotal * ($discount_value / 100);
    } elseif ($discount_type === 'fixed') {
        $discount_amount = $discount_value;
    }
}

// Don't exceed subtotal
if ($discount_amount > $subtotal) {
    $discount_amount = $subtotal;
}

$discounted_subtotal = $subtotal - $discount_amount;
$final_total = $discounted_subtotal + $tax_result['tax_amount'];

// Get payment method tax rate for display
$payment_tax_rate = getPaymentMethodTaxRate($conn, $payment_method);
$tax_method = getTaxCalculationMethod($conn);

// Prepare response
$response = [
    'success' => true,
    'tax_amount' => $tax_result['tax_amount'],
    'subtotal' => $subtotal,
    'discount_amount' => $discount_amount,
    'discounted_subtotal' => $discounted_subtotal,
    'total' => $final_total,
    'payment_tax_rate' => $payment_tax_rate,
    'tax_method' => $tax_method,
    'tax_method_display' => getTaxMethodDisplayName($tax_method),
    'payment_method' => $payment_method,
    'discount_id' => $discount_id
];

echo json_encode($response);
?>
