<?php
require_once 'db/config.php';
require_once 'vendor/autoload.php';
$stripe_config = require_once 'config/stripe.php';

session_start();

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$message = '';
$error = false;

try {
    $pdo = db();
    $stmt = $pdo->prepare('SELECT * FROM subscriptions WHERE user_id = ? AND status = \'active\'');
    $stmt->execute([$_SESSION['user_id']]);
    $subscription = $stmt->fetch();

    if ($subscription) {
        \Stripe\Stripe::setApiKey($stripe_config['stripe']['secret_key']);
        
        // Cancel the subscription in Stripe
        $stripe_subscription = \Stripe\Subscription::update($subscription['stripe_subscription_id'], ['cancel_at_period_end' => true]);

        // Update the status in the local database
        $stmt = $pdo->prepare("UPDATE subscriptions SET status = 'canceled' WHERE id = ?");
        $stmt->execute([$subscription['id']]);

        $message = "Your subscription has been successfully canceled. You will have access until the end of the current billing period.";

    } else {
        $message = "No active subscription found to cancel.";
        $error = true;
    }
} catch (\Stripe\Exception\ApiErrorException $e) {
    $message = "Error canceling subscription: " . $e->getMessage();
    $error = true;
} catch (PDOException $e) {
    $message = "Database error: " . $e->getMessage();
    $error = true;
}

include 'templates/header.php';
?>

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-md-8 text-center">
            <div class="auth-container">
                <?php if ($error): ?>
                    <h2 class="text-danger">Cancellation Failed</h2>
                <?php else: ?>
                    <h2 class="text-success">Subscription Canceled</h2>
                <?php endif; ?>
                <p class="lead"><?php echo htmlspecialchars($message); ?></p>
                <a href="profile.php" class="btn btn-primary mt-3">Back to Profile</a>
            </div>
        </div>
    </div>
</div>

<?php include 'templates/footer.php'; ?>