<?php
require_once '../connection.php';

if (!isLoggedIn() || isAdmin()) {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['plan_id'])) {
    $client_id = $_SESSION['user_id'];
    $plan_id = $_POST['plan_id'];
    
    // Get plan details
    $stmt = $pdo->prepare("SELECT * FROM plans WHERE id = ? AND is_active = 1");
    $stmt->execute([$plan_id]);
    $plan = $stmt->fetch();
    
    if (!$plan) {
        $_SESSION['error'] = "Invalid plan selected";
        header('Location: dashboard.php');
        exit();
    }
    
    // Get client wallet balance
    $stmt = $pdo->prepare("SELECT wallet_balance FROM clients WHERE id = ?");
    $stmt->execute([$client_id]);
    $client = $stmt->fetch();
    
    if ($client['wallet_balance'] < $plan['price']) {
        $_SESSION['error'] = "Insufficient wallet balance. Please add funds to your wallet.";
        header('Location: dashboard.php');
        exit();
    }
    
    // Process renewal
    require_once '../functions.php';
    if (renewSubscription($client_id, $plan_id, 'wallet')) {
        $_SESSION['success'] = "Plan purchased successfully! Your new subscription is active.";
    } else {
        $_SESSION['error'] = "Failed to purchase plan. Please try again.";
    }
    
    header('Location: dashboard.php');
    exit();
} else {
    header('Location: dashboard.php');
    exit();
}
?>