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

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

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

$action = $_POST['action'] ?? '';
$clubModel = new Club();
$clubManagerModel = new ClubManager();

// Verify club ownership
$club = $clubManagerModel->getClubByManagerId($_SESSION['user_id']);
$posted_club_id = filter_input(INPUT_POST, 'club_id', FILTER_VALIDATE_INT);

if (!$club || $club->id != $posted_club_id) {
    header('Location: my_club.php?error=auth_failed');
    exit();
}

try {
    if ($action === 'create') {
        $data = [
            'club_id' => $club->id,
            'name' => trim($_POST['name']),
            'description' => trim($_POST['description']),
            'price' => filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT),
            'duration_type' => $_POST['duration_type']
        ];
        $clubModel->createMembershipPackage($data);

    } elseif ($action === 'update') {
        $data = [
            'id' => filter_input(INPUT_POST, 'package_id', FILTER_VALIDATE_INT),
            'club_id' => $club->id,
            'name' => trim($_POST['name']),
            'description' => trim($_POST['description']),
            'price' => filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT),
            'duration_type' => $_POST['duration_type'],
            'is_active' => filter_input(INPUT_POST, 'is_active', FILTER_VALIDATE_INT)
        ];
        $clubModel->updateMembershipPackage($data);
    }

    header('Location: club_membership_packages.php?status=success');

} catch (Exception $e) {
    header('Location: club_membership_packages.php?status=error&error=' . urlencode($e->getMessage()));
}
exit();
?>