<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Extract authorization token
$token = getAuthToken();

// Validate token
$user = getUserFromToken($token);
if (!$user) {
    errorResponse('User not authenticated', 401);
}

// Validate required fields
if (!isset($input['order_id']) || !isset($input['payment_method'])) {
    errorResponse('Order ID and payment method are required', 400);
}

$orderId = $input['order_id'];
$paymentMethod = $input['payment_method'];
$details = $input['payment_details'] ?? [];

try {
    // 1. Verify Order
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? AND user_id = ?");
    $stmt->execute([$orderId, $user['id']]);
    $order = $stmt->fetch();

    if (!$order) {
        errorResponse('Order not found', 404);
    }

    if ($order['status'] === 'paid') {
        errorResponse('Order is already paid', 400);
    }

    // 2. Simulate Payment Processing (Success mostly)
    // In a real scenario, you'd call Stripe/Coinbase/PayPal API here.
    
    // Simulate a random failure for testing? (Maybe later)
    $paymentStatus = 'paid';
    $transactionId = 'tx_' . bin2hex(random_bytes(12));

    // 3. Update Order Status
    $stmt = $pdo->prepare("UPDATE orders SET status = ?, payment_status = ?, updated_at = datetime('now') WHERE id = ?");
    $stmt->execute([$paymentStatus, $paymentStatus, $orderId]);

    // 4. Update User Subscription Logic
    // Get the tier related to this order
    $stmt = $pdo->prepare("SELECT * FROM subscription_tiers WHERE id = ?");
    $stmt->execute([$order['subscription_tier_id']]);
    $tier = $stmt->fetch();

    if ($tier) {
        // Update user profile or separate subscription table
        // For simplicity, we might update a 'subscription_status' in users table or similar.
        // Let's assume we update the user's progress or profile to reflect the new plan.
        
        // Check if user has a profile, if not create one (though they should have one)
        
        // Update user_progress current_rank if applicable, or just generic subscription flag
        // Assuming 'user_profiles' or 'users' has a subscription column. 
        // Based on previous files, we didn't see a specific subscription column in users, 
        // but 'user_progress' has 'current_rank'. Let's update that.
        
        $rankMap = [
            'basic' => 'Basic',
            'pro' => 'Silver', 
            'enterprise' => 'Gold' 
        ];
        
        // Attempt to map tier name to rank, or just use the tier name
        $newRank = $tier['name']; // e.g. "Pro Plan"

        $stmt = $pdo->prepare("UPDATE user_progress SET current_rank = ? WHERE user_id = ?");
        $stmt->execute([$newRank, $user['id']]);
        
        // Also set a flag in user_profiles if needed, e.g., plan_id
        // $stmt = $pdo->prepare("UPDATE user_profiles SET plan_id = ? WHERE user_id = ?");
        // $stmt->execute([$tier['id'], $user['id']]);
    }

    // 5. Log Activity
    $stmt = $pdo->prepare("INSERT INTO mail_activity (id, user_id, email_type, recipient_email, status, details, created_at) VALUES (?, ?, ?, ?, ?, ?, datetime('now'))");
    $stmt->execute([
        generateUUID(),
        $user['id'],
        'system_notification',
        $user['email'],
        'sent',
        json_encode(['message' => "Order $orderId paid via $paymentMethod", 'amount' => $order['amount']])
    ]);

    jsonResponse([
        'message' => 'Payment successful',
        'transaction_id' => $transactionId,
        'order_id' => $orderId,
        'status' => 'paid'
    ], 200);

} catch (Exception $e) {
    errorResponse('Payment processing failed: ' . $e->getMessage(), 500);
}
?>
