<?php
/**
 * Hostxolo - Payment Processing (Subscribe Page)
 * 
 * This file handles the subscription process and creates a pending subscription
 * before redirecting to the payment gateway
 */
require_once 'config.php';
require_login();

$user_id = $_SESSION['user_id'];
$plan_slug = $_GET['plan'] ?? '';
$billing = $_GET['billing'] ?? 'monthly';

// Get plan details
$plan = null;
if ($plan_slug) {
    try {
        $stmt = db()->prepare("SELECT * FROM subscription_plans WHERE slug = ? AND status = 1");
        $stmt->execute([$plan_slug]);
        $plan = $stmt->fetch();
    } catch (PDOException $e) {
        // Handle error
    }
}

if (!$plan) {
    redirect(BASE_URL . 'plans.php', 'error', 'Plan not found.');
}

// Check for existing active subscription to the same plan
$existing_subscription = null;
try {
    $stmt = db()->prepare("
        SELECT * FROM user_subscriptions 
        WHERE user_id = ? AND plan_id = ? AND status = 'active' 
        AND end_date >= CURDATE()
        ORDER BY end_date DESC LIMIT 1
    ");
    $stmt->execute([$user_id, $plan['id']]);
    $existing_subscription = $stmt->fetch();
} catch (PDOException $e) {
    // Continue
}

// If user has active subscription to this plan, redirect to renew instead
if ($existing_subscription) {
    redirect(BASE_URL . 'user/subscriptions.php', 'info', 'You already have an active subscription to this plan. You can renew it from your subscriptions page or choose a different plan.');
}

$amount = ($billing === 'yearly') ? $plan['yearly_price'] : $plan['monthly_price'];

$errors = [];
$success = '';

// Process subscription
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token.';
    } else {
        $billing_cycle = $_POST['billing'] ?? 'monthly';
        $amount = ($billing_cycle === 'yearly') ? $plan['yearly_price'] : $plan['monthly_price'];
        
        // Calculate dates
        $start_date = date('Y-m-d');
        $end_date = ($billing_cycle === 'yearly') 
            ? date('Y-m-d', strtotime('+1 year')) 
            : date('Y-m-d', strtotime('+1 month'));
        
        try {
            // Create subscription
            $stmt = db()->prepare("INSERT INTO user_subscriptions 
                (user_id, plan_id, subscription_type, amount, start_date, end_date, status, payment_status, created_at)
                VALUES (?, ?, ?, ?, ?, ?, 'pending', 'unpaid', NOW())");
            $stmt->execute([
                $user_id, 
                $plan['id'], 
                $billing_cycle, 
                $amount, 
                $start_date, 
                $end_date
            ]);
            
            $subscription_id = db()->lastInsertId();
            
            // Create transaction
            $transaction_number = 'TXN' . date('Ymd') . strtoupper(substr(uniqid(), -6));
            $stmt = db()->prepare("INSERT INTO transactions 
                (user_id, transaction_number, transaction_type, item_id, item_type, amount, total_amount, currency, status, created_at)
                VALUES (?, ?, 'subscription', ?, 'subscription_plan', ?, ?, 'INR', 'pending', NOW())");
            $stmt->execute([
                $user_id,
                $transaction_number,
                $subscription_id,
                $amount,
                $amount
            ]);
            
            $transaction_id = db()->lastInsertId();
            
            // Log activity
            log_activity('subscription_initiated', 'User initiated subscription to ' . $plan['name'], $user_id, 'user');
            
            // Redirect to checkout page
            redirect(BASE_URL . 'checkout.php?subscription=' . $subscription_id . '&txn=' . $transaction_number);
            
        } catch (PDOException $e) {
            $errors[] = 'Failed to create subscription. Please try again.';
            error_log("Subscription error: " . $e->getMessage());
        }
    }
}

$csrf_token = generate_csrf_token();

include 'includes/header.php';
?>

<section class="py-5" style="margin-top: 70px;">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="card shadow-lg border-0">
                    <div class="card-header bg-primary text-white py-4">
                        <h4 class="mb-0 fw-bold"><i class="bi bi-credit-card me-2"></i>Complete Your Subscription</h4>
                    </div>
                    <div class="card-body p-4 p-md-5">
                        <?php if (!empty($errors)): ?>
                            <div class="alert alert-danger">
                                <?php foreach ($errors as $error): ?>
                                    <p class="mb-0"><?php echo $error; ?></p>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                        
                        <div class="row g-4">
                            <!-- Plan Details -->
                            <div class="col-md-6">
                                <div class="card bg-light border-0 h-100">
                                    <div class="card-body">
                                        <h5 class="fw-bold mb-3">Plan Summary</h5>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>Plan:</span>
                                            <span class="fw-bold"><?php echo $plan['name']; ?></span>
                                        </div>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>Billing:</span>
                                            <span class="fw-bold"><?php echo ucfirst($billing); ?></span>
                                        </div>
                                        <hr>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <span class="h5 mb-0">Total:</span>
                                            <span class="h3 mb-0 text-primary"><?php echo format_currency($amount); ?></span>
                                        </div>
                                        
                                        <?php if ($billing === 'yearly'): ?>
                                            <p class="text-success small mt-2 mb-0">
                                                <i class="bi bi-check-circle me-1"></i>You save 20% with yearly billing!
                                            </p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Subscription Form -->
                            <div class="col-md-6">
                                <form method="POST" action="">
                                    <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                                    <input type="hidden" name="billing" value="<?php echo $billing; ?>">
                                    
                                    <div class="mb-3">
                                        <label class="form-label fw-bold">Select Billing Cycle</label>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="billing" id="monthly" value="monthly" 
                                                   <?php echo $billing === 'monthly' ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="monthly">
                                                Monthly - <?php echo format_currency($plan['monthly_price']); ?>/month
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="billing" id="yearly" value="yearly"
                                                   <?php echo $billing === 'yearly' ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="yearly">
                                                Yearly - <?php echo format_currency($plan['yearly_price']); ?>/year
                                                <span class="badge bg-success ms-2">Save 20%</span>
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <div class="alert alert-info">
                                        <small>
                                            <i class="bi bi-info-circle me-1"></i>
                                            You will be redirected to our secure payment gateway to complete the transaction.
                                        </small>
                                    </div>
                                    
                                    <div class="d-grid gap-2">
                                        <button type="submit" class="btn btn-primary btn-lg">
                                            <i class="bi bi-lock me-2"></i>Proceed to Payment
                                        </button>
                                        <a href="<?php echo BASE_URL; ?>plans.php" class="btn btn-outline-secondary">
                                            Change Plan
                                        </a>
                                    </div>
                                </form>
                            </div>
                        </div>
                        
                        <hr class="my-4">
                        
                        <!-- Plan Features -->
                        <h6 class="fw-bold mb-3">What's Included:</h6>
                        <div class="row">
                            <?php 
                            $features = json_decode($plan['features'] ?? '[]', true);
                            foreach ($features as $feature): 
                            ?>
                                <div class="col-md-6 mb-2">
                                    <i class="bi bi-check-circle-fill text-success me-2"></i><?php echo $feature; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <div class="text-center mt-4">
                            <p class="text-muted small mb-0">
                                <i class="bi bi-shield-check me-1"></i>
                                7-Day Money Back Guarantee - Cancel Anytime
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

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