<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['POST']);
$user = hw_auth_user();
if (!$user) hw_json(['success' => false, 'message' => 'Unauthorized'], 401);

$input = hw_input_json();
$plan = $input['plan'] ?? null;
$paymentMethod = trim((string)($input['payment_method'] ?? 'demo'));
$amount = (float)($input['amount'] ?? 0);

// Validate inputs
if (!$plan || !in_array($plan, ['personal', 'family'])) {
    hw_json(['success' => false, 'message' => 'Invalid plan selected'], 400);
}

if (!in_array($paymentMethod, ['card', 'paypal', 'demo'])) {
    hw_json(['success' => false, 'message' => 'Invalid payment method'], 400);
}

if ($amount <= 0) {
    hw_json(['success' => false, 'message' => 'Invalid amount'], 400);
}

try {
    $pdo = hw_db();
    $pdo->beginTransaction();
    
    // Generate transaction ID based on payment method
    $transactionId = match($paymentMethod) {
        'card' => 'stripe_' . uniqid(),
        'paypal' => 'paypal_' . uniqid(),
        default => 'demo_' . uniqid()
    };
    
    $status = 'completed'; // Demo always succeeds
    
    // Create payment record
    $stmt = $pdo->prepare("
        INSERT INTO payments (user_id, amount, status, payment_method, transaction_id) 
        VALUES (?, ?, ?, ?, ?)
    ");
    
    if (!$stmt->execute([
        (int)$user['sub'],
        $amount,
        $status,
        $paymentMethod,
        $transactionId
    ])) {
        throw new Exception('Failed to create payment record');
    }
    
    $paymentId = (int)$pdo->lastInsertId();
    
    // Update user's subscription plan
    $updateStmt = $pdo->prepare("
        UPDATE users 
        SET subscription_plan = ?, plan_updated_at = NOW() 
        WHERE id = ?
    ");
    
    if (!$updateStmt->execute([$plan, (int)$user['sub']])) {
        throw new Exception('Failed to update subscription');
    }
    
    // Calculate platform revenue (10% platform fee)
    $platformFee = $amount * 0.10;
    $netAmount = $amount - $platformFee;
    
    if (!$pdo->prepare("
        INSERT INTO revenue_records (payment_id, revenue_type, gross_amount, platform_fee, net_amount) 
        VALUES (?, ?, ?, ?, ?)
    ")->execute([$paymentId, 'membership', $amount, $platformFee, $netAmount])) {
        throw new Exception('Failed to record revenue');
    }
    
    // Audit log
    $pdo->prepare('
        INSERT INTO audit_logs (user_id, action, meta) 
        VALUES (?, ?, JSON_OBJECT("plan", ?, "payment_id", ?, "amount", ?, "method", ?))
    ')->execute([
        (int)$user['sub'], 
        'subscription_upgraded', 
        $plan,
        $paymentId, 
        $amount, 
        $paymentMethod
    ]);
    
    $pdo->commit();
    
    hw_json([
        'success' => true,
        'plan' => $plan,
        'payment_id' => $paymentId,
        'transaction_id' => $transactionId,
        'amount' => $amount,
        'status' => $status,
        'message' => 'Subscription activated successfully'
    ]);
} catch (Throwable $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    error_log('Subscription error: ' . $e->getMessage());
    hw_json(['success' => false, 'message' => 'Payment processing failed: ' . $e->getMessage()], 500);
}