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

require_once '../config/database.php';
require_once '../config/auth.php';

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

// Check authentication
$auth = new Auth();
if (!$auth->isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

$method = $_SERVER['REQUEST_METHOD'];
$endpoint = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            handleGetRequest($endpoint);
            break;
        case 'POST':
            handlePostRequest($endpoint);
            break;
        case 'PUT':
            handlePutRequest($endpoint);
            break;
        default:
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
            break;
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Internal server error: ' . $e->getMessage()]);
}

function handleGetRequest($endpoint) {
    global $pdo;
    
    switch ($endpoint) {
        case 'get-balance':
            getWalletBalance();
            break;
        case 'get-transactions':
            getTransactionHistory();
            break;
        case 'get-stats':
            getWalletStats();
            break;
        case 'get-user-wallets':
            getAllUserWallets();
            break;
        default:
            http_response_code(404);
            echo json_encode(['error' => 'Endpoint not found']);
            break;
    }
}

function handlePostRequest($endpoint) {
    global $pdo;
    
    switch ($endpoint) {
        case 'recharge':
            rechargeWallet();
            break;
        case 'deduct':
            deductFromWallet();
            break;
        case 'transfer':
            transferBetweenWallets();
            break;
        case 'add-transaction':
            addTransaction();
            break;
        default:
            http_response_code(404);
            echo json_encode(['error' => 'Endpoint not found']);
            break;
    }
}

function handlePutRequest($endpoint) {
    global $pdo;
    
    if ($endpoint === 'update-wallet') {
        updateWallet();
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Endpoint not found']);
    }
}

