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

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

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

$package_id = filter_input(INPUT_POST, 'package_id', FILTER_VALIDATE_INT);
$payment_method = $_POST['payment_method'] ?? 'gateway';
if (!$package_id) {
    header('Location: memberships.php?error=invalid_package');
    exit();
}

$clubModel = new Club();
$userModel = new User();
$settingModel = new Setting();
$settings = $settingModel->getAll();

$package = $clubModel->getMembershipPackageById($package_id);
$user = $userModel->getFullUserDetailsById($_SESSION['user_id']);

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

// --- Handle Wallet Payment ---
if ($payment_method === 'wallet') {
    $walletModel = new Wallet();
    $userWallet = $walletModel->getOrCreateWallet('user', $user->id);

    if ($userWallet->balance < $package->price) {
        header('Location: memberships.php?error=insufficient_funds');
        exit();
    }

    // Ensure Board/System wallet exists for commission
    $walletModel->getOrCreateWallet('board', 0);
    $walletModel->getOrCreateWallet('site', 0);

    // Process Payment via Wallet
    // distributePaymentWithCommission handles deduction from user wallet and distribution to club/site/board
    if ($walletModel->distributePaymentWithCommission(
        $package->price,
        'membership',
        'club',
        $package->club_id,
        "Membership: " . $package->name,
        'MEM-' . uniqid(),
        $userWallet->id
    )) {
        // Create Membership Record
        $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') $expiry_date = date('Y-m-d', strtotime('+3 months'));
        elseif ($package->duration_type === 'yearly') $expiry_date = date('Y-m-d', strtotime('+1 year'));

        $membershipData = [
            'user_id' => $user->id,
            'club_id' => $package->club_id,
            'membership_type' => $package->name,
            'start_date' => date('Y-m-d'),
            'expiry_date' => $expiry_date
        ];
        $clubModel->createMembership($membershipData);

        header('Location: memberships.php?status=success');
    } else {
        header('Location: memberships.php?error=transaction_failed');
    }
    exit();
}

// --- Prepare Flutterwave Payment ---
$flutterwave_secret_key = $settings['flutterwave_secret_key'] ?? '';
if (empty($flutterwave_secret_key)) {
    header('Location: memberships.php?error=payment_config_error');
    exit();
}

$tx_ref = uniqid('mem_', true);
$currency = 'ZMW'; // Or fetch from settings

// Prepare data for Flutterwave
$request = [
    'tx_ref' => $tx_ref,
    'amount' => $package->price,
    'currency' => $currency,
    'payment_options' => 'card,mobilemoney',
    'redirect_url' => URL_ROOT . '/app/flutterwave_verify.php?payment_context=membership_purchase',
    'customer' => [
        'email' => $user->email,
        'phonenumber' => $user->phone_number ?? '',
        'name' => $user->first_name . ' ' . $user->last_name
    ],
    'meta' => [
        'package_id' => $package->id,
        'type' => 'membership_purchase',
        'club_id' => $package->club_id,
        'user_id' => $user->id
    ],
    'customizations' => [
        'title' => 'Club Membership',
        'description' => 'Purchase of ' . $package->name,
        'logo' => '' // Could fetch club logo here
    ]
];

// Call Flutterwave Standard API
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.flutterwave.com/v3/payments',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_SSL_VERIFYPEER => false, // Fix for XAMPP SSL issues
  CURLOPT_POSTFIELDS => json_encode($request),
  CURLOPT_HTTPHEADER => array(
    'Authorization: Bearer ' . $flutterwave_secret_key,
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);
curl_close($curl);

$res = json_decode($response);

if ($res && isset($res->status) && $res->status == 'success') {
    $link = $res->data->link;
    header('Location: ' . $link);
} else {
    header('Location: memberships.php?error=payment_init_failed');
}
exit();