<?php
require_once '../core/bootstrap.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: memberships.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$package_id = filter_input(INPUT_POST, 'package_id', FILTER_VALIDATE_INT);

if (!$package_id) {
    header('Location: memberships.php?status=error');
    exit();
}

$clubModel = new Club();
$package = $clubModel->getMembershipPackageById($package_id);

if (!$package) {
    header('Location: memberships.php?status=error&reason=invalid_package');
    exit();
}

// Calculate expiry date based on package duration
$expiry_date = date('Y-m-d');
if ($package->duration_type === 'monthly') {
    $expiry_date = date('Y-m-d', strtotime('+1 month'));
} elseif ($package->duration_type === 'termly') { // Assuming termly is 3 months
    $expiry_date = date('Y-m-d', strtotime('+3 months'));
} elseif ($package->duration_type === 'yearly') {
    $expiry_date = date('Y-m-d', strtotime('+1 year'));
}

$data = [
    'user_id' => $user_id,
    'club_id' => $package->club_id,
    'membership_type' => $package->name,
    'start_date' => date('Y-m-d'),
    'expiry_date' => $expiry_date
];

if ($clubModel->createMembership($data)) {
    // In a real app, you would redirect to a payment gateway here, passing the package price.
    header('Location: memberships.php?status=success');
} else {
    header('Location: memberships.php?status=error');
}
exit();
?>