<?= $this->extend('layouts/app') ?>

<?= $this->section('content') ?>
<?php
$isEdit = isset($client) && is_array($client);
$action = $isEdit ? site_url('clients/' . $client['id'] . '/update') : site_url('clients');
$old = static fn (string $k, $default = '') => old($k, $isEdit ? ($client[$k] ?? $default) : $default);
?>
<section class="card stack-md">
    <form method="post" action="<?= esc($action) ?>" class="stack-md">
        <?= csrf_field() ?>

        <div class="grid grid-2">
            <div>
                <label>Nombre del cliente *</label>
                <input type="text" name="nombre" required value="<?= esc($old('nombre')) ?>">
            </div>
            <div>
                <label>Contrato</label>
                <input type="text" name="contrato" value="<?= esc($old('contrato')) ?>">
            </div>
        </div>

        <div>
            <label>Dirección</label>
            <textarea name="direccion" rows="2"><?= esc($old('direccion')) ?></textarea>
        </div>

        <div class="grid grid-2">
            <div>
                <label>Contacto</label>
                <input type="text" name="contacto_nombre" value="<?= esc($old('contacto_nombre')) ?>">
            </div>
            <div>
                <label>Email del contacto</label>
                <input type="email" name="contacto_email" value="<?= esc($old('contacto_email')) ?>">
            </div>
        </div>

        <div class="grid grid-2">
            <div>
                <label>Teléfono</label>
                <input type="text" name="contacto_telefono" value="<?= esc($old('contacto_telefono')) ?>">
            </div>
            <div>
                <label>Notas internas</label>
                <textarea name="notas" rows="2"><?= esc($old('notas')) ?></textarea>
            </div>
        </div>

        <div class="actions-row">
            <a class="btn btn-secondary" href="<?= site_url('clients') ?>">Cancelar</a>
            <button class="btn btn-primary" type="submit"><?= $isEdit ? 'Actualizar' : 'Crear' ?></button>
            <?php if ($isEdit): ?>
                <form method="post" action="<?= site_url('clients/' . $client['id'] . '/delete') ?>" onsubmit="return confirm('¿Eliminar cliente?')" style="display:inline">
                    <?= csrf_field() ?>
                    <button type="submit" class="btn btn-danger">Eliminar</button>
                </form>
            <?php endif; ?>
        </div>
    </form>
</section>
<?= $this->endSection() ?>
