['min_range' => 1, 'max_range' => 10]]); $meals = filter_input(INPUT_POST, 'meals', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 10]]); $base_price_per_meal = 9.99; // Should match the price on pricing.php if ($people === false || $meals === false) { header('Location: pricing.php?error=invalid_input'); exit; } // --- Product Selection --- $selected_products = $_POST['products'] ?? []; $product_total_price = 0; $product_ids_for_metadata = []; $line_items = []; if (!empty($selected_products)) { $placeholders = implode(',', array_fill(0, count($selected_products), '?')); $stmt = db()->prepare("SELECT id, name, price FROM products WHERE id IN ($placeholders)"); $stmt->execute($selected_products); $products = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($products as $product) { $product_total_price += $product['price']; $product_ids_for_metadata[] = $product['id']; } } // --- Price Calculation --- $weekly_meal_price = $people * $meals * $base_price_per_meal; $weekly_total = $weekly_meal_price + $product_total_price; $monthly_price = $weekly_total * 4; // Approximate monthly price $plan_name = sprintf("Weekly plan for %d %s, %d %s per week", $people, ($people > 1 ? 'people' : 'person'), $meals, ($meals > 1 ? 'meals' : 'meal') ); if (!empty($products)) { $plan_name .= " with add-ons"; } // --- Stripe Checkout --- if ($stripe_config['stripe']['secret_key'] === 'YOUR_STRIPE_SECRET_KEY') { die('Error: Stripe secret key is not configured. Please update config/stripe.php with your actual Stripe keys.'); } \Stripe\Stripe::setApiKey($stripe_config['stripe']['secret_key']); $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http"; $host = $_SERVER['HTTP_HOST']; try { $checkout_session = \Stripe\Checkout\Session::create([ 'payment_method_types' => ['card'], 'line_items' => [[ 'price_data' => [ 'currency' => 'usd', 'product_data' => [ 'name' => $plan_name, ], 'unit_amount' => round($monthly_price * 100), // Price in cents 'recurring' => [ 'interval' => 'month', ], ], 'quantity' => 1, ]], 'mode' => 'subscription', 'success_url' => $protocol . '://' . $host . '/success.php?session_id={CHECKOUT_SESSION_ID}', 'cancel_url' => $protocol . '://' . $host . '/pricing.php', 'customer_email' => $_SESSION['user_email'] ?? null, 'metadata' => [ 'user_id' => $_SESSION['user_id'], 'people' => $people, 'meals_per_week' => $meals, 'product_ids' => json_encode($product_ids_for_metadata) // Add product IDs to metadata ] ]); header("Location: " . $checkout_session->url); exit; } catch (\Stripe\Exception\ApiErrorException $e) { error_log('Stripe API error: ' . $e->getMessage()); header('Location: pricing.php?error=stripe_error'); exit; } catch (Exception $e) { error_log('General error: ' . $e->getMessage()); header('Location: pricing.php?error=general_error'); exit; }