false, 'error' => 'Missing coupon code or plan ID']); exit; } global $subscriptions; if (!isset($subscriptions[$plan_id])) { echo json_encode(['success' => false, 'error' => 'Invalid plan']); exit; } $plan = $subscriptions[$plan_id]; // Fetch coupon details $stmt = db()->prepare('SELECT * FROM discounts WHERE code = ? AND is_active = 1'); $stmt->execute([$coupon_code]); $coupon = $stmt->fetch(); if (!$coupon) { echo json_encode(['success' => false, 'error' => 'Invalid or inactive coupon']); exit; } // Check date validity if (($coupon['start_date'] && strtotime($coupon['start_date']) > time()) || ($coupon['end_date'] && strtotime($coupon['end_date']) < time())) { echo json_encode(['success' => false, 'error' => 'Coupon is not valid at this time']); exit; } // Check usage limit if ($coupon['uses_limit'] !== null && $coupon['times_used'] >= $coupon['uses_limit']) { echo json_encode(['success' => false, 'error' => 'Coupon has reached its usage limit']); exit; } // Calculate discounted price $original_price = $plan['price'] / 100; $discounted_price = 0; if ($coupon['type'] === 'percentage') { $discounted_price = $original_price - ($original_price * ($coupon['value'] / 100)); } else { // fixed $discounted_price = $original_price - $coupon['value']; } if ($discounted_price < 0) { $discounted_price = 0; } echo json_encode(['success' => true, 'discounted_price' => $discounted_price]);