redirectToLogin('Session expired. Please log in again.'); } // Initialize database try { $db = new Database(); $pdo = $db->getConnection(); } catch (Exception $e) { logError('Database connection failed in redemption.php: ' . $e->getMessage()); die('System error. Please try again later.'); } $errors = []; $success_message = ''; // Get user points $userPoints = ['points' => 0, 'total_earned' => 0, 'total_redeemed' => 0]; try { $stmt = $pdo->prepare("SELECT points, total_earned, total_redeemed FROM user_points WHERE user_id = ?"); $stmt->execute([$user['id']]); $pointsData = $stmt->fetch(); if ($pointsData) { $userPoints = $pointsData; } } catch (Exception $e) { logError('Error fetching user points', ['user_id' => $user['id'], 'error' => $e->getMessage()]); $errors[] = 'Unable to fetch your points balance.'; } // Check if user has minimum points for redemption if ($userPoints['points'] < 200) { header('Location: dashboard.php#rewards'); exit; } // Get UPI ID from profiler if exists $savedUpiId = ''; try { $stmt = $pdo->prepare("SELECT response FROM user_profiler WHERE user_id = ? AND section = 'communication_payments' AND question_id = 'upi_id'"); $stmt->execute([$user['id']]); $upiData = $stmt->fetch(); if ($upiData) { $savedUpiId = json_decode($upiData['response'], true); } } catch (Exception $e) { logError('Error fetching UPI ID', ['user_id' => $user['id'], 'error' => $e->getMessage()]); } // Handle form submission if ($_SERVER['REQUEST_METHOD'] === 'POST') { $pointsToRedeem = isset($_POST['points_to_redeem']) ? intval($_POST['points_to_redeem']) : 0; $upiId = isset($_POST['upi_id']) ? sanitize($_POST['upi_id']) : ''; // Validation if ($pointsToRedeem < 200) { $errors[] = 'Minimum redemption amount is 200 points (₹100).'; } elseif ($pointsToRedeem > $userPoints['points']) { $errors[] = 'You cannot redeem more points than your available balance.'; } elseif ($pointsToRedeem % 10 !== 0) { $errors[] = 'Points must be redeemed in multiples of 10.'; } elseif (empty($upiId)) { $errors[] = 'Please enter your UPI ID.'; } elseif (!preg_match('/^[\w\.-]+@[\w\.-]+$/', $upiId)) { $errors[] = 'Please enter a valid UPI ID (e.g., yourname@paytm).'; } else { try { $pdo->beginTransaction(); // Generate unique request ID $requestId = 'RRR' . date('Ymd') . sprintf('%04d', mt_rand(1000, 9999)); // Calculate amount in INR $amountInr = $pointsToRedeem * 0.5; // Create redemption request $stmt = $pdo->prepare("INSERT INTO redemption_requests (user_id, request_id, points_redeemed, amount_inr, upi_id, status) VALUES (?, ?, ?, ?, ?, 'pending')"); $stmt->execute([$user['id'], $requestId, $pointsToRedeem, $amountInr, $upiId]); // Deduct points from user account $stmt = $pdo->prepare("UPDATE user_points SET points = points - ?, total_redeemed = total_redeemed + ? WHERE user_id = ?"); $stmt->execute([$pointsToRedeem, $pointsToRedeem, $user['id']]); // Add transaction record $stmt = $pdo->prepare("INSERT INTO point_transactions (user_id, transaction_type, points, source, description, reference_id, status) VALUES (?, 'redeemed', ?, 'redemption', ?, ?, 'pending')"); $description = "UPI redemption request - ₹" . number_format($amountInr, 2) . " to " . $upiId; $stmt->execute([$user['id'], $pointsToRedeem, $description, $requestId]); // Save UPI ID to profiler if not already saved if ($upiId !== $savedUpiId) { $stmt = $pdo->prepare("INSERT INTO user_profiler (user_id, section, question_id, response) VALUES (?, 'communication_payments', 'upi_id', ?) ON DUPLICATE KEY UPDATE response = ?, updated_at = NOW()"); $upiJson = json_encode($upiId); $stmt->execute([$user['id'], $upiJson, $upiJson]); // Check if this completes the communication_payments section and award points $stmt = $pdo->prepare("SELECT COUNT(*) as completed_questions FROM user_profiler WHERE user_id = ? AND section = 'communication_payments'"); $stmt->execute([$user['id']]); $completedCount = $stmt->fetch()['completed_questions']; // If this is a new UPI ID entry, check for section completion if ($completedCount >= 8) { // Assuming 8 questions in communication_payments section $stmt = $pdo->prepare("SELECT points_awarded FROM profiler_completion WHERE user_id = ? AND section = 'communication_payments'"); $stmt->execute([$user['id']]); $completion = $stmt->fetch(); if (!$completion || !$completion['points_awarded']) { // Award section completion points $stmt = $pdo->prepare("INSERT INTO user_points (user_id, points, total_earned) VALUES (?, 10.00, 10.00) ON DUPLICATE KEY UPDATE points = points + 10.00, total_earned = total_earned + 10.00"); $stmt->execute([$user['id']]); $stmt = $pdo->prepare("INSERT INTO point_transactions (user_id, transaction_type, points, source, description) VALUES (?, 'earned', 10.00, 'profiler_communication_payments', 'Communication & Payments section completion')"); $stmt->execute([$user['id']]); $stmt = $pdo->prepare("INSERT INTO profiler_completion (user_id, section, total_questions, answered_questions, completion_percentage, is_completed, points_awarded, completed_at) VALUES (?, 'communication_payments', 8, ?, 100.00, 1, 1, NOW()) ON DUPLICATE KEY UPDATE answered_questions = ?, completion_percentage = 100.00, is_completed = 1, points_awarded = 1, completed_at = NOW()"); $stmt->execute([$user['id'], $completedCount, $completedCount]); } } } $pdo->commit(); logError('Redemption request created', [ 'user_id' => $user['id'], 'request_id' => $requestId, 'points_redeemed' => $pointsToRedeem, 'amount_inr' => $amountInr, 'upi_id' => $upiId ]); $success_message = "Redemption request submitted successfully! Request ID: $requestId"; // Update user points for display $userPoints['points'] -= $pointsToRedeem; $userPoints['total_redeemed'] += $pointsToRedeem; } catch (Exception $e) { $pdo->rollback(); logError('Error creating redemption request', ['user_id' => $user['id'], 'error' => $e->getMessage()]); $errors[] = 'Error processing your redemption request. Please try again.'; } } } // Get recent redemption requests $recentRedemptions = []; try { $stmt = $pdo->prepare("SELECT request_id, points_redeemed, amount_inr, upi_id, status, created_at, processed_at FROM redemption_requests WHERE user_id = ? ORDER BY created_at DESC LIMIT 5"); $stmt->execute([$user['id']]); $recentRedemptions = $stmt->fetchAll(); } catch (Exception $e) { logError('Error fetching redemption history', ['user_id' => $user['id'], 'error' => $e->getMessage()]); } ?>
Convert your earned points to cash via instant UPI transfer
What happens next?
Worth ₹
1 Point = ₹0.50
Minimum redemption: 200 points (₹100)₹ ( points)
to