<div class="row mb-4">
    <div class="col-12">
        <h2><i class="bi bi-building"></i> Gestión de Casas</h2>
        <p class="text-muted">Administración del registro de propietarios</p>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead class="table-dark">
                    <tr>
                        <th>Número</th>
                        <th>Estado</th>
                        <th>Consumo Only</th>
                        <th>Propietario</th>
                        <th>Email</th>
                        <th>Teléfono</th>
                        <th>Ver</th>
                        <?php if (Auth::isAdmin()): ?>
                            <th>Acciones</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($houses as $house): ?>
                        <tr>
                            <td><strong><?= $house['number'] ?></strong></td>
                            <td>
                                <span class="badge <?= $house['status'] == 'activa' ? 'bg-success' : 'bg-secondary' ?>">
                                    <?= $house['status'] == 'activa' ? 'Activa' : 'Deshabitada' ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($house['consumption_only']): ?>
                                    <span class="badge bg-warning" title="Solo consumo">Sí</span>
                                <?php else: ?>
                                    <span class="text-muted">No</span>
                                <?php endif; ?>
                            </td>
                            <td><?= htmlspecialchars($house['owner_name'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($house['owner_email'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($house['owner_phone'] ?? '-') ?></td>
                            <td>
                                <a href="/dashboard.php?page=house_view&id=<?= $house['id'] ?>" class="btn btn-sm btn-info">
                                    <i class="bi bi-eye"></i>
                                </a>
                            </td>
                            <?php if (Auth::isAdmin()): ?>
                                <td>
                                    <button class="btn btn-sm btn-primary" onclick="editHouse(<?= $house['id'] ?>)">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                </td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php if (Auth::isAdmin()): ?>
<div class="modal fade" id="houseModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Editar Casa</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="houseForm">
                <div class="modal-body">
                    <input type="hidden" id="houseId" name="id">
                    <div class="mb-3">
                        <label class="form-label">Estado</label>
                        <select class="form-select" name="status" required>
                            <option value="activa">Activa</option>
                            <option value="deshabitada">Deshabitada</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Solo Consumo</label>
                        <select class="form-select" name="consumption_only">
                            <option value="0">No</option>
                            <option value="1">Sí (Descuento $100)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Propietario</label>
                        <input type="text" class="form-control" name="owner_name">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" name="owner_email">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Teléfono</label>
                        <input type="text" class="form-control" name="owner_phone">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Guardar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
let housesData = <?= json_encode($houses) ?>;

function editHouse(id) {
    const house = housesData.find(h => h.id === id);
    if (house) {
        document.getElementById('houseId').value = house.id;
        document.querySelector('[name="status"]').value = house.status;
        document.querySelector('[name="consumption_only"]').value = house.consumption_only;
        document.querySelector('[name="owner_name"]').value = house.owner_name || '';
        document.querySelector('[name="owner_email"]').value = house.owner_email || '';
        document.querySelector('[name="owner_phone"]').value = house.owner_phone || '';
        new bootstrap.Modal(document.getElementById('houseModal')).show();
    }
}

document.getElementById('houseForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const data = Object.fromEntries(formData.entries());
    data.consumption_only = parseInt(data.consumption_only);
    
    data.consumption_only = parseInt(data.consumption_only);
    
    fetch('/dashboard.php?page=house_actions&action=save', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
    .then(r => r.json())
    .then(result => {
        if (result.success) {
            Swal.fire('Éxito', 'Casa actualizada', 'success').then(() => location.reload());
        } else {
            Swal.fire('Error', result.message, 'error');
        }
    });
});
</script>
<?php endif; ?>
