<?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();
$amount = (float)($input['amount'] ?? 0);
$paymentMethod = $input['payment_method'] ?? 'demo';
$description = $input['description'] ?? 'Payment';
$invoiceId = (int)($input['invoice_id'] ?? 0);

if ($amount <= 0) hw_json(['success' => false, 'message' => 'Valid amount is required'], 422);

try {
    $pdo = hw_db();
    $pdo->beginTransaction();
    
    // Process payment based on method
    $transactionId = 'txn_' . uniqid();
    $status = 'completed'; // Demo always succeeds
    
    switch ($paymentMethod) {
        case 'card':
            // In real implementation: integrate with Stripe, Square, etc.
            $transactionId = 'stripe_' . uniqid();
            break;
        case 'paypal':
            // In real implementation: integrate with PayPal API
            $transactionId = 'paypal_' . uniqid();
            break;
        case 'crypto':
            // In real implementation: integrate with crypto payment processor
            $transactionId = 'crypto_' . uniqid();
            break;
        default:
            $transactionId = 'demo_' . uniqid();
    }
    
    // Create payment record
    $stmt = $pdo->prepare("
        INSERT INTO payments (user_id, amount, status, payment_method, transaction_id) 
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        (int)$user['sub'],
        $amount,
        $status,
        $paymentMethod,
        $transactionId
    ]);
    $paymentId = (int)$pdo->lastInsertId();
    
    // Update invoice if provided
    if ($invoiceId > 0) {
        $stmt = $pdo->prepare("
            UPDATE invoices SET status = 'paid', paid_at = NOW() 
            WHERE id = ? AND user_id = ?
        ");
        $stmt->execute([$invoiceId, (int)$user['sub']]);
    }
    
    // Calculate platform revenue (10% platform fee)
    $platformFee = $amount * 0.10;
    $netAmount = $amount - $platformFee;
    
    $stmt = $pdo->prepare("
        INSERT INTO revenue_records (payment_id, revenue_type, gross_amount, platform_fee, net_amount) 
        VALUES (?, 'product', ?, ?, ?)
    ");
    $stmt->execute([$paymentId, $amount, $platformFee, $netAmount]);
    
    // Audit log
    $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("payment_id", ?, "amount", ?, "method", ?))')
        ->execute([(int)$user['sub'], 'payment_processed', $paymentId, $amount, $paymentMethod]);
    
    $pdo->commit();
    
    hw_json([
        'success' => true,
        'payment_id' => $paymentId,
        'transaction_id' => $transactionId,
        'amount' => $amount,
        'status' => $status
    ]);
} catch (Throwable $e) {
    $pdo->rollBack();
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}