63 lines
1.8 KiB
PHP
63 lines
1.8 KiB
PHP
<?php
|
|
require_once '../db/config.php';
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
|
|
$coupon_code = $data['coupon_code'] ?? null;
|
|
$package_id = $data['package_id'] ?? null;
|
|
|
|
if (!$coupon_code || !$package_id) {
|
|
echo json_encode(['success' => false, 'error' => 'Missing coupon code or package ID']);
|
|
exit;
|
|
}
|
|
|
|
// Fetch package details
|
|
$stmt = db()->prepare('SELECT * FROM service_packages WHERE id = ?');
|
|
$stmt->execute([$package_id]);
|
|
$package = $stmt->fetch();
|
|
|
|
if (!$package) {
|
|
echo json_encode(['success' => false, 'error' => 'Invalid package']);
|
|
exit;
|
|
}
|
|
|
|
// 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 = $package['price'];
|
|
$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]);
|