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

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

// Check if user is admin
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Super Admin') {
    header('Location: index.php');
    exit();
}

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

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

// Get landlord details
$sql_landlord = "SELECT * FROM users WHERE id = ?";
$stmt_landlord = $conn->prepare($sql_landlord);
$stmt_landlord->bind_param("i", $landlord_id);
$stmt_landlord->execute();
$result_landlord = $stmt_landlord->get_result();
$landlord = $result_landlord->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();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $amount = $_POST['amount'] ?? 0;
    $bank_account = $_POST['bank_account'] ?? '';
    $bank_name = $_POST['bank_name'] ?? '';
    $notes = $_POST['notes'] ?? '';
    
    if (empty($amount) || $amount <= 0) {
        $error_message = "Invalid amount";
    } elseif ($amount > $balance['wallet_balance']) {
        $error_message = "Amount exceeds available balance";
    } elseif (empty($bank_account) || empty($bank_name)) {
        $error_message = "Bank details are required";
    } else {
        // Create withdrawal request
        $sql = "INSERT INTO withdrawals (landlord_id, amount, bank_account, bank_name, status, notes, created_at) 
                VALUES (?, ?, ?, ?, 'pending', ?, NOW())";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("idsss", $landlord_id, $amount, $bank_account, $bank_name, $notes);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Withdrawal request submitted successfully!";
            header('Location: landlord_wallets.php');
            exit();
        } else {
            $error_message = "Error: " . $conn->error;
        }
    }
}
?>
<?php include 'layouts/main.php'; ?>

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

                    <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>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Process Withdrawal for <?php echo htmlspecialchars($landlord['first_name'] . ' ' . $landlord['last_name']); ?></h4>
                                </div>
                                <div class="card-body">
                                    <div class="alert alert-info mb-3">
                                        <strong>Available Balance:</strong> KES <?php echo number_format($balance['wallet_balance'], 2); ?>
                                    </div>

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

                                    <form method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">Amount (KES) <span class="text-danger">*</span></label>
                                            <input type="number" class="form-control" name="amount" 
                                                   max="<?php echo $balance['wallet_balance']; ?>" 
                                                   step="0.01" required>
                                            <small class="text-muted">Maximum: KES <?php echo number_format($balance['wallet_balance'], 2); ?></small>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Bank Name <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" name="bank_name" required>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Bank Account <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" name="bank_account" required>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Notes</label>
                                            <textarea class="form-control" name="notes" rows="3"></textarea>
                                        </div>
                                        <div class="mt-4">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-money-dollar-circle-line align-bottom me-1"></i>Process Withdrawal
                                            </button>
                                            <a href="landlord_wallets.php" class="btn btn-light ms-2">
                                                <i class="ri-close-line align-bottom me-1"></i>Cancel
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

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

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