<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'message' => 'Method not allowed. Use POST.',
        'new_balance' => 0.0
    ]);
    exit();
}

// Include database configuration
require_once '../config/database.php';

try {
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Invalid JSON input',
            'new_balance' => 0.0
        ]);
        exit();
    }
    
    // Validate required fields
    $userId = isset($input['user_id']) ? intval($input['user_id']) : null;
    $amount = isset($input['amount']) ? floatval($input['amount']) : null;
    $paymentMethod = isset($input['payment_method']) ? $input['payment_method'] : null;
    $transactionTime = isset($input['timestamp']) ? $input['timestamp'] : date('Y-m-d H:i:s');
    
    if (!$userId || !$amount || !$paymentMethod) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Missing required fields: user_id, amount, payment_method',
            'new_balance' => 0.0
        ]);
        exit();
    }
    
    if ($amount <= 0) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Amount must be greater than 0',
            'new_balance' => 0.0
        ]);
        exit();
    }
    
    // Start transaction
    $pdo->beginTransaction();
    
    try {
        // Get current balance
        $balanceStmt = $pdo->prepare("
            SELECT COALESCE(SUM(
                CASE 
                    WHEN type = 'credit' THEN amount 
                    WHEN type = 'debit' THEN -amount 
                    ELSE 0 
                END
            ), 0) as balance
            FROM wallet_transactions 
            WHERE user_id = ?
        ");
        
        $balanceStmt->execute([$userId]);
        $balanceResult = $balanceStmt->fetch(PDO::FETCH_ASSOC);
        $currentBalance = floatval($balanceResult['balance']);
        
        // Calculate new balance
        $newBalance = $currentBalance + $amount;
        
        // Insert recharge transaction
        $insertStmt = $pdo->prepare("
            INSERT INTO wallet_transactions (
                user_id, type, amount, description, payment_method, 
                transaction_time, balance_after, created_at
            ) VALUES (?, 'credit', ?, ?, ?, ?, ?, NOW())
        ");
        
        $insertStmt->execute([
            $userId,
            $amount,
            'Wallet Recharge',
            $paymentMethod,
            $transactionTime,
            $newBalance
        ]);
        
        $transactionId = $pdo->lastInsertId();
        
        // Commit transaction
        $pdo->commit();
        
        // Return success response
        echo json_encode([
            'success' => true,
            'message' => 'Wallet recharged successfully',
            'transaction_id' => $transactionId,
            'amount' => $amount,
            'previous_balance' => $currentBalance,
            'new_balance' => $newBalance,
            'user_id' => $userId
        ]);
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $pdo->rollBack();
        throw $e;
    }
    
} catch (PDOException $e) {
    // Database error
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage(),
        'new_balance' => 0.0
    ]);
} catch (Exception $e) {
    // General error
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Server error: ' . $e->getMessage(),
        'new_balance' => 0.0
    ]);
}
?> 