<?php
require 'stripe/init.php'; // Must have stripe/stripe-php via Composer

\Stripe\Stripe::setApiKey('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'); // 🔁 Replace with your actual Stripe Secret Key
//\Stripe\Stripe::setApiKey('sk_test_51IiIECGG4CyVWk0NCcBMTtwzd2X2QIZedT2NrSKIrYBDesLWP8E9LCTsW7wuyR19tbUC7018RmGpWdERw2nMdP0q00Gsc33xLp'); // 🔁 Replace with your actual Stripe Secret Key


// ✅ Courses array
$courses = [
    "kursus-i" => ["title" => "Kursus I", "price" => 1795, "installments" => 3],
    "kursus-ii" => ["title" => "Kursus II", "price" => 1995, "installments" => 2],
    "masterclass" => ["title" => "Masterclass", "price" => 2495, "installments" => 2],
    "samlet-tilmelding-i-ii" => ["title" => "Samlet tilmelding I & II", "price" => 2995, "installments" => 3],
    "samlet-tilmelding-i-ii-mc" => ["title" => "Samlet tilmelding I II & MC", "price" => 4995, "installments" => 3],
    "fortaellervinkler" => ["title" => "Fortællervinkler", "price" => 3495, "installments" => 3],
    "coach-1-month" => ["title" => "Coach – 1 month", "price" => 3495, "installments" => 2],
    "coach-3-months" => ["title" => "Coach – 3 months", "price" => 5995, "installments" => 3],
    "coach-6-months" => ["title" => "Coach – 6 months", "price" => 15995, "installments" => 6],
    "born-and-unge" => ["title" => "Born and unge", "price" => 1895, "installments" => 2],
];


// ✅ Return from Stripe – process subscription
if (isset($_GET['session_id']) && isset($_GET['course'])) {
    $session_id = $_GET['session_id'];
    $slug = $_GET['course'];

    if (!isset($courses[$slug])) {
        die("❌ Invalid course selected on return.");
    }

    $course = $courses[$slug];
    $installments = $course['installments'];

    try {
        $session = \Stripe\Checkout\Session::retrieve($session_id);
        $subscription = \Stripe\Subscription::retrieve($session->subscription);

        // Calculate cancel date
        $start = $subscription->current_period_start;
        $cancel_at = strtotime("+$installments months", $start);

        // ✅ Fix: Only set cancel_at (Stripe sets cancel_at_period_end automatically)
        \Stripe\Subscription::update($subscription->id, [
            'cancel_at' => $cancel_at,
        ]);

        // echo "<h2>✅ Subscription created for {$course['title']}</h2>";
        // echo "<p>Total: {$course['price']} DKK — {$installments} installments</p>";
        // echo "<p>It will automatically cancel after {$installments} month(s).</p>";
        // exit;
        header("Location: https://www.forfatterskole.dk/");
        exit;

    } catch (Exception $e) {
        echo "❌ Stripe error on return: " . $e->getMessage();
        exit;
    }
}


// ✅ Initial checkout request
$slug = isset($_GET['course']) ? strtolower(trim($_GET['course'])) : '';
if (!isset($courses[$slug])) {
    die("❌ Invalid course selected.");
}

$course = $courses[$slug];
$title = $course['title'];
$amount = $course['price'];
$installments = $course['installments'];
$installmentAmount = round(($amount / $installments) * 100); // in cents

try {
    // 🛍️ Create Stripe Product
    $product = \Stripe\Product::create([
        'name' => $title,
        'description' => "Installment Plan Auto-stop after $installments month(s). Total: $amount DKK"
    ]);

    // 💳 Create Recurring Price
    $price = \Stripe\Price::create([
        'unit_amount' => $installmentAmount,
        'currency' => 'dkk',
        'recurring' => ['interval' => 'month'],
        'product' => $product->id,
    ]);

    // ✅ Checkout session
    $session = \Stripe\Checkout\Session::create([
        'mode' => 'subscription',
        'line_items' => [[
            'price' => $price->id,
            'quantity' => 1,
        ]],
        'success_url' => 'https://malikubaid.com/stripe/installment.php?session_id={CHECKOUT_SESSION_ID}&course=' . $slug,
        'cancel_url' => 'https://yourdomain.com/cancelled',
    ]);

    // 🔁 Redirect to Stripe
    header("Location: " . $session->url);
    exit;

} catch (Exception $e) {
    echo "❌ Stripe error on checkout: " . $e->getMessage();
}