<?php
/**
 * API: Calculate Discount
 * Calculates discount amount and final price for products or bills
 */

header('Content-Type: application/json');
session_start();

// Get POST data
$data = json_decode(file_get_contents('php://input'), true);

$originalAmount = isset($data['amount']) ? floatval($data['amount']) : 0;
$discount = isset($data['discount']) ? floatval($data['discount']) : 0;
$discountType = isset($data['discount_type']) ? $data['discount_type'] : 'PERCENTAGE';

if ($originalAmount == 0) {
    echo json_encode(['success' => false, 'message' => 'Amount is required']);
    exit();
}

try {
    $discountAmount = 0;
    $finalAmount = $originalAmount;
    
    if ($discount > 0) {
        if ($discountType == 'PERCENTAGE') {
            // Validate percentage is between 0 and 100
            if ($discount > 100) {
                echo json_encode(['success' => false, 'message' => 'Discount percentage cannot exceed 100%']);
                exit();
            }
            $discountAmount = round(($originalAmount * $discount) / 100, 2);
        } else {
            // AMOUNT type
            if ($discount > $originalAmount) {
                echo json_encode(['success' => false, 'message' => 'Discount amount cannot exceed original amount']);
                exit();
            }
            $discountAmount = $discount;
        }
        
        $finalAmount = $originalAmount - $discountAmount;
    }
    
    echo json_encode([
        'success' => true,
        'originalAmount' => round($originalAmount, 2),
        'discount' => $discount,
        'discountType' => $discountType,
        'discountAmount' => round($discountAmount, 2),
        'finalAmount' => round($finalAmount, 2),
        'discountPercentage' => $originalAmount > 0 ? round(($discountAmount / $originalAmount) * 100, 2) : 0
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error calculating discount: ' . $e->getMessage()
    ]);
}
?>
