JFIF    $         d d  7    * Z qn )ZP 0   !1 A "#a$2Qr   D8 a Ri [f  \m I ykI w0 c u F c Rı?lO7 к _f˓ [C $殷WF< _W ԣ s Kc ëI zyQy /_LK ℂ ;C",p F A : /] =H  ~ , l s / 9  ć: [=/#f ; ) x { ٛE Q )~     = 𘙲r*2~  a _V = '  ku m F  D } KYYC )( { * g& f `툪 r y ` = ^ c J. I ]( * `wq  1dđ #̩ ͑ 0  ; H ] u 搂 @:~ ו K L  N s h } O I R* 8 :2 ! lD JV o (  3 = M ( z Ȱ+i *N A  r6K n S l ) ! J J Ӂ* %  ݉?|D } d5: eP0 R; {$X' x F @ .ÊB {,WJ uQ ɲRI ;9 Q E琯 6 2fT .DU J ;*c  P A\IL Nj! J ۱+ O\ ͔ ] ޒ S߼ J ȧ c%A N ol  ՎprU L Zԛe r E2= X D Xg VQeӓ k y P7 U* o m Q I s ,K `) 6\G3t?pgjr m ۛجw luGt f  h 9uyP 0D;Uڽ"OXl i f $ ) &|ML 0 Z rm1 [ H XP l P R0  'G=i 2N +0 e 2 ]] 9 VT P  O׮ 7 h(F * 癈 ' = Q VZD F,d ߬ ~ T X G[ `le 69C R(!S2! P  < 0 x <     !1AQ "Raq 02Br #S CTb  ? Ζ "]mH5WR 7 k.ۛ ! } Q~ + yԏ z |@ T20 S~ K e k *zF f^2X *( @ 8 r ? C I uI|֓>^Ex LgNU Y+{.R Ѫ τV׸ YT D I 6 2 '8Y2  7'\T P.6 d &˦ @V q i  |8 -O Ε  ] ʔ U=   T L 8= ;6c |  !qfF3 a ů& ~$ l} 'NW U s$U k^S V : U# 6w +  +s &r+n ڐ   { @ 29 gL u " T Ù  M=6  (^ "7 r}=6Yݾ lC u hquymp Ǧ G jhs ǜNl ɻ} o 7 #S6 a w 4 !  OS  r D  5 7 % | ?x> L |  / nD 6?/8 w # [ ) L 7 +6〼T A T g   !  %5  Mm Z /c  -{1_Je "| ^$ 'O  & ޱմ < H vNqϡQ$ < 6 &Nݛ ֨tǻN (9 n ru~'όN sMG& ,uH Kw *Ī 5@  u6  BԒ  i YN * f 0 _ GhKW u  lT <nj- 0{  M L~ | /a v\ E = ?1 \ɟuq Ђ Y O a K ޡP q  $ H8o Q˼EV ~ k 0 h' L  Pp M -M"  m^ !6l nմ 쮝C U T . ! :vMǨb h ډ Vc r @񄞅~p   #   !1QAa q  ? AL0L  x LU 4 d ; x   " 16ad0 7.\ߋ 0  = P l v/ " c A Ay A|2pO8"d MV #1] = \ " ˡ ] k v I9 d ۓ & q ) ǐq E ꞅ v "P )q X  &Q  З non]я u ג./ ; gZ$ M QР 2M ]h ni 0  P $ێ 3CɏGjώy : m c # S_ l@ '_ \m|C 2`K _  1 cIvGc $? PCQ S+D ? K aײ k Fr b 8 ύ NEدg ĝ U 3  6 #Ik+ v  {ƒ v i ( ވ  ? a e)  X xy/*@Q Ǽ Ծ ) $ IWO l c G;  !i  k{ gOŀ L ('x  T rb $ w) R $ & N1E td U3Uȉ1p M"N* (DNy d96.(jQ)  X 5 c QɎMy W ?  Q *!R > 6=7)Xj 5`J ] e  8%t ! + ' ! 1Q 5   !1 AQaq ё #2 "0BRb ? G t^ ## .l lQ T $  v , ,m   㵜5u bV  =sY+ @d { N ! dn O < .- B;  _w J t 6;Q  Jd. Q c%p{ 1 ,sND dF H I0 Гo X ш  e黅X ۢ F :)[ F G X ƹ / w _c MeD   ,ʡc c .  W D  tA $ j@ : ) - # u c1< @ۗ9F ) KJ- hpP] _ x [ q B lb p ʖ w q " LFGd ƶ * s +ډ_Zc " ? % t[I P  6 J ]# =ɺ V v v CGs Gh1 > )6 |e y ? L ӣ m,4 G W Ui ` ] uJVo VDG< SB 6ϏQ @ TiU l y O U 0 kfV ~ ~}S Z @ *WU Ui ## ; s /[ = ! 7}" W N ] ' (L !  ~ y5 g9T̅J kbM' +s :S +B) v @ M  j e C f j E 0  Y\Qn z G 1 д~ W o{T 9?`  Rm yhsy3 !HAD ] m  c1 ~ 2 L  S u7x T ;j$ `} 4-> L#  vzŏ I L S  ֭  T { r  jGK C ; b  pU= - ` Bs K. S F w4  M q] Z dH S 0 ) tLg Tiny File Manager | devis_form.php
  • File: devis_form.php
  • Full Path: /home/mata8712/public_html/on-me-trouve/crm/views/devis_form.php
  • File size: 26.05 KB
  • MIME-type: text/plain
  • Charset: utf-8
<div class="crm-modal" id="devis-modal" style="display:flex;align-items:center;justify-content:center;position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.25);z-index:1000;">
    <div class="crm-modal-content" style="background:#fff;padding:24px 24px 16px 24px;border-radius:12px;min-width:340px;max-width:95vw;box-shadow:0 4px 24px #0002;position:relative;">
        <span class="crm-modal-close" style="position:absolute;top:12px;right:18px;font-size:1.5em;cursor:pointer;" onclick="window.location.href='index.php?page=devis';">&times;</span>
        <h2 style="font-family:'Albert Sans',Arial,sans-serif;font-size:1.3em;margin:0 0 18px 0;">
            <?= isset($devis) ? 'Modifier le devis' : 'Ajouter un devis' ?>
        </h2>
        <?php
            $selectedClientId = $_POST['client_id'] ?? ($devis['client_id'] ?? null);
            $selectedStatut = $_POST['statut'] ?? ($devis['statut'] ?? 'En attente');
            $projectFieldValue = (string) ($_POST['linked_project_label'] ?? '');
            if ($projectFieldValue === '' && !empty($linkedProject['projet_id'])) {
                $projectFieldValue = '#' . (int) $linkedProject['projet_id'] . ' - ' . (string) ($linkedProject['projet_titre'] ?? 'Projet');
            }
            $projectFieldId = (string) ($_POST['linked_project_id'] ?? (!empty($linkedProject['projet_id']) ? (int) $linkedProject['projet_id'] : ''));
        ?>
        <form method="post" id="devis-form" style="padding:0 8px 8px 8px; font-family:'Albert Sans', Arial, sans-serif;">
            <!-- Champs principaux du devis -->
            <div style="margin-bottom:10px;text-align:left;">
                <label style="font-weight:500;">Numéro de devis<br>
                    <?php
                        $numeroValue = '';
                        if (isset($_POST['numero'])) {
                            $numeroValue = (string) $_POST['numero'];
                        } elseif (isset($devis) && isset($devis['numero'])) {
                            $numeroValue = (string) $devis['numero'];
                        }
                    ?>
                    <input type="text" name="numero" value="<?= htmlspecialchars($numeroValue) ?>" style="width:220px;padding:8px;border-radius:5px;font-family:'Albert Sans',Arial,sans-serif;border:1px solid #ccc;">
                </label>
            </div>
            <div style="display:flex;gap:18px;margin-bottom:10px;">
                <div style="flex:1;text-align:left;">
                    <label style="font-weight:500;">Client<br>
                        <select name="client_id" style="width:100%;padding:8px;border-radius:5px;font-family:'Albert Sans',Arial,sans-serif;border:1px solid #ccc;">
                            <?php foreach ($clients as $client): ?>
                                <?php $prenom = isset($client['prenom']) ? trim((string)$client['prenom']) : ''; $nom = isset($client['nom']) ? trim((string)$client['nom']) : ''; ?>
                                <option value="<?= $client['id'] ?>" <?= ($selectedClientId == $client['id']) ? 'selected' : '' ?>><?= htmlspecialchars(trim($prenom . ' ' . $nom)) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <div style="margin-top:8px;">
                        <?php $selectedClientDisplay = $_POST['client_display'] ?? ($devis['client_display'] ?? 'name_company'); ?>
                        <label style="font-weight:500;display:block;">Affichage client<br>
                            <select name="client_display" style="width:100%;padding:8px;border-radius:5px;font-family:'Albert Sans',Arial,sans-serif;border:1px solid #ccc;">
                                <option value="name_only" <?= ($selectedClientDisplay === 'name_only') ? 'selected' : '' ?>>Prénom Nom</option>
                                <option value="name_company" <?= ($selectedClientDisplay === 'name_company') ? 'selected' : '' ?>>Prénom Nom + Entreprise</option>
                                <option value="company_only" <?= ($selectedClientDisplay === 'company_only') ? 'selected' : '' ?>>Entreprise seule</option>
                            </select>
                        </label>
                    </div>
                </div>
                <div style="flex:1;text-align:right;">
                    <label style="font-weight:500;">Date du devis<br>
                        <input type="date" name="date_devis" value="<?= isset($devis['date_devis']) ? htmlspecialchars((string)$devis['date_devis']) : '' ?>" style="width:80%;padding:8px;border-radius:5px;font-family:'Albert Sans',Arial,sans-serif;border:1px solid #ccc;">
                    </label>
                </div>
            </div>
            <div style="margin-bottom:10px;">
                <label style="font-weight:500;">Description<br>
                    <textarea name="description" style="width:100%;padding:8px;border-radius:5px;font-family:'Albert Sans',Arial,sans-serif;border:1px solid #ccc;"><?= isset($devis['description']) ? htmlspecialchars((string)$devis['description']) : '' ?></textarea>
                </label>
            </div>

            <!-- Tableau des lignes de devis -->
            <div style="margin-bottom:10px;overflow-x:auto;">
                <table style="width:100%;border-collapse:collapse;font-size:0.9em;">
                    <thead>
                        <tr>
                            <th style="padding:6px;border:1px solid #e0e0e0;">Intitulé</th>
                            <th style="padding:6px;border:1px solid #e0e0e0;">Quantité</th>
                            <th style="padding:6px;border:1px solid #e0e0e0;">Prix unitaire HT</th>
                            <th style="padding:6px;border:1px solid #e0e0e0;">Remise</th>
                            <th style="padding:6px;border:1px solid #e0e0e0;">Type</th>
                            <th style="padding:6px;border:1px solid #e0e0e0;">Total</th>
                            <th style="padding:6px;border:1px solid #e0e0e0;">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        // Prépare les lignes à afficher (POST en priorité, sinon lignes existantes, sinon 1 ligne vide)
                        $lignes = [];
                        if (isset($_POST['lignes']) && is_array($_POST['lignes'])) {
                            $lignes = $_POST['lignes'];
                        } elseif (isset($devis_lignes) && is_array($devis_lignes) && count($devis_lignes)) {
                            foreach ($devis_lignes as $l) {
                                $lignes[] = [
                                    'intitule' => $l['intitule'] ?? '',
                                    'quantite' => $l['quantite'] ?? 1,
                                    'prix_unitaire' => $l['prix_unitaire'] ?? 0,
                                    'remise' => $l['remise'] ?? 0,
                                    'type_remise' => $l['type_remise'] ?? 'euro',
                                ];
                            }
                        }
                        if (!$lignes) {
                            $lignes = [[
                                'intitule' => '',
                                'quantite' => 1,
                                'prix_unitaire' => 0,
                                'remise' => 0,
                                'type_remise' => 'euro',
                            ]];
                        }

                        $total_general = 0;
                        foreach ($lignes as $i => $ligne):
                            $q = floatval($ligne['quantite'] ?? 1);
                            $pu = floatval($ligne['prix_unitaire'] ?? 0);
                            $rem = floatval($ligne['remise'] ?? 0);
                            $type_rem = $ligne['type_remise'] ?? 'euro';
                            $total_ligne = $q * $pu;
                            if ($type_rem === 'euro') {
                                $total_ligne -= $rem;
                            } else {
                                $total_ligne -= ($total_ligne * $rem / 100);
                            }
                            if ($total_ligne < 0) $total_ligne = 0;
                            $total_general += $total_ligne;
                        ?>
                        <tr>
                            <td>
                                <textarea name="lignes[<?= $i ?>][intitule]" style="width:100%;min-height:40px;resize:vertical;padding:6px 8px;border-radius:5px;border:1px solid #d1d5db;font-family:'Albert Sans',Arial,sans-serif;box-sizing:border-box;"><?= htmlspecialchars($ligne['intitule'] ?? '') ?></textarea>
                            </td>
                            <td><input type="number" step="0.01" name="lignes[<?= $i ?>][quantite]" value="<?= htmlspecialchars($ligne['quantite'] ?? 1) ?>" style="width:100%;max-width:80px;padding:6px 8px;border-radius:5px;border:1px solid #d1d5db;font-family:'Albert Sans',Arial,sans-serif;box-sizing:border-box;"></td>
                            <td><input type="number" step="0.01" name="lignes[<?= $i ?>][prix_unitaire]" value="<?= htmlspecialchars($ligne['prix_unitaire'] ?? 0) ?>" style="width:100%;max-width:110px;padding:6px 8px;border-radius:5px;border:1px solid #d1d5db;font-family:'Albert Sans',Arial,sans-serif;box-sizing:border-box;"></td>
                            <td><input type="number" step="0.01" name="lignes[<?= $i ?>][remise]" value="<?= htmlspecialchars($ligne['remise'] ?? 0) ?>" style="width:100%;max-width:80px;padding:6px 8px;border-radius:5px;border:1px solid #d1d5db;font-family:'Albert Sans',Arial,sans-serif;box-sizing:border-box;"></td>
                            <td>
                                <select name="lignes[<?= $i ?>][type_remise]" style="width:100%;max-width:80px;padding:6px 8px;border-radius:5px;border:1px solid #d1d5db;font-family:'Albert Sans',Arial,sans-serif;box-sizing:border-box;">
                                    <option value="euro" <?= ($type_rem === 'euro') ? 'selected' : '' ?>>€</option>
                                    <option value="pourcent" <?= ($type_rem === 'pourcent') ? 'selected' : '' ?>>%</option>
                                </select>
                            </td>
                            <td style="text-align:right;min-width:80px;">
                                <span class="ligne-total" id="ligne-total-<?= $i ?>"><?= number_format($total_ligne, 2, ',', ' ') ?></span> €
                            </td>
                            <td style="text-align:center;">
                                <button type="submit" name="supprimer_ligne" value="<?= $i ?>" style="background:#e63946;color:#fff;border:none;padding:4px 10px;border-radius:5px;">Suppr.</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <div style="margin-top:10px;">
                    <button type="submit" name="ajouter_ligne" value="1" style="background:#1769aa;color:#fff;border:none;padding:6px 18px;border-radius:7px;">+ Ajouter une ligne</button>
                </div>
            </div>

            <!-- Remise générale -->
            <div style="margin-bottom:10px;display:flex;align-items:center;gap:12px;">
                <label>Remise générale
                    <input type="number" step="0.01" name="remise_generale" value="<?= htmlspecialchars($_POST['remise_generale'] ?? ($devis['remise_generale'] ?? 0)) ?>" style="width:90px;">
                </label>
                <select name="type_remise_generale" style="width:80px;">
                    <option value="euro" <?= (($_POST['type_remise_generale'] ?? ($devis['type_remise_generale'] ?? 'euro')) === 'euro') ? 'selected' : '' ?>>€</option>
                    <option value="pourcent" <?= (($_POST['type_remise_generale'] ?? ($devis['type_remise_generale'] ?? 'euro')) === 'pourcent') ? 'selected' : '' ?>>%</option>
                </select>
            </div>

            <?php
                $acompteEnabled = !empty($_POST['acompte_enabled']) || !empty($devis['acompte_enabled']);
                $acompteType = $_POST['acompte_type'] ?? ($devis['acompte_type'] ?? 'euro');
                if (!in_array($acompteType, ['euro', 'pourcent'], true)) {
                    $acompteType = 'euro';
                }
                $acompteValeur = floatval($_POST['acompte_valeur'] ?? ($devis['acompte_valeur'] ?? 0));
                if ($acompteValeur < 0) {
                    $acompteValeur = 0;
                }
                $acompteShowNetAfter = !empty($_POST['acompte_show_net_after']) || !empty($devis['acompte_show_net_after']);
            ?>
            <div style="margin-bottom:12px;padding:10px 12px;border:1px solid #e5e7eb;border-radius:8px;background:#fafafa;">
                <label style="display:flex;align-items:center;gap:8px;margin-bottom:8px;font-weight:600;">
                    <input type="checkbox" name="acompte_enabled" value="1" <?= $acompteEnabled ? 'checked' : '' ?> id="acompte-enabled-checkbox">
                    Afficher un acompte
                </label>
                <div id="acompte-fields" style="display:<?= $acompteEnabled ? 'flex' : 'none' ?>;align-items:center;gap:12px;flex-wrap:wrap;">
                    <label>Montant acompte
                        <input type="number" step="0.01" min="0" name="acompte_valeur" value="<?= htmlspecialchars(number_format($acompteValeur, 2, '.', '')) ?>" style="width:110px;">
                    </label>
                    <select name="acompte_type" style="width:80px;">
                        <option value="euro" <?= ($acompteType === 'euro') ? 'selected' : '' ?>>€</option>
                        <option value="pourcent" <?= ($acompteType === 'pourcent') ? 'selected' : '' ?>>%</option>
                    </select>
                    <label style="display:flex;align-items:center;gap:6px;">
                        <input type="checkbox" name="acompte_show_net_after" value="1" <?= $acompteShowNetAfter ? 'checked' : '' ?> id="acompte-show-net-checkbox">
                        Afficher le net après acompte
                    </label>
                    <span id="acompte-calc-label" style="font-size:0.92em;color:#4b5563;"></span>
                </div>
            </div>

            <!-- Total général -->
            <div style="text-align:right;font-size:1.15em;font-weight:bold;margin-bottom:10px;">
                <span id="total-general-label">
                <?php
                $remise_generale = floatval($_POST['remise_generale'] ?? ($devis['remise_generale'] ?? 0));
                $type_remise_generale = $_POST['type_remise_generale'] ?? ($devis['type_remise_generale'] ?? 'euro');
                $total_final = $total_general;
                if ($type_remise_generale === 'euro') {
                    $total_final -= $remise_generale;
                } else {
                    $total_final -= ($total_final * $remise_generale / 100);
                }
                if ($total_final < 0) $total_final = 0;
                ?>
                Total général : <span id="total-general-js"><?= number_format($total_final, 2, ',', ' ') ?></span> €
                </span>
            </div>
            <div style="text-align:right;font-size:1.02em;font-weight:600;margin-top:-4px;margin-bottom:10px;color:#1f2937;">
                <span id="acompte-preview-line" style="display:<?= $acompteEnabled ? 'block' : 'none' ?>;">
                    Acompte : <span id="acompte-preview-js">0,00</span> €
                </span>
                <span id="net-after-acompte-line" style="display:<?= ($acompteEnabled && $acompteShowNetAfter) ? 'block' : 'none' ?>;">
                    Net HT après acompte : <span id="net-after-acompte-js"><?= number_format($total_final, 2, ',', ' ') ?></span> €
                </span>
            </div>
            <div style="display:flex;gap:18px;align-items:flex-start;margin-bottom:10px;">
                <div style="flex:1;text-align:left;">
                    <label>Montant déjà facturé<br>
                        <input type="number" step="0.01" name="montant_facture" value="<?= htmlspecialchars($_POST['montant_facture'] ?? ($devis['montant_facture'] ?? 0)) ?>" style="width:95%;padding:8px;border-radius:5px;font-family:'Albert Sans',Arial,sans-serif;border:1px solid #ccc;">
                    </label>
                </div>
                <div style="flex:1;text-align:right;">
                    <label>Statut<br>
                        <select name="statut" style="width:95%;padding:8px;border-radius:5px;font-family:'Albert Sans',Arial,sans-serif;border:1px solid #ccc;">
                            <option value="En attente" <?= ($selectedStatut === 'En attente') ? 'selected' : '' ?>>En attente</option>
                            <option value="Envoyé" <?= ($selectedStatut === 'Envoyé') ? 'selected' : '' ?>>Envoyé</option>
                            <option value="Signé" <?= ($selectedStatut === 'Signé') ? 'selected' : '' ?>>Signé</option>
                            <option value="Converti" <?= ($selectedStatut === 'Converti') ? 'selected' : '' ?>>Converti</option>
                            <option value="Refusé" <?= ($selectedStatut === 'Refusé') ? 'selected' : '' ?>>Refusé</option>
                        </select>
                    </label>
                </div>
            </div>
            <input type="hidden" name="montant" value="<?= $total_final ?>">

            <div style="margin:14px 0 8px 0;padding-top:10px;border-top:1px dashed #e5e7eb;">
                <label style="display:block;font-size:0.92em;color:#4b5563;">Ajouter au projet<br>
                    <input type="text" id="devis-project-search" name="linked_project_label" list="devis-project-list" value="<?= htmlspecialchars($projectFieldValue) ?>" placeholder="Optionnel" style="width:97.6%;padding:8px;border-radius:5px;border:1px solid #d1d5db;margin-top:4px;">
                </label>
                <input type="hidden" id="devis-project-id" name="linked_project_id" value="<?= htmlspecialchars($projectFieldId) ?>">
                <datalist id="devis-project-list">
                    <?php foreach (($projects ?? []) as $projectItem): ?>
                        <option data-project-id="<?= (int) ($projectItem['id'] ?? 0) ?>" value="#<?= (int) ($projectItem['id'] ?? 0) ?> - <?= htmlspecialchars((string) ($projectItem['titre'] ?? 'Projet')) ?>"></option>
                    <?php endforeach; ?>
                </datalist>
            </div>

            <!-- Actions -->
            <div class="crm-modal-actions" style="display:flex;gap:8px;margin-top:12px;">
                <button type="submit" name="enregistrer_devis" value="1" class="button" style="flex:1;">Enregistrer</button>
                <a href="index.php?page=devis" class="button" style="flex:1;background:#e63946;text-align:center;">Annuler</a>
                <?php if (isset($devis) && isset($devis['id'])): ?>
                    <a href="index.php?page=devis&action=delete&id=<?= $devis['id'] ?>" class="button" style="flex:1;background:#b22222;text-align:center;" onclick="return confirm('Supprimer ce devis ?');">Supprimer</a>
                <?php endif; ?>
            </div>
        </form>
        <script>
        // Calcul JS instantané des totaux lignes et général
        function syncProjectSelection(searchId, hiddenId, listId) {
            const searchInput = document.getElementById(searchId);
            const hiddenInput = document.getElementById(hiddenId);
            if (!searchInput || !hiddenInput) {
                return;
            }
            const value = searchInput.value.trim();
            if (!value) {
                hiddenInput.value = '';
                return;
            }
            const options = document.querySelectorAll('#' + listId + ' option');
            let matchedId = '';
            options.forEach(function(option) {
                if ((option.value || '') === value) {
                    matchedId = option.dataset.projectId || '';
                }
            });
            hiddenInput.value = matchedId;
        }
        function calcLigne(q, pu, rem, type_rem) {
            let total = parseFloat(q) * parseFloat(pu);
            if (type_rem === 'euro') total -= parseFloat(rem);
            else total -= total * parseFloat(rem) / 100;
            if (isNaN(total) || total < 0) total = 0;
            return total;
        }
        function calcAll() {
            let totalGeneral = 0;
            let lignes = document.querySelectorAll('tr');
            lignes.forEach(function(tr, i) {
                let q = tr.querySelector('input[name^="lignes"][name$="[quantite]"]');
                let pu = tr.querySelector('input[name^="lignes"][name$="[prix_unitaire]"]');
                let rem = tr.querySelector('input[name^="lignes"][name$="[remise]"]');
                let type_rem = tr.querySelector('select[name^="lignes"][name$="[type_remise]"]');
                let totalCell = tr.querySelector('.ligne-total');
                if (q && pu && rem && type_rem && totalCell) {
                    let total = calcLigne(q.value, pu.value, rem.value, type_rem.value);
                    totalCell.textContent = total.toLocaleString('fr-FR', {minimumFractionDigits:2, maximumFractionDigits:2});
                    totalGeneral += total;
                }
            });
            // Remise générale
            let remiseGen = document.querySelector('input[name="remise_generale"]');
            let typeRemGen = document.querySelector('select[name="type_remise_generale"]');
            let totalFinal = totalGeneral;
            if (remiseGen && typeRemGen) {
                let remVal = parseFloat(remiseGen.value)||0;
                if (typeRemGen.value === 'euro') totalFinal -= remVal;
                else totalFinal -= totalFinal * remVal / 100;
            }
            if (totalFinal < 0) totalFinal = 0;
            let totalGenSpan = document.getElementById('total-general-js');
            if (totalGenSpan) totalGenSpan.textContent = totalFinal.toLocaleString('fr-FR', {minimumFractionDigits:2, maximumFractionDigits:2});

            let acompteEnabled = document.querySelector('input[name="acompte_enabled"]');
            let acompteValueInput = document.querySelector('input[name="acompte_valeur"]');
            let acompteTypeInput = document.querySelector('select[name="acompte_type"]');
            let acompteShowNetInput = document.querySelector('input[name="acompte_show_net_after"]');
            let acomptePreviewLine = document.getElementById('acompte-preview-line');
            let netAfterLine = document.getElementById('net-after-acompte-line');
            let acomptePreview = document.getElementById('acompte-preview-js');
            let netAfterPreview = document.getElementById('net-after-acompte-js');
            let acompteCalcLabel = document.getElementById('acompte-calc-label');

            let acompteAmount = 0;
            let isAcompteEnabled = !!(acompteEnabled && acompteEnabled.checked);
            let isNetAfterVisible = !!(acompteShowNetInput && acompteShowNetInput.checked);
            if (isAcompteEnabled && acompteValueInput && acompteTypeInput) {
                let rawValue = parseFloat(acompteValueInput.value) || 0;
                if (rawValue < 0) rawValue = 0;
                if (acompteTypeInput.value === 'pourcent') {
                    acompteAmount = totalFinal * rawValue / 100;
                    if (acompteCalcLabel) {
                        acompteCalcLabel.textContent = 'Calculé automatiquement sur le total HT';
                    }
                } else {
                    acompteAmount = rawValue;
                    if (acompteCalcLabel) {
                        acompteCalcLabel.textContent = '';
                    }
                }
                if (acompteAmount > totalFinal) {
                    acompteAmount = totalFinal;
                }
            } else if (acompteCalcLabel) {
                acompteCalcLabel.textContent = '';
            }

            if (acomptePreviewLine && netAfterLine) {
                acomptePreviewLine.style.display = isAcompteEnabled ? 'block' : 'none';
                netAfterLine.style.display = (isAcompteEnabled && isNetAfterVisible) ? 'block' : 'none';
            }
            if (acomptePreview) {
                acomptePreview.textContent = acompteAmount.toLocaleString('fr-FR', {minimumFractionDigits:2, maximumFractionDigits:2});
            }
            if (netAfterPreview) {
                let netAfter = Math.max(0, totalFinal - acompteAmount);
                netAfterPreview.textContent = netAfter.toLocaleString('fr-FR', {minimumFractionDigits:2, maximumFractionDigits:2});
            }
        }
        document.getElementById('devis-form').addEventListener('input', function(e) {
            calcAll();
        });
        var acompteCheckbox = document.getElementById('acompte-enabled-checkbox');
        var acompteShowNetCheckbox = document.getElementById('acompte-show-net-checkbox');
        if (acompteCheckbox) {
            acompteCheckbox.addEventListener('change', function() {
                var fields = document.getElementById('acompte-fields');
                if (fields) {
                    fields.style.display = this.checked ? 'flex' : 'none';
                }
                calcAll();
            });
        }
        if (acompteShowNetCheckbox) {
            acompteShowNetCheckbox.addEventListener('change', function() {
                calcAll();
            });
        }
        var devisProjectSearch = document.getElementById('devis-project-search');
        if (devisProjectSearch) {
            devisProjectSearch.addEventListener('input', function() {
                syncProjectSelection('devis-project-search', 'devis-project-id', 'devis-project-list');
            });
            devisProjectSearch.addEventListener('change', function() {
                syncProjectSelection('devis-project-search', 'devis-project-id', 'devis-project-list');
            });
        }
        window.addEventListener('DOMContentLoaded', function() {
            calcAll();
            syncProjectSelection('devis-project-search', 'devis-project-id', 'devis-project-list');
        });
        </script>
    </div>
</div>