<?php
use App\Core\Csrf;

$old = $_SESSION['old'] ?? [];
$errors = $_SESSION['form_errors'] ?? [];
unset($_SESSION['old'], $_SESSION['form_errors']);

function form_value(string $key, $family, array $old, string $default = ''): string {
    return htmlspecialchars((string)($old[$key] ?? ($family[$key] ?? $default)));
}
function resp_value(string $key, $responsible, array $old, string $postKey, string $default = ''): string {
    return htmlspecialchars((string)($old[$postKey] ?? ($responsible[$key] ?? $default)));
}
?>
<section class="page-heading">
    <div>
        <span class="section-kicker">Dossier famille</span>
        <h2><?= htmlspecialchars($pageTitle) ?></h2>
        <p>Les informations pourront être complétées progressivement.</p>
    </div>
    <a class="secondary-button button-link" href="/public/familles">Retour à la liste</a>
</section>

<?php if ($errors): ?>
<div class="alert alert-error">
    <strong>Le formulaire contient des erreurs :</strong>
    <ul><?php foreach ($errors as $error): ?><li><?= htmlspecialchars($error) ?></li><?php endforeach; ?></ul>
</div>
<?php endif; ?>

<form method="post" action="<?= htmlspecialchars($formAction) ?>" class="family-form">
    <?= Csrf::field() ?>

    <section class="panel form-section">
        <div class="form-section-header">
            <div class="step-number">1</div>
            <div>
                <h3>Informations générales</h3>
                <p>Identité administrative et coordonnées principales de la famille.</p>
            </div>
        </div>

        <div class="form-grid form-grid-3">
            <label class="field field-span-2">
                <span>Nom de la famille *</span>
                <input type="text" name="nom_famille" required
                       value="<?= form_value('nom_famille', $family, $old) ?>"
                       placeholder="Ex. DUPONT">
            </label>

            <label class="field">
                <span>Situation familiale</span>
                <select name="situation_familiale">
                    <?php
                    $selectedSituation = $old['situation_familiale'] ?? ($family['situation_familiale'] ?? '');
                    foreach (['' => 'Non renseignée', 'Couple' => 'Couple', 'Famille monoparentale' => 'Famille monoparentale', 'Garde alternée' => 'Garde alternée', 'Autre' => 'Autre'] as $v => $label):
                    ?>
                    <option value="<?= htmlspecialchars($v) ?>" <?= $selectedSituation === $v ? 'selected' : '' ?>>
                        <?= htmlspecialchars($label) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </label>

            <label class="field field-span-2">
                <span>Adresse</span>
                <input type="text" name="adresse_ligne1"
                       value="<?= form_value('adresse_ligne1', $family, $old) ?>"
                       placeholder="Numéro et nom de voie">
            </label>

            <label class="field">
                <span>Complément</span>
                <input type="text" name="adresse_ligne2"
                       value="<?= form_value('adresse_ligne2', $family, $old) ?>">
            </label>

            <label class="field">
                <span>Code postal</span>
                <input type="text" name="code_postal"
                       value="<?= form_value('code_postal', $family, $old, '59123') ?>">
            </label>

            <label class="field">
                <span>Ville</span>
                <input type="text" name="ville"
                       value="<?= form_value('ville', $family, $old, 'BRAY-DUNES') ?>">
            </label>

            <label class="field">
                <span>Pays</span>
                <input type="text" name="pays"
                       value="<?= form_value('pays', $family, $old, 'France') ?>">
            </label>
        </div>
    </section>

    <section class="panel form-section">
        <div class="form-section-header">
            <div class="step-number">2</div>
            <div>
                <h3>Coordonnées et facturation</h3>
                <p>Ces informations seront utilisées pour les contacts et les documents.</p>
            </div>
        </div>

        <div class="form-grid form-grid-2">
            <label class="field">
                <span>Téléphone principal</span>
                <input type="tel" name="telephone_principal"
                       value="<?= form_value('telephone_principal', $family, $old) ?>">
            </label>
            <label class="field">
                <span>Téléphone secondaire</span>
                <input type="tel" name="telephone_secondaire"
                       value="<?= form_value('telephone_secondaire', $family, $old) ?>">
            </label>
            <label class="field">
                <span>E-mail principal</span>
                <input type="email" name="email_principal"
                       value="<?= form_value('email_principal', $family, $old) ?>">
            </label>
            <label class="field">
                <span>E-mail secondaire</span>
                <input type="email" name="email_secondaire"
                       value="<?= form_value('email_secondaire', $family, $old) ?>">
            </label>
            <label class="field">
                <span>Quotient familial</span>
                <input type="number" step="0.01" min="0" name="quotient_familial"
                       value="<?= form_value('quotient_familial', $family, $old) ?>">
            </label>
        </div>
    </section>

    <section class="panel form-section">
        <div class="form-section-header">
            <div class="step-number">3</div>
            <div>
                <h3>Responsable principal</h3>
                <p>Cette rubrique peut être complétée maintenant ou ultérieurement.</p>
            </div>
        </div>

        <div class="form-grid form-grid-3">
            <label class="field">
                <span>Civilité</span>
                <?php $civilite = $old['responsable_civilite'] ?? ($responsible['civilite'] ?? 'Non renseigne'); ?>
                <select name="responsable_civilite">
                    <?php foreach (['Non renseigne','Mme','M.','Autre'] as $item): ?>
                    <option value="<?= $item ?>" <?= $civilite === $item ? 'selected' : '' ?>><?= $item ?></option>
                    <?php endforeach; ?>
                </select>
            </label>
            <label class="field">
                <span>Nom</span>
                <input type="text" name="responsable_nom"
                       value="<?= resp_value('nom', $responsible, $old, 'responsable_nom') ?>">
            </label>
            <label class="field">
                <span>Prénom</span>
                <input type="text" name="responsable_prenom"
                       value="<?= resp_value('prenom', $responsible, $old, 'responsable_prenom') ?>">
            </label>
            <label class="field">
                <span>Lien avec l’adhérent</span>
                <input type="text" name="responsable_lien"
                       value="<?= resp_value('lien_avec_adherent', $responsible, $old, 'responsable_lien') ?>"
                       placeholder="Père, mère, tuteur…">
            </label>
            <label class="field">
                <span>Téléphone</span>
                <input type="tel" name="responsable_telephone"
                       value="<?= resp_value('telephone', $responsible, $old, 'responsable_telephone') ?>">
            </label>
            <label class="field">
                <span>E-mail</span>
                <input type="email" name="responsable_email"
                       value="<?= resp_value('email', $responsible, $old, 'responsable_email') ?>">
            </label>
        </div>

        <div class="check-grid">
            <label class="check-card">
                <input type="checkbox" name="responsable_autorite_parentale"
                    <?= isset($old['responsable_autorite_parentale']) || (!isset($_SESSION['old']) && !empty($responsible['autorite_parentale'])) ? 'checked' : '' ?>>
                <span><strong>Autorité parentale</strong><small>Personne autorisée à prendre les décisions administratives.</small></span>
            </label>
            <label class="check-card">
                <input type="checkbox" name="responsable_payeur_principal"
                    <?= isset($old['responsable_payeur_principal']) || (!isset($_SESSION['old']) && !empty($responsible['payeur_principal'])) ? 'checked' : '' ?>>
                <span><strong>Payeur principal</strong><small>Destinataire principal des factures et échéanciers.</small></span>
            </label>
        </div>
    </section>

    <section class="panel form-section">
        <div class="form-section-header">
            <div class="step-number">4</div>
            <div>
                <h3>Consentements et observations</h3>
                <p>Préférences de contact et informations complémentaires.</p>
            </div>
        </div>

        <div class="check-grid">
            <?php
            $checks = [
                'autorise_contact_telephone' => ['Contact téléphonique', 'Autorise les appels administratifs.'],
                'autorise_contact_email' => ['Contact par e-mail', 'Autorise les messages et documents par e-mail.'],
                'autorise_contact_sms' => ['Contact par SMS', 'Autorise les rappels courts par SMS.'],
                'rgpd_accepte' => ['Consentement RGPD', 'Consentement enregistré pour le traitement du dossier.'],
            ];
            foreach ($checks as $name => [$title, $desc]):
                $checked = array_key_exists($name, $old)
                    ? isset($old[$name])
                    : (!empty($family[$name]) || (!$family && $name !== 'rgpd_accepte'));
            ?>
            <label class="check-card">
                <input type="checkbox" name="<?= $name ?>" <?= $checked ? 'checked' : '' ?>>
                <span><strong><?= $title ?></strong><small><?= $desc ?></small></span>
            </label>
            <?php endforeach; ?>
        </div>

        <label class="field">
            <span>Observations</span>
            <textarea name="notes" rows="5" placeholder="Informations utiles au suivi administratif…"><?= form_value('notes', $family, $old) ?></textarea>
        </label>
    </section>

    <div class="form-actions">
        <a class="secondary-button button-link" href="/public/familles">Annuler</a>
        <button class="primary-button" type="submit"><?= htmlspecialchars($submitLabel) ?></button>
    </div>
</form>
