<?php
// app/Helpers/CouponHelper.php

class CouponHelper {
    /**
     * Calculate discount for a coupon based on product/category restrictions.
     */
    public static function calculateDiscount($coupon, $items, $subtotal) {
        if (!$coupon) return 0;
        
        $restrictedSubtotal = 0;
        $hasRestriction = false;
        
        if (!empty($coupon['product_id'])) {
            $hasRestriction = true;
            foreach ($items as $item) {
                $productId = $item['product_id'] ?? $item['id'] ?? null;
                if ($productId == $coupon['product_id']) {
                    $qty = $item['quantity'] ?? $item['qty'] ?? 0;
                    $restrictedSubtotal += (floatval($item['price']) * intval($qty));
                }
            }
        } elseif (!empty($coupon['category_id'])) {
            $hasRestriction = true;
            $db = getDB();
            foreach ($items as $item) {
                $productId = $item['product_id'] ?? $item['id'] ?? null;
                if ($productId) {
                    $catStmt = $db->prepare('SELECT category_id FROM products WHERE id = ? LIMIT 1');
                    $catStmt->execute([$productId]);
                    $catId = $catStmt->fetchColumn();
                    if ($catId == $coupon['category_id']) {
                        $qty = $item['quantity'] ?? $item['qty'] ?? 0;
                        $restrictedSubtotal += (floatval($item['price']) * intval($qty));
                    }
                }
            }
        }
        
        if (!$hasRestriction) {
            $restrictedSubtotal = $subtotal;
        }
        
        if ($coupon['type'] === 'percentage') {
            return $restrictedSubtotal * (floatval($coupon['value']) / 100);
        } else {
            return min($restrictedSubtotal, floatval($coupon['value']));
        }
    }
}