// Get Wallet Balance Function
function getWalletBalance() {
    global $pdo;
    
    $userId = $_GET['user_id'] ?? $_SESSION['user_id'] ?? 0;
    
    if (!$userId) {
        http_response_code(400);
        echo json_encode(['error' => 'User ID is required']);
        return;
    }
    
    try {
        $stmt = $pdo->prepare("
            SELECT balance, created_at, updated_at
            FROM user_wallets
            WHERE user_id = ?
        ");
        $stmt->execute([$userId]);
        $wallet = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($wallet) {
            echo json_encode([
                'success' => true,
                'balance' => floatval($wallet['balance']),
                'created_at' => $wallet['created_at'],
                'updated_at' => $wallet['updated_at']
            ]);
        } else {
            // Create wallet if doesn't exist
            $createStmt = $pdo->prepare("
                INSERT INTO user_wallets (user_id, balance, created_at, updated_at)
                VALUES (?, 0.00, NOW(), NOW())
            ");
            $createStmt->execute([$userId]);
            
            echo json_encode([
                'success' => true,
                'balance' => 0.00,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error fetching wallet balance: ' . $e->getMessage()]);
    }
}

// Get Transaction History Function
function getTransactionHistory() {
    global $pdo;
    
    $userId = $_GET['user_id'] ?? $_SESSION['user_id'] ?? 0;
    $limit = $_GET['limit'] ?? 50;
    $offset = $_GET['offset'] ?? 0;
    
    if (!$userId) {
        http_response_code(400);
        echo json_encode(['error' => 'User ID is required']);
        return;
    }
    
    try {
        $stmt = $pdo->prepare("
            SELECT id, type, amount, description, payment_method, balance_after, created_at
            FROM wallet_transactions
            WHERE user_id = ?
            ORDER BY created_at DESC
            LIMIT ? OFFSET ?
        ");
        $stmt->execute([$userId, intval($limit), intval($offset)]);
        $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get total count
        $countStmt = $pdo->prepare("
            SELECT COUNT(*) as total
            FROM wallet_transactions
            WHERE user_id = ?
        ");
        $countStmt->execute([$userId]);
        $total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        echo json_encode([
            'success' => true,
            'transactions' => $transactions,
            'total' => intval($total),
            'limit' => intval($limit),
            'offset' => intval($offset)
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error fetching transactions: ' . $e->getMessage()]);
    }
}

// Recharge Wallet Function
function rechargeWallet() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $userId = $input['user_id'] ?? $_SESSION['user_id'] ?? 0;
    $amount = floatval($input['amount'] ?? 0);
    $paymentMethod = $input['payment_method'] ?? 'Online Payment';
    $transactionId = $input['transaction_id'] ?? '';
    
    if (!$userId || $amount <= 0) {
        http_response_code(400);
        echo json_encode(['error' => 'Valid user ID and amount are required']);
        return;
    }
    
    try {
        $pdo->beginTransaction();
        
        // Get current balance
        $stmt = $pdo->prepare("
            SELECT balance FROM user_wallets WHERE user_id = ?
        ");
        $stmt->execute([$userId]);
        $wallet = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $currentBalance = $wallet ? floatval($wallet['balance']) : 0.00;
        $newBalance = $currentBalance + $amount;
        
        // Update wallet balance
        if ($wallet) {
            $updateStmt = $pdo->prepare("
                UPDATE user_wallets 
                SET balance = ?, updated_at = NOW()
                WHERE user_id = ?
            ");
            $updateStmt->execute([$newBalance, $userId]);
        } else {
            $createStmt = $pdo->prepare("
                INSERT INTO user_wallets (user_id, balance, created_at, updated_at)
                VALUES (?, ?, NOW(), NOW())
            ");
            $createStmt->execute([$userId, $newBalance]);
        }
        
        // Add transaction record
        $transactionStmt = $pdo->prepare("
            INSERT INTO wallet_transactions (user_id, type, amount, description, payment_method, balance_after, transaction_id, created_at)
            VALUES (?, 'credit', ?, ?, ?, ?, ?, NOW())
        ");
        $transactionStmt->execute([
            $userId,
            $amount,
            'Wallet Recharge',
            $paymentMethod,
            $newBalance,
            $transactionId
        ]);
        
        $pdo->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Wallet recharged successfully',
            'new_balance' => $newBalance,
            'transaction_id' => $transactionId
        ]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode(['error' => 'Error recharging wallet: ' . $e->getMessage()]);
    }
}

// Deduct from Wallet Function
function deductFromWallet() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $userId = $input['user_id'] ?? $_SESSION['user_id'] ?? 0;
    $amount = floatval($input['amount'] ?? 0);
    $service = $input['service'] ?? 'Service Payment';
    
    if (!$userId || $amount <= 0) {
        http_response_code(400);
        echo json_encode(['error' => 'Valid user ID and amount are required']);
        return;
    }
    
    try {
        $pdo->beginTransaction();
        
        // Check current balance
        $stmt = $pdo->prepare("
            SELECT balance FROM user_wallets WHERE user_id = ?
        ");
        $stmt->execute([$userId]);
        $wallet = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$wallet) {
            http_response_code(400);
            echo json_encode(['error' => 'Wallet not found']);
            return;
        }
        
        $currentBalance = floatval($wallet['balance']);
        
        if ($currentBalance < $amount) {
            http_response_code(400);
            echo json_encode(['error' => 'Insufficient balance']);
            return;
        }
        
        $newBalance = $currentBalance - $amount;
        
        // Update wallet balance
        $updateStmt = $pdo->prepare("
            UPDATE user_wallets 
            SET balance = ?, updated_at = NOW()
            WHERE user_id = ?
        ");
        $updateStmt->execute([$newBalance, $userId]);
        
        // Add transaction record
        $transactionStmt = $pdo->prepare("
            INSERT INTO wallet_transactions (user_id, type, amount, description, balance_after, created_at)
            VALUES (?, 'debit', ?, ?, ?, NOW())
        ");
        $transactionStmt->execute([
            $userId,
            $amount,
            $service,
            $newBalance
        ]);
        
        $pdo->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Payment successful',
            'new_balance' => $newBalance
        ]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode(['error' => 'Error deducting from wallet: ' . $e->getMessage()]);
    }
}

// Transfer Between Wallets Function
function transferBetweenWallets() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $fromUserId = $input['from_user_id'] ?? 0;
    $toUserId = $input['to_user_id'] ?? 0;
    $amount = floatval($input['amount'] ?? 0);
    $description = $input['description'] ?? 'Wallet Transfer';
    
    if (!$fromUserId || !$toUserId || $amount <= 0) {
        http_response_code(400);
        echo json_encode(['error' => 'Valid user IDs and amount are required']);
        return;
    }
    
    if ($fromUserId === $toUserId) {
        http_response_code(400);
        echo json_encode(['error' => 'Cannot transfer to same wallet']);
        return;
    }
    
    try {
        $pdo->beginTransaction();
        
        // Check sender balance
        $stmt = $pdo->prepare("
            SELECT balance FROM user_wallets WHERE user_id = ?
        ");
        $stmt->execute([$fromUserId]);
        $fromWallet = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$fromWallet || floatval($fromWallet['balance']) < $amount) {
            http_response_code(400);
            echo json_encode(['error' => 'Insufficient balance for transfer']);
            return;
        }
        
        // Deduct from sender
        $fromBalance = floatval($fromWallet['balance']) - $amount;
        $updateFromStmt = $pdo->prepare("
            UPDATE user_wallets 
            SET balance = ?, updated_at = NOW()
            WHERE user_id = ?
        ");
        $updateFromStmt->execute([$fromBalance, $fromUserId]);
        
        // Add to receiver
        $stmt->execute([$toUserId]);
        $toWallet = $stmt->fetch(PDO::FETCH_ASSOC);
        $toBalance = ($toWallet ? floatval($toWallet['balance']) : 0.00) + $amount;
        
        if ($toWallet) {
            $updateToStmt = $pdo->prepare("
                UPDATE user_wallets 
                SET balance = ?, updated_at = NOW()
                WHERE user_id = ?
            ");
            $updateToStmt->execute([$toBalance, $toUserId]);
        } else {
            $createStmt = $pdo->prepare("
                INSERT INTO user_wallets (user_id, balance, created_at, updated_at)
                VALUES (?, ?, NOW(), NOW())
            ");
            $createStmt->execute([$toUserId, $toBalance]);
        }
        
        // Record transactions
        $transactionStmt = $pdo->prepare("
            INSERT INTO wallet_transactions (user_id, type, amount, description, balance_after, created_at)
            VALUES (?, ?, ?, ?, ?, NOW())
        ");
        
        // Sender transaction
        $transactionStmt->execute([
            $fromUserId,
            'debit',
            $amount,
            "Transfer to User $toUserId: $description",
            $fromBalance
        ]);
        
        // Receiver transaction
        $transactionStmt->execute([
            $toUserId,
            'credit',
            $amount,
            "Transfer from User $fromUserId: $description",
            $toBalance
        ]);
        
        $pdo->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Transfer completed successfully',
            'from_balance' => $fromBalance,
            'to_balance' => $toBalance
        ]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode(['error' => 'Error processing transfer: ' . $e->getMessage()]);
    }
}

// Get Wallet Stats Function
function getWalletStats() {
    global $pdo;
    
    $userId = $_GET['user_id'] ?? $_SESSION['user_id'] ?? 0;
    
    if (!$userId) {
        http_response_code(400);
        echo json_encode(['error' => 'User ID is required']);
        return;
    }
    
    try {
        // Get total credit and debit
        $stmt = $pdo->prepare("
            SELECT 
                SUM(CASE WHEN type = 'credit' AND status = 'completed' THEN amount ELSE 0 END) as total_credit,
                SUM(CASE WHEN type = 'debit' AND status = 'completed' THEN amount ELSE 0 END) as total_debit,
                COUNT(*) as total_transactions
            FROM wallet_transactions
            WHERE user_id = ?
        ");
        $stmt->execute([$userId]);
        $stats = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Get current balance
        $balanceStmt = $pdo->prepare("
            SELECT balance FROM user_wallets WHERE user_id = ?
        ");
        $balanceStmt->execute([$userId]);
        $wallet = $balanceStmt->fetch(PDO::FETCH_ASSOC);
        $currentBalance = $wallet ? floatval($wallet['balance']) : 0.00;
        
        echo json_encode([
            'success' => true,
            'stats' => [
                'total_credit' => floatval($stats['total_credit'] ?? 0),
                'total_debit' => floatval($stats['total_debit'] ?? 0),
                'net_balance' => $currentBalance,
                'total_transactions' => intval($stats['total_transactions'] ?? 0)
            ]
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error fetching wallet stats: ' . $e->getMessage()]);
    }
}

// Get All User Wallets (Admin Function)
function getAllUserWallets() {
    global $pdo;
    
    // Check if user is admin
    if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
        http_response_code(403);
        echo json_encode(['error' => 'Admin access required']);
        return;
    }
    
    try {
        $stmt = $pdo->prepare("
            SELECT 
                w.user_id,
                w.balance,
                w.created_at,
                w.updated_at,
                u.username,
                u.email
            FROM user_wallets w
            JOIN users u ON w.user_id = u.id
            ORDER BY w.balance DESC
        ");
        $stmt->execute();
        $wallets = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'wallets' => $wallets,
            'total_users' => count($wallets)
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error fetching user wallets: ' . $e->getMessage()]);
    }
}

// Update Wallet Function
function updateWallet() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $userId = $input['user_id'] ?? 0;
    $balance = floatval($input['balance'] ?? 0);
    
    if (!$userId || $balance < 0) {
        http_response_code(400);
        echo json_encode(['error' => 'Valid user ID and balance are required']);
        return;
    }
    
    // Check if user is admin
    if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
        http_response_code(403);
        echo json_encode(['error' => 'Admin access required']);
        return;
    }
    
    try {
        $stmt = $pdo->prepare("
            UPDATE user_wallets 
            SET balance = ?, updated_at = NOW()
            WHERE user_id = ?
        ");
        $stmt->execute([$balance, $userId]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode([
                'success' => true,
                'message' => 'Wallet updated successfully',
                'new_balance' => $balance
            ]);
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Wallet not found']);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error updating wallet: ' . $e->getMessage()]);
    }
}

// Add Transaction Function
function addTransaction() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $userId = $input['user_id'] ?? 0;
    $type = $input['type'] ?? '';
    $amount = floatval($input['amount'] ?? 0);
    $description = $input['description'] ?? '';
    $paymentMethod = $input['payment_method'] ?? '';
    
    if (!$userId || !in_array($type, ['credit', 'debit']) || $amount <= 0) {
        http_response_code(400);
        echo json_encode(['error' => 'Valid user ID, type, and amount are required']);
        return;
    }
    
    try {
        $pdo->beginTransaction();
        
        // Get current balance
        $stmt = $pdo->prepare("
            SELECT balance FROM user_wallets WHERE user_id = ?
        ");
        $stmt->execute([$userId]);
        $wallet = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$wallet) {
            http_response_code(400);
            echo json_encode(['error' => 'Wallet not found']);
            return;
        }
        
        $currentBalance = floatval($wallet['balance']);
        $newBalance = $type === 'credit' ? $currentBalance + $amount : $currentBalance - $amount;
        
        if ($newBalance < 0) {
            http_response_code(400);
            echo json_encode(['error' => 'Insufficient balance for debit transaction']);
            return;
        }
        
        // Update wallet balance
        $updateStmt = $pdo->prepare("
            UPDATE user_wallets 
            SET balance = ?, updated_at = NOW()
            WHERE user_id = ?
        ");
        $updateStmt->execute([$newBalance, $userId]);
        
        // Add transaction record
        $transactionStmt = $pdo->prepare("
            INSERT INTO wallet_transactions (user_id, type, amount, description, payment_method, balance_after, created_at)
            VALUES (?, ?, ?, ?, ?, ?, NOW())
        ");
        $transactionStmt->execute([
            $userId,
            $type,
            $amount,
            $description,
            $paymentMethod,
            $newBalance
        ]);
        
        $pdo->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Transaction added successfully',
            'new_balance' => $newBalance,
            'transaction_id' => $pdo->lastInsertId()
        ]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode(['error' => 'Error adding transaction: ' . $e->getMessage()]);
    }
}
?> 
