80 lines
2.3 KiB
PHP
80 lines
2.3 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'db/config.php';
|
|
|
|
if (!isset($_SESSION['user_id'])) {
|
|
header('Location: login.php');
|
|
exit();
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['reward'])) {
|
|
header('Location: rewards.php');
|
|
exit();
|
|
}
|
|
|
|
$user_id = $_SESSION['user_id'];
|
|
$reward = $_POST['reward'];
|
|
|
|
$rewards = [
|
|
'5_off' => [
|
|
'points' => 500,
|
|
'discount' => 5,
|
|
'type' => 'fixed'
|
|
]
|
|
];
|
|
|
|
if (!array_key_exists($reward, $rewards)) {
|
|
$_SESSION['error_message'] = 'Invalid reward selected.';
|
|
header('Location: rewards.php');
|
|
exit();
|
|
}
|
|
|
|
$reward_details = $rewards[$reward];
|
|
$points_required = $reward_details['points'];
|
|
|
|
$pdo = db();
|
|
|
|
// Get user's current points
|
|
$stmt = $pdo->prepare("SELECT points FROM user_rewards WHERE user_id = ?");
|
|
$stmt->execute([$user_id]);
|
|
$user_reward = $stmt->fetch();
|
|
|
|
$current_points = $user_reward ? $user_reward['points'] : 0;
|
|
|
|
if ($current_points < $points_required) {
|
|
$_SESSION['error_message'] = 'You do not have enough points to redeem this reward.';
|
|
header('Location: rewards.php');
|
|
exit();
|
|
}
|
|
|
|
// Deduct points and create coupon
|
|
try {
|
|
$pdo->beginTransaction();
|
|
|
|
// Deduct points
|
|
$new_points = $current_points - $points_required;
|
|
$stmt = $pdo->prepare("UPDATE user_rewards SET points = ? WHERE user_id = ?");
|
|
$stmt->execute([$new_points, $user_id]);
|
|
|
|
// Log history
|
|
$stmt = $pdo->prepare("INSERT INTO reward_history (user_id, points_change, reason) VALUES (?, ?, ?)");
|
|
$stmt->execute([$user_id, -$points_required, 'Redeemed ' . $reward]);
|
|
|
|
// Create coupon
|
|
$coupon_code = 'REWARD-' . strtoupper(bin2hex(random_bytes(4))) . '-' . $user_id;
|
|
$stmt = $pdo->prepare("INSERT INTO coupons (code, type, value, expires_at, is_active) VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 30 DAY), 1)");
|
|
$stmt->execute([$coupon_code, $reward_details['type'], $reward_details['discount']]);
|
|
|
|
$pdo->commit();
|
|
|
|
$_SESSION['success_message'] = 'Reward redeemed successfully! Your coupon code is: ' . $coupon_code;
|
|
header('Location: rewards.php');
|
|
exit();
|
|
|
|
} catch (Exception $e) {
|
|
$pdo->rollBack();
|
|
$_SESSION['error_message'] = 'There was an error redeeming your reward. Please try again.';
|
|
error_log($e->getMessage());
|
|
header('Location: rewards.php');
|
|
exit();
|
|
} |