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

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

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

if (empty($unit_id)) {
    header('Location: list_units.php');
    exit();
}

// Get unit details
$sql = "SELECT u.*, p.property_name, p.property_code, p.location_area, ut.name as unit_type_name
        FROM units u
        LEFT JOIN properties p ON u.property_id = p.property_id
        LEFT JOIN unit_types ut ON u.unit_type_id = ut.type_id
        WHERE u.unit_id = ?";

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

if (!$unit) {
    header('Location: list_units.php');
    exit();
}

// Get current lease
$sql_lease = "SELECT l.*, t.first_name, t.last_name, t.email, t.phone
               FROM leases l
               JOIN lease_tenants lt ON l.lease_id = lt.lease_id AND lt.is_primary = 1
               JOIN tenants t ON lt.tenant_id = t.tenant_id
               WHERE l.unit_id = ? AND l.lease_status = 'ACTIVE'
               ORDER BY l.start_date DESC LIMIT 1";

$stmt_lease = $conn->prepare($sql_lease);
$stmt_lease->bind_param("i", $unit_id);
$stmt_lease->execute();
$result_lease = $stmt_lease->get_result();
$lease = $result_lease->fetch_assoc();

// Get maintenance requests
$sql_maintenance = "SELECT mr.*, t.first_name, t.last_name
                     FROM maintenance_requests mr
                     LEFT JOIN tenants t ON mr.tenant_id = t.tenant_id
                     WHERE mr.unit_id = ?
                     ORDER BY mr.created_at DESC LIMIT 10";

