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

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

$landlord_id = $_GET['id'] ?? '';

if (empty($landlord_id)) {
    header('Location: landlord_wallets.php');
    exit();
}

// Get landlord details
$sql = "SELECT * FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $landlord_id);
$stmt->execute();
$result = $stmt->get_result();
$landlord = $result->fetch_assoc();

if (!$landlord) {
    header('Location: landlord_wallets.php');
    exit();
}

// 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_balance = $conn->prepare($sql_balance);
$stmt_balance->bind_param("i", $landlord_id);
$stmt_balance->execute();
$result_balance = $stmt_balance->get_result();
$balance = $result_balance->fetch_assoc();

// Get recent transactions
$sql_transactions = "SELECT 
                        'Revenue' as type,
                        rp.payment_date as date,
                        CONCAT('Rent - ', i.invoice_number) as description,
                        rp.amount as amount
                    FROM rent_payments rp
                    JOIN leases l ON rp.lease_id = l.lease_id
                    JOIN units u ON l.unit_id = u.unit_id
                    JOIN properties p ON u.property_id = p.id
                    LEFT JOIN invoices i ON rp.invoice_id = i.invoice_id
                    WHERE p.owner_id = ? AND rp.payment_status = 'COMPLETED'
                    
                    UNION ALL
                    
                    SELECT 
                        'Expense' as type,
                        e.incurred_date as date,
                        CONCAT(e.category, ' - ', e.description) as description,
                        e.amount as amount
                    FROM expenses e
                    JOIN properties p ON e.property_id = p.id
                    WHERE p.owner_id = ? AND e.status = 'paid'
                    
                    ORDER BY date DESC LIMIT 20";

$stmt_trans = $conn->prepare($sql_transactions);
$stmt_trans->bind_param("ii", $landlord_id, $landlord_id);
$stmt_trans->execute();
$result_trans = $stmt_trans->get_result();

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

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Wallet Details')); ?>
    <?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' => 'Accounting', 'title' => 'Wallet Details')); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="landlord_wallets.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i>Back to Wallets
                            </a>
                            <a href="process_withdrawal_request.php?landlord_id=<?php echo $landlord_id; ?>" class="btn btn-primary ms-2">
                                <i class="ri-money-dollar-circle-line me-1"></i>Process Withdrawal
                            </a>
                        </div>
                    </div>

                    <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-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Recent Transactions</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>Type</th>
                                                    <th>Description</th>
                                                    <th class="text-end">Amount</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_trans && $result_trans->num_rows > 0): ?>
                                                    <?php while($transaction = $result_trans->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($transaction['date'])); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-<?php echo $transaction['type'] == 'Revenue' ? 'success' : 'danger'; ?>">
                                                                    <?php echo htmlspecialchars($transaction['type']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($transaction['description']); ?></td>
                                                            <td class="text-end">
                                                                <span class="fw-semibold <?php echo $transaction['type'] == 'Revenue' ? 'text-success' : 'text-danger'; ?>">
                                                                    <?php echo $transaction['type'] == 'Revenue' ? '+' : '-'; ?>KES <?php echo number_format($transaction['amount'], 2); ?>
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="4" class="text-center py-4">
                                                            <div class="text-muted">No transactions found</div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Withdrawal Requests</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</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>
