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

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

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

if (empty($property_id)) {
    header('Location: list_properties.php');
    exit();
}

// Get property details
$sql = "SELECT p.*, pt.type_name, u.first_name as owner_first, u.last_name as owner_last, u.email as owner_email
        FROM properties p
        LEFT JOIN property_types pt ON p.type_id = pt.type_id
        LEFT JOIN users u ON p.owner_id = u.id
        WHERE p.property_id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $property_id);
$stmt->execute();
$result = $stmt->get_result();
$property = $result->fetch_assoc();

if (!$property) {
    header('Location: list_properties.php');
    exit();
}

// Get units for this property
$sql_units = "SELECT u.*, ut.name as unit_type_name,
              COUNT(DISTINCT l.lease_id) as lease_count,
              COUNT(DISTINCT CASE WHEN l.lease_status = 'ACTIVE' THEN l.lease_id END) as active_leases
              FROM units u
              LEFT JOIN unit_types ut ON u.unit_type_id = ut.type_id
              LEFT JOIN leases l ON u.unit_id = l.unit_id
              WHERE u.property_id = ?
              GROUP BY u.unit_id
              ORDER BY u.unit_number ASC";

$stmt_units = $conn->prepare($sql_units);
$stmt_units->bind_param("i", $property_id);
$stmt_units->execute();
$result_units = $stmt_units->get_result();

// Get financial summary
$sql_financial = "SELECT 
                    COUNT(DISTINCT i.invoice_id) as total_invoices,
                    SUM(CASE WHEN i.status = 'paid' THEN i.total_amount ELSE 0 END) as total_collected,
                    SUM(CASE WHEN i.status IN ('unpaid', 'overdue') THEN i.balance ELSE 0 END) as outstanding
                  FROM invoices i
                  JOIN leases l ON i.lease_id = l.lease_id
                  JOIN units u ON l.unit_id = u.unit_id
                  WHERE u.property_id = ?";

$stmt_financial = $conn->prepare($sql_financial);
$stmt_financial->bind_param("i", $property_id);
$stmt_financial->execute();
$result_financial = $stmt_financial->get_result();
$financial = $result_financial->fetch_assoc();
?>
<?php include 'layouts/main.php'; ?>

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

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="list_properties.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i>Back to Properties
                            </a>
                            <a href="add_property.php?id=<?php echo $property_id; ?>" class="btn btn-primary ms-2">
                                <i class="ri-edit-line me-1"></i>Edit Property
                            </a>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0"><?php echo htmlspecialchars($property['property_name']); ?></h4>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <p class="mb-2"><strong>Property Code:</strong> <?php echo htmlspecialchars($property['property_code'] ?? 'N/A'); ?></p>
                                            <p class="mb-2"><strong>Type:</strong> <?php echo htmlspecialchars($property['type_name'] ?? 'N/A'); ?></p>
                                            <p class="mb-2"><strong>Location:</strong> <?php echo htmlspecialchars($property['location_area'] ?? 'N/A'); ?></p>
                                            <p class="mb-2"><strong>Street Address:</strong> <?php echo htmlspecialchars($property['street_address'] ?? 'N/A'); ?></p>
                                        </div>
                                        <div class="col-md-6">
                                            <p class="mb-2"><strong>City:</strong> <?php echo htmlspecialchars($property['city'] ?? 'N/A'); ?></p>
                                            <p class="mb-2"><strong>Total Floors:</strong> <?php echo $property['total_floors'] ?? 'N/A'; ?></p>
                                            <p class="mb-2"><strong>Owner:</strong> 
                                                <?php if ($property['owner_first']): ?>
                                                    <?php echo htmlspecialchars($property['owner_first'] . ' ' . $property['owner_last']); ?>
                                                    <br><small class="text-muted"><?php echo htmlspecialchars($property['owner_email']); ?></small>
                                                <?php else: ?>
                                                    Not assigned
                                                <?php endif; ?>
                                            </p>
                                        </div>
                                    </div>
                                    <?php if ($property['description']): ?>
                                        <div class="mb-3">
                                            <strong>Description:</strong>
                                            <p class="text-muted"><?php echo nl2br(htmlspecialchars($property['description'])); ?></p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <div class="card mt-3">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Units (<?php echo $result_units->num_rows; ?>)</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Unit Number</th>
                                                    <th>Type</th>
                                                    <th>Bedrooms</th>
                                                    <th>Bathrooms</th>
                                                    <th>Rent Amount</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_units && $result_units->num_rows > 0): ?>
                                                    <?php while($unit = $result_units->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($unit['unit_number']); ?></td>
                                                            <td><?php echo htmlspecialchars($unit['unit_type_name'] ?? 'N/A'); ?></td>
                                                            <td><?php echo $unit['bedrooms'] ?? 0; ?></td>
                                                            <td><?php echo $unit['bathrooms'] ?? 0; ?></td>
                                                            <td>KES <?php echo number_format($unit['rent_amount'] ?? 0, 2); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-<?php echo strtolower($unit['status']) == 'occupied' ? 'success' : 'danger'; ?>">
                                                                    <?php echo htmlspecialchars($unit['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <a href="unit_details.php?id=<?php echo $unit['unit_id']; ?>" 
                                                                   class="btn btn-soft-secondary btn-sm">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="7" class="text-center py-4">
                                                            <div class="text-muted">No units 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">Financial Summary</h4>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <p class="mb-1 text-muted">Total Invoices</p>
                                        <h4 class="mb-0"><?php echo $financial['total_invoices'] ?? 0; ?></h4>
                                    </div>
                                    <div class="mb-3">
                                        <p class="mb-1 text-muted">Total Collected</p>
                                        <h4 class="mb-0 text-success">KES <?php echo number_format($financial['total_collected'] ?? 0, 2); ?></h4>
                                    </div>
                                    <div class="mb-3">
                                        <p class="mb-1 text-muted">Outstanding</p>
                                        <h4 class="mb-0 text-danger">KES <?php echo number_format($financial['outstanding'] ?? 0, 2); ?></h4>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

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

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