$stmt_maint = $conn->prepare($sql_maintenance);
$stmt_maint->bind_param("i", $unit_id);
$stmt_maint->execute();
$result_maint = $stmt_maint->get_result();
?>
<?php include 'layouts/main.php'; ?>

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

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="list_units.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i>Back to Units
                            </a>
                            <a href="add_unit.php?id=<?php echo $unit_id; ?>" class="btn btn-primary ms-2">
                                <i class="ri-edit-line me-1"></i>Edit Unit
                            </a>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Unit <?php echo htmlspecialchars($unit['unit_number']); ?></h4>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <p class="mb-2"><strong>Property:</strong> 
                                                <a href="property_details.php?id=<?php echo $unit['property_id']; ?>">
                                                    <?php echo htmlspecialchars($unit['property_name']); ?>
                                                </a>
                                            </p>
                                            <p class="mb-2"><strong>Unit Type:</strong> <?php echo htmlspecialchars($unit['unit_type_name'] ?? 'N/A'); ?></p>
                                            <p class="mb-2"><strong>Floor Level:</strong> <?php echo $unit['floor_level'] ?? 'N/A'; ?></p>
                                            <p class="mb-2"><strong>Bedrooms:</strong> <?php echo $unit['bedrooms'] ?? 0; ?></p>
                                            <p class="mb-2"><strong>Bathrooms:</strong> <?php echo $unit['bathrooms'] ?? 0; ?></p>
                                        </div>
                                        <div class="col-md-6">
                                            <p class="mb-2"><strong>Rent Amount:</strong> KES <?php echo number_format($unit['rent_amount'] ?? 0, 2); ?></p>
                                            <p class="mb-2"><strong>Deposit Amount:</strong> KES <?php echo number_format($unit['deposit_amount'] ?? 0, 2); ?></p>
                                            <p class="mb-2"><strong>Status:</strong> 
                                                <span class="badge bg-soft-<?php echo strtolower($unit['status']) == 'occupied' ? 'success' : 'danger'; ?>">
                                                    <?php echo htmlspecialchars($unit['status']); ?>
                                                </span>
                                            </p>
                                            <p class="mb-2"><strong>Furnishing:</strong> <?php echo htmlspecialchars($unit['furnishing'] ?? 'N/A'); ?></p>
                                            <p class="mb-2"><strong>Parking:</strong> 
                                                <?php if ($unit['has_parking']): ?>
                                                    Yes (Slot: <?php echo htmlspecialchars($unit['parking_slot_no'] ?? 'N/A'); ?>)
                                                <?php else: ?>
                                                    No
                                                <?php endif; ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <?php if ($lease): ?>
                                <div class="card mt-3">
                                    <div class="card-header">
                                        <h4 class="card-title mb-0">Current Lease</h4>
                                    </div>
                                    <div class="card-body">
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <p class="mb-2"><strong>Lease Code:</strong> <?php echo htmlspecialchars($lease['lease_code']); ?></p>
                                                <p class="mb-2"><strong>Tenant:</strong> 
                                                    <?php echo htmlspecialchars($lease['first_name'] . ' ' . $lease['last_name']); ?>
                                                    <br><small class="text-muted"><?php echo htmlspecialchars($lease['email']); ?></small>
                                                </p>
                                            </div>
                                            <div class="col-md-6">
                                                <p class="mb-2"><strong>Period:</strong> 
                                                    <?php echo date('M d, Y', strtotime($lease['start_date'])); ?> to 
                                                    <?php echo date('M d, Y', strtotime($lease['end_date'])); ?>
                                                </p>
                                                <p class="mb-2"><strong>Rent Amount:</strong> KES <?php echo number_format($lease['rent_amount'], 2); ?></p>
                                                <p class="mb-2"><strong>Status:</strong> 
                                                    <span class="badge bg-soft-success"><?php echo htmlspecialchars($lease['lease_status']); ?></span>
                                                </p>
                                            </div>
                                        </div>
                                        <a href="lease_details.php?id=<?php echo $lease['lease_id']; ?>" class="btn btn-primary btn-sm">
                                            <i class="ri-eye-line me-1"></i>View Lease Details
                                        </a>
                                    </div>
                                </div>
                            <?php else: ?>
                                <div class="card mt-3">
                                    <div class="card-body text-center py-4">
                                        <i class="ri-file-line fs-48 text-muted mb-3"></i>
                                        <h5>No Active Lease</h5>
                                        <p class="text-muted">This unit is currently vacant.</p>
                                        <a href="create_lease.php?unit_id=<?php echo $unit_id; ?>" class="btn btn-primary">
                                            <i class="ri-file-add-line me-1"></i>Create Lease
                                        </a>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <div class="card mt-3">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Recent Maintenance Requests</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Ticket #</th>
                                                    <th>Category</th>
                                                    <th>Status</th>
                                                    <th>Created</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_maint && $result_maint->num_rows > 0): ?>
                                                    <?php while($maint = $result_maint->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($maint['ticket_number'] ?? $maint['request_code']); ?></td>
                                                            <td><?php echo htmlspecialchars($maint['category']); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-primary"><?php echo htmlspecialchars($maint['status']); ?></span>
                                                            </td>
                                                            <td><?php echo date('M d, Y', strtotime($maint['created_at'])); ?></td>
                                                            <td>
                                                                <a href="maintenance_request_details.php?id=<?php echo $maint['request_id']; ?>" 
                                                                   class="btn btn-soft-secondary btn-sm">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="5" class="text-center py-4">
                                                            <div class="text-muted">No maintenance requests</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">Quick Actions</h4>
                                </div>
                                <div class="card-body">
                                    <?php if (!$lease): ?>
                                        <a href="create_lease.php?unit_id=<?php echo $unit_id; ?>" class="btn btn-primary w-100 mb-2">
                                            <i class="ri-file-add-line me-1"></i>Create Lease
                                        </a>
                                    <?php endif; ?>
                                    <a href="list_maintenance.php?unit_id=<?php echo $unit_id; ?>" class="btn btn-warning w-100 mb-2">
                                        <i class="ri-tools-line me-1"></i>View Maintenance
                                    </a>
                                    <a href="list_invoices.php?unit_id=<?php echo $unit_id; ?>" class="btn btn-info w-100">
                                        <i class="ri-receipt-line me-1"></i>View Invoices
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

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

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