<?php
require_once __DIR__ . '/../../src/db.php';
require_once __DIR__ . '/../../src/Auth/AuthManager.php';
require_once __DIR__ . '/../../src/MultiTenant/TenantManager.php';
require_once __DIR__ . '/../../src/Billing/PaymentManager.php';

header('Content-Type: application/json');

// Require authentication
if (!AuthManager::isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

// Require admin role
if (!AuthManager::hasRole('super_admin')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Admin access required']);
    exit;
}

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// Get request data
$data = json_decode(file_get_contents('php://input'), true);
$planId = (int) ($data['plan_id'] ?? 0);
$billingCycle = $data['billing_cycle'] ?? 'monthly';

if (!$planId) {
    echo json_encode(['success' => false, 'error' => 'Plan ID required']);
    exit;
}

try {
    // Initialize payment manager
    PaymentManager::initialize();
    
    // Get current company
    $company = TenantManager::getCurrentCompany();
    $user = AuthManager::getCurrentUser();
    
    // Create Razorpay payment link
    $paymentLink = PaymentManager::createRazorpayPaymentLink(
        $planId,
        $billingCycle,
        $company['id'],
        $user['email']
    );
    
    echo json_encode([
        'success' => true,
        'payment_link_id' => $paymentLink['id'],
        'url' => $paymentLink['short_url'],
        'amount' => $paymentLink['amount'],
        'customer_id' => $paymentLink['customer_id']
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
