<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Calculate wallet balance
$sql_balance = "SELECT 
                    COALESCE(SUM(rp.amount), 0) as total_collected,
                    COALESCE(SUM(e.amount), 0) as total_expenses,
                    (COALESCE(SUM(rp.amount), 0) - COALESCE(SUM(e.amount), 0)) as wallet_balance
                FROM properties p
                LEFT JOIN units u ON p.id = u.property_id
                LEFT JOIN leases l ON u.id = l.unit_id
                LEFT JOIN rent_payments rp ON l.id = rp.lease_id AND rp.payment_status = 'COMPLETED'
                LEFT JOIN expenses e ON p.id = e.property_id AND e.status = 'paid'
                WHERE p.owner_id = ?";

$stmt = $conn->prepare($sql_balance);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result_balance = $stmt->get_result();
$balance = $result_balance->fetch_assoc();

// Get withdrawal requests
$sql_withdrawals = "SELECT * FROM withdrawals 
                    WHERE landlord_id = ? 
                    ORDER BY created_at DESC 
                    LIMIT 10";

$stmt_w = $conn->prepare($sql_withdrawals);
$stmt_w->bind_param("i", $user_id);
$stmt_w->execute();
$result_withdrawals = $stmt_w->get_result();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Wallet')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Financials', 'title' => 'Wallet / Withdrawals')); ?>

                    <div class="row mb-3">
                        <div class="col-md-4">
                            <div class="card bg-soft-success">
                                <div class="card-body text-center">
                                    <h6 class="text-muted mb-2">Total Collected</h6>
                                    <h3 class="text-success mb-0">KES <?php echo number_format($balance['total_collected'], 2); ?></h3>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card bg-soft-danger">
                                <div class="card-body text-center">
                                    <h6 class="text-muted mb-2">Total Expenses</h6>
                                    <h3 class="text-danger mb-0">KES <?php echo number_format($balance['total_expenses'], 2); ?></h3>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card bg-soft-<?php echo $balance['wallet_balance'] >= 0 ? 'success' : 'danger'; ?>">
                                <div class="card-body text-center">
                                    <h6 class="text-muted mb-2">Available Balance</h6>
                                    <h3 class="text-<?php echo $balance['wallet_balance'] >= 0 ? 'success' : 'danger'; ?> mb-0">
                                        KES <?php echo number_format($balance['wallet_balance'], 2); ?>
                                    </h3>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Request Withdrawal</h4>
                                </div>
                                <div class="card-body">
                                    <form action="process_withdrawal_request.php" method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">Amount (KES)</label>
                                            <input type="number" class="form-control" name="amount" 
                                                   max="<?php echo $balance['wallet_balance']; ?>" 
                                                   step="0.01" required>
                                            <small class="text-muted">Available: KES <?php echo number_format($balance['wallet_balance'], 2); ?></small>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Bank Account</label>
                                            <input type="text" class="form-control" name="bank_account" 
                                                   placeholder="Account number" required>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Bank Name</label>
                                            <input type="text" class="form-control" name="bank_name" required>
                                        </div>
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="ri-money-dollar-circle-line me-1"></i>Request Withdrawal
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Recent Withdrawals</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Amount</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_withdrawals && $result_withdrawals->num_rows > 0): ?>
                                                    <?php while($withdrawal = $result_withdrawals->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($withdrawal['created_at'])); ?></td>
                                                            <td>KES <?php echo number_format($withdrawal['amount'], 2); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-<?php echo $withdrawal['status'] == 'completed' ? 'success' : 'warning'; ?>">
                                                                    <?php echo ucfirst($withdrawal['status']); ?>
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="3" class="text-center py-4">
                                                            <div class="text-muted">No withdrawals found</div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
