34681-vm/subscribe.php
Flatlogic Bot 373e36aedb 0.1
2025-10-05 01:54:26 +00:00

54 lines
1.5 KiB
PHP

<?php
session_start();
require_once __DIR__ . '/db/config.php';
// 1. Check if user is logged in
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit();
}
// 2. Get the plan from the URL
$plan = $_GET['plan'] ?? null;
if ($plan !== 'monthly' && $plan !== 'yearly') {
// Redirect if plan is invalid
header('Location: pricing.php');
exit();
}
$user_id = $_SESSION['user_id'];
$start_date = new DateTime();
$end_date = new DateTime();
if ($plan === 'monthly') {
$end_date->modify('+1 month');
} elseif ($plan === 'yearly') {
$end_date->modify('+1 year');
}
$db = db();
// 3. Update user's subscription status
$stmt_user = $db->prepare("UPDATE users SET subscription_status = 'premium' WHERE id = ?");
$user_updated = $stmt_user->execute([$user_id]);
// 4. Create a record in the subscriptions table
$stmt_sub = $db->prepare("INSERT INTO subscriptions (user_id, plan, start_date, end_date) VALUES (?, ?, ?, ?)");
$subscription_created = $stmt_sub->execute([
$user_id,
$plan,
$start_date->format('Y-m-d H:i:s'),
$end_date->format('Y-m-d H:i:s')
]);
if ($user_updated && $subscription_created) {
// 5. Update session and redirect with success message
$_SESSION['subscription_status'] = 'premium';
$_SESSION['success_message'] = 'Welcome to Premium! You now have access to all courses.';
} else {
$_SESSION['error_message'] = 'There was an error processing your subscription. Please try again.';
}
header('Location: dashboard.php');
exit();