<?php
$typeLabels = [
    'DEVIS' => 'Devis',
    'BL' => 'Bon de livraison',
    'FACTURE' => 'Facture',
    'AVOIR' => 'Avoir',
];
$impactStock = in_array($type, ['BL', 'FACTURE'], true);
$mode = $mode ?? 'create';
$isEdit = $mode === 'edit';
$document = $document ?? null;
$existingLines = $existingLines ?? [];
$formAction = $isEdit ? 'index.php?page=documents_update' : 'index.php?page=documents_store';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1"><?= $isEdit ? 'Modifier' : 'Nouveau' ?> <?= htmlspecialchars($typeLabels[$type] ?? $type) ?></h1>
        <p class="text-muted mb-0">
            Document créé par le moteur commun DocumentManager.
            <?php if ($impactStock): ?>Ce document déclenchera une sortie de stock à l'enregistrement.<?php else: ?>Ce document ne modifie pas le stock.<?php endif; ?>
        </p>
    </div>
    <a href="index.php?page=documents" class="btn btn-outline-secondary">Retour</a>
</div>

<form method="post" action="<?= htmlspecialchars($formAction) ?>" id="documentForm">
    <?php if ($isEdit): ?><input type="hidden" name="id" value="<?= (int)$document['id'] ?>"><?php endif; ?>
    <input type="hidden" name="type_document" value="<?= htmlspecialchars($type) ?>">

    <div class="darlink-card p-4 mb-4">
        <div class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Type</label>
                <input type="text" class="form-control" value="<?= htmlspecialchars($typeLabels[$type] ?? $type) ?>" readonly>
            </div>
            <div class="col-md-3">
                <label class="form-label">Numéro</label>
                <input type="text" name="numero" class="form-control" value="<?= htmlspecialchars($numero) ?>" readonly>
            </div>
            <div class="col-md-3">
                <label class="form-label">Date</label>
                <input type="date" name="date_document" class="form-control" value="<?= htmlspecialchars($today) ?>" required>
            </div>
            <div class="col-md-3">
                <label class="form-label">Échéance</label>
                <input type="date" name="date_echeance" class="form-control" value="<?= htmlspecialchars($dateEcheance) ?>">
            </div>
            <div class="col-md-6">
                <label class="form-label">Client</label>
                <select name="client_id" class="form-select" id="documentClientSelect" required>
                    <option value="">Sélectionner...</option>
                    <?php foreach ($clients as $client): ?>
                        <option value="<?= (int)$client['id'] ?>" <?= $isEdit && (int)$document['client_id'] === (int)$client['id'] ? 'selected' : '' ?>><?= htmlspecialchars($client['raison_sociale'] . ' — ' . $client['code_client']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-6">
                <label class="form-label">Observations</label>
                <input type="text" name="observations" class="form-control" value="<?= htmlspecialchars($isEdit ? (string)($document['observations'] ?? '') : '') ?>" placeholder="Note interne ou commentaire document">
            </div>
        </div>
    </div>

    <div class="darlink-card p-4 mb-4">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h5 class="mb-0">Lignes</h5>
            <button type="button" class="btn btn-outline-primary" id="addLineBtn">+ Ajouter une ligne</button>
        </div>

        <div class="row mb-3">
            <div class="col-md-8 position-relative">
                <input type="text" id="articleQuickSearch" class="form-control" placeholder="Rechercher un article par référence ou désignation...">
                <div id="articleResults" class="list-group mt-2 shadow-sm" style="display:none; position:absolute; z-index:20; left:12px; right:12px;"></div>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-hover align-middle darlink-table" id="documentLinesTable">
                <thead>
                <tr>
                    <th style="width:120px;">Réf.</th>
                    <th>Désignation</th>
                    <th style="width:80px;">Unité</th>
                    <th class="text-end" style="width:100px;">Qté</th>
                    <th class="text-end" style="width:120px;">Prix HT</th>
                    <th class="text-end" style="width:90px;">Remise</th>
                    <th class="text-end" style="width:90px;">TVA</th>
                    <th class="text-end" style="width:120px;">Total HT</th>
                    <th style="width:50px;"></th>
                </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>

    <div class="darlink-card p-4 mb-4">
        <div class="row text-end">
            <div class="col-md-8 text-start text-muted small">
                <?php if ($type === 'DEVIS'): ?>Le devis ne réserve pas et ne modifie pas le stock.<?php endif; ?>
                <?php if ($type === 'BL'): ?>Le bon de livraison génère les sorties de stock.<?php endif; ?>
                <?php if ($type === 'FACTURE'): ?>La facture directe génère les sorties de stock. Une facture issue d'un BL ne redécrémente pas le stock.<?php endif; ?>
            </div>
            <div class="col-md-4">
                <div class="d-flex justify-content-between mb-2"><strong>Total HT</strong><span id="totalHt">0,00</span></div>
                <div class="d-flex justify-content-between mb-2"><strong>Total TVA</strong><span id="totalTva">0,00</span></div>
                <div class="d-flex justify-content-between fs-5"><strong>Total TTC</strong><strong id="totalTtc">0,00</strong></div>
                <div class="d-flex justify-content-between text-muted small mt-2"><span>Marge interne estimée</span><span id="totalMarge">0,00 %</span></div>
            </div>
        </div>
    </div>

    <div class="d-flex justify-content-end gap-2">
        <a href="index.php?page=documents" class="btn btn-outline-secondary">Annuler</a>
        <button type="submit" class="btn darlink-btn-primary"><?= $isEdit ? 'Enregistrer les modifications' : 'Enregistrer' ?></button>
    </div>
</form>

<script>
window.DARLINK_ARTICLES = <?= json_encode($articles, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE) ?>;
window.DARLINK_TARIFS_CLIENTS = <?= json_encode($tarifsClients ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE) ?>;
window.DARLINK_EXISTING_LINES = <?= json_encode($existingLines ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE) ?>;
</script>
<script src="assets/js/documents.js"></script>
