<?php
session_start();

// Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit();
}

// Define admin access constant for this page
define('ADMIN_ACCESS', true);

// Include database connection
require_once '../config/database.php';
$pdo = getDBConnection();

// Handle actions
$action = $_GET['action'] ?? 'list';
$message = '';
$error = '';

// Process form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_transaction'])) {
        $userId = intval($_POST['user_id']);
        $type = $_POST['type'];
        $amount = floatval($_POST['amount']);
        $description = $_POST['description'];
        $paymentMethod = $_POST['payment_method'];
        
        try {
            $pdo->beginTransaction();
            
            // 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();
            $currentBalance = floatval($balanceResult['balance']);
            
            // Calculate new balance
            $newBalance = $type === 'credit' ? $currentBalance + $amount : $currentBalance - $amount;
            
            // Insert transaction
            $insertStmt = $pdo->prepare("
                INSERT INTO wallet_transactions (
                    user_id, type, amount, description, payment_method, 
                    transaction_time, balance_after, created_at
                ) VALUES (?, ?, ?, ?, ?, NOW(), ?, NOW())
            ");
            
            $insertStmt->execute([
                $userId, $type, $amount, $description, $paymentMethod, $newBalance
            ]);
            
            $pdo->commit();
            $message = "Transaction added successfully! New balance: ₹" . number_format($newBalance, 2);
            
} catch (Exception $e) {
            $pdo->rollBack();
            $error = "Error: " . $e->getMessage();
        }
    }
}

// Get users for dropdown
$usersStmt = $pdo->query("SELECT id, name, mobile FROM users ORDER BY name");
$users = $usersStmt->fetchAll();

// Get wallet transactions
$transactionsStmt = $pdo->query("
    SELECT 
        wt.*,
        u.name as user_name,
        u.mobile as user_mobile
    FROM wallet_transactions wt
    JOIN users u ON wt.user_id = u.id
    ORDER BY wt.created_at DESC
    LIMIT 100
");
$transactions = $transactionsStmt->fetchAll();

// Get wallet summary
$summaryStmt = $pdo->query("
    SELECT 
        COUNT(DISTINCT user_id) as total_users,
        SUM(CASE WHEN type = 'credit' THEN amount ELSE 0 END) as total_credits,
        SUM(CASE WHEN type = 'debit' THEN amount ELSE 0 END) as total_debits,
        SUM(CASE WHEN type = 'credit' THEN amount ELSE -amount END) as net_balance
    FROM wallet_transactions
");
$summary = $summaryStmt->fetch();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wallet Management - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .wallet-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .transaction-row:hover {
            background-color: #f8f9fa;
        }
        .balance-positive { color: #28a745; }
        .balance-negative { color: #dc3545; }
        .stats-card {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
        }
    </style>
</head>
<body class="bg-light">
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 d-md-block bg-dark sidebar collapse">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link text-white" href="index.php">
                                <i class="fas fa-home"></i> Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white active" href="wallet_management.php">
                                <i class="fas fa-wallet"></i> Wallet Management
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="user_management.php">
                                <i class="fas fa-users"></i> User Management
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="appointment_management.php">
                                <i class="fas fa-calendar"></i> Appointments
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="fas fa-wallet text-primary"></i> Wallet Management
                    </h1>
            </div>

                <!-- Messages -->
                <?php if ($message): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                <?php endif; ?>

                <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($error); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Wallet Summary Cards -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                        <div class="stats-card">
                            <h4><?php echo $summary['total_users']; ?></h4>
                            <p class="mb-0">Total Users</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                        <div class="stats-card">
                            <h4>₹<?php echo number_format($summary['total_credits'], 2); ?></h4>
                            <p class="mb-0">Total Credits</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                        <div class="stats-card">
                            <h4>₹<?php echo number_format($summary['total_debits'], 2); ?></h4>
                            <p class="mb-0">Total Debits</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                        <div class="stats-card">
                            <h4 class="<?php echo $summary['net_balance'] >= 0 ? 'balance-positive' : 'balance-negative'; ?>">
                                ₹<?php echo number_format($summary['net_balance'], 2); ?>
                            </h4>
                            <p class="mb-0">Net Balance</p>
                            </div>
                        </div>
                    </div>

                <!-- Add Transaction Form -->
                            <div class="card mb-4">
                                <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-plus-circle"></i> Add Transaction
                        </h5>
                                </div>
                                <div class="card-body">
                        <form method="POST">
                            <div class="row">
                                <div class="col-md-3">
                                    <label class="form-label">User</label>
                                    <select name="user_id" class="form-select" required>
                                        <option value="">Select User</option>
                                        <?php foreach ($users as $user): ?>
                                            <option value="<?php echo $user['id']; ?>">
                                                <?php echo htmlspecialchars($user['name'] . ' (' . $user['mobile'] . ')'); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Type</label>
                                    <select name="type" class="form-select" required>
                                        <option value="credit">Credit</option>
                                        <option value="debit">Debit</option>
                                    </select>
                            </div>
                                <div class="col-md-2">
                                    <label class="form-label">Amount (₹)</label>
                                    <input type="number" name="amount" class="form-control" step="0.01" min="0.01" required>
                        </div>
                                <div class="col-md-3">
                                    <label class="form-label">Description</label>
                                    <input type="text" name="description" class="form-control" required>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Payment Method</label>
                                    <select name="payment_method" class="form-select" required>
                                        <option value="Online Payment">Online Payment</option>
                                        <option value="Cash">Cash</option>
                                        <option value="Bank Transfer">Bank Transfer</option>
                                        <option value="System">System</option>
                                    </select>
                                </div>
                            </div>
                            <div class="mt-3">
                                <button type="submit" name="add_transaction" class="btn btn-primary">
                                    <i class="fas fa-plus"></i> Add Transaction
                                </button>
                            </div>
                        </form>
                        </div>
                    </div>

                <!-- Transactions Table -->
                    <div class="card">
                        <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-list"></i> Recent Transactions
                        </h5>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                    <thead class="table-dark">
                                        <tr>
                                        <th>ID</th>
                                        <th>User</th>
                                        <th>Type</th>
                                        <th>Amount</th>
                                        <th>Description</th>
                                        <th>Payment Method</th>
                                        <th>Balance After</th>
                                        <th>Date</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <?php foreach ($transactions as $transaction): ?>
                                        <tr class="transaction-row">
                                            <td><?php echo $transaction['id']; ?></td>
                                            <td>
                                                <strong><?php echo htmlspecialchars($transaction['user_name']); ?></strong><br>
                                                <small class="text-muted"><?php echo $transaction['user_mobile']; ?></small>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo $transaction['type'] === 'credit' ? 'success' : 'danger'; ?>">
                                                    <?php echo ucfirst($transaction['type']); ?>
                                                </span>
                                            </td>
                                            <td class="<?php echo $transaction['type'] === 'credit' ? 'balance-positive' : 'balance-negative'; ?>">
                                                <strong>₹<?php echo number_format($transaction['amount'], 2); ?></strong>
                                            </td>
                                            <td><?php echo htmlspecialchars($transaction['description']); ?></td>
                                            <td><?php echo htmlspecialchars($transaction['payment_method']); ?></td>
                                            <td class="balance-positive">
                                                <strong>₹<?php echo number_format($transaction['balance_after'], 2); ?></strong>
                                            </td>
                                            <td><?php echo date('d M Y H:i', strtotime($transaction['created_at'])); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                    </tbody>
                                </table>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto-hide alerts after 5 seconds
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(alert => {
                const bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            });
        }, 5000);
    </script>
</body>
</html> 