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.php
  • File: devis.php
  • Full Path: /home/mata8712/public_html/on-me-trouve/crm/views/devis.php
  • File size: 33.28 KB
  • MIME-type: text/plain
  • Charset: utf-8
<div class="crm-main">
    <?php
    $devisCsvFields = [
        'id' => 'ID',
        'numero' => 'Numero',
        'client_id' => 'Client ID',
        'client_nom' => 'Client',
        'client_prenom' => 'Prénom client',
        'date_devis' => 'Date du devis',
        'montant' => 'Montant total',
        'montant_facture' => 'Montant facture',
        'statut' => 'Statut',
        'description' => 'Description',
        'remise_generale' => 'Remise generale',
        'type_remise_generale' => 'Type remise generale',
    ];
    $devisImportFields = [
        'client_id' => 'Client ID',
        'client_prenom' => 'Prénom client',
        'numero' => 'Numero',
        'date_devis' => 'Date du devis',
        'montant' => 'Montant total',
        'montant_facture' => 'Montant facture',
        'statut' => 'Statut',
        'description' => 'Description',
        'remise_generale' => 'Remise generale',
        'type_remise_generale' => 'Type remise generale',
    ];
    $importMasks = isset($importMasks) && is_array($importMasks) ? $importMasks : [];
    $devisStatusClass = static function ($statut) {
        $normalized = mb_strtolower(trim((string) $statut), 'UTF-8');
        return match ($normalized) {
            'en attente', 'brouillon' => 'crm-status-pending',
            'envoye', 'envoyé', 'envoyee', 'envoyée' => 'crm-status-sent',
            'signe', 'signé', 'payee', 'payée' => 'crm-status-success',
            'refuse', 'refusé', 'annule', 'annulé', 'en retard' => 'crm-status-cancelled',
            'converti' => 'crm-status-converted',
            default => 'crm-status-pending',
        };
    };
    ?>
    <div class="crm-devis-header" style="display:flex;align-items:center;justify-content:space-between;margin-bottom:18px;">
        <div style="display:flex;align-items:center;gap:18px;">
            <h1 style="margin:0;">Devis</h1>
            <div class="crm-dashboard-date"><?php echo date('d/m/Y'); ?></div>
        </div>
        <div class="crm-devis-actions" style="display:flex;gap:12px;align-items:center;">
            <input type="text" id="search-devis" placeholder="Rechercher..." style="width:220px;padding:7px 12px;border-radius:6px;border:1px solid #ccc;">
            <button type="button" class="button" id="search-devis-btn">Rechercher</button>
            <form method="get" action="index.php" style="display:inline;">
                <input type="hidden" name="page" value="devis">
                <input type="hidden" name="action" value="add">
                <button type="submit" class="button crm-btn-add-devis">Ajouter un devis</button>
            </form>
            <form method="get" action="index.php" style="display:inline;">
                <button type="button" class="button crm-btn-csv" data-csv-open="devis-csv-modal">Import/Export CSV</button>
            </form>
            <!-- exercice filter moved below header, above list -->
        </div>
    </div>
    <?php if (isset($_GET['csv_message'])): ?>
        <div style="margin:0 0 16px 0;padding:10px 14px;border-radius:8px;background:<?= (($_GET['csv_status'] ?? '') === 'success') ? '#e8f7ee' : '#fdecec' ?>;color:<?= (($_GET['csv_status'] ?? '') === 'success') ? '#186a3b' : '#b42318' ?>;font-weight:600;">
            <?= htmlspecialchars((string) $_GET['csv_message']) ?>
        </div>
    <?php endif; ?>
    <?php if (isset($_GET['increment_message'])): ?>
        <div style="margin:0 0 16px 0;padding:10px 14px;border-radius:8px;background:<?= (($_GET['increment_status'] ?? '') === 'success') ? '#e8f7ee' : '#fdecec' ?>;color:<?= (($_GET['increment_status'] ?? '') === 'success') ? '#186a3b' : '#b42318' ?>;font-weight:600;">
            <?= htmlspecialchars((string) $_GET['increment_message']) ?>
        </div>
    <?php endif; ?>
    <div class="crm-dashboard-bottom-row">
        <div class="crm-encart crm-encart-50">
            <div class="crm-devis-list-container">
                <?php if (!empty($infos_gestion['filtre_exercice'])): ?>
                <div style="margin:8px 0 12px 0;padding:10px;border:1px solid #e6eef8;border-radius:8px;background:#f8fbff;display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
                    <form method="get" action="index.php" id="exercice-filter-form" style="display:flex;gap:8px;align-items:center;margin:0;">
                        <input type="hidden" name="page" value="devis">
                        <label style="font-weight:600;margin-right:6px;">Filtrer :</label>
                        <label>
                            <select name="exercice_mode" id="exercice_mode">
                                <option value="">Aucun</option>
                                <option value="year" <?= (isset($_GET['exercice_mode']) && $_GET['exercice_mode'] === 'year') ? 'selected' : '' ?>>Année</option>
                                <option value="quarter" <?= (isset($_GET['exercice_mode']) && $_GET['exercice_mode'] === 'quarter') ? 'selected' : '' ?>>Trimestre</option>
                            </select>
                        </label>
                        <label id="exercice_year_container" style="display:none;">
                            <select name="exercice_year" id="exercice_year">
                                <?php $currentYear = (int)date('Y'); for ($y = $currentYear - 5; $y <= $currentYear + 1; $y++): ?>
                                    <option value="<?= $y ?>" <?= (isset($_GET['exercice_year']) && (int)$_GET['exercice_year'] === $y) ? 'selected' : '' ?>><?= $y ?></option>
                                <?php endfor; ?>
                            </select>
                        </label>
                        <label id="exercice_quarter_container" style="display:none;">
                            <select name="exercice_quarter" id="exercice_quarter">
                                <?php for ($q = 1; $q <= 4; $q++): ?>
                                    <option value="<?= $q ?>" <?= (isset($_GET['exercice_quarter']) && (int)$_GET['exercice_quarter'] === $q) ? 'selected' : '' ?>>T<?= $q ?></option>
                                <?php endfor; ?>
                            </select>
                        </label>
                        <button type="submit" class="button">Appliquer</button>
                    </form>
                    <script>
                        (function(){
                            var mode = document.getElementById('exercice_mode');
                            var yearC = document.getElementById('exercice_year_container');
                            var quarterC = document.getElementById('exercice_quarter_container');
                            function update() {
                                if (!mode) return;
                                if (mode.value === 'year') { yearC.style.display = ''; quarterC.style.display = 'none'; }
                                else if (mode.value === 'quarter') { yearC.style.display = ''; quarterC.style.display = ''; }
                                else { yearC.style.display = 'none'; quarterC.style.display = 'none'; }
                            }
                            if (mode) { mode.addEventListener('change', update); update(); }
                        })();
                    </script>
                </div>
                <?php endif; ?>

                <script>
                function filterDevis() {
                    const input = document.getElementById('search-devis');
                    const val = (input ? input.value : '').toLowerCase();
                    document.querySelectorAll('.crm-devis-table tbody tr').forEach(tr => {
                        const txt = tr.textContent.toLowerCase();
                        tr.style.display = txt.includes(val) ? '' : 'none';
                    });
                }
                document.getElementById('search-devis').addEventListener('input', filterDevis);
                document.getElementById('search-devis-btn').addEventListener('click', filterDevis);
                </script>
                <table class="crm-devis-table">
                    <thead>
                        <tr>
                            <!-- Colonne ID masquée -->
                            <th style="display:none;"><span>ID</span></th>
                            <th>
                                <span style="display:inline-flex;align-items:center;gap:8px;">
                                    <span>Numéro</span>
                                    <button type="button" class="crm-reset-increment-btn" data-page="devis" title="Réinitialiser le prochain ID devis" style="border:none;background:none;color:#1769aa;cursor:pointer;font-size:1em;padding:0;line-height:1;">&#8635;</button>
                                </span>
                            </th>
                            <th>Nom du devis</th>
                            <th>Client</th>
                            <th>Montant total</th>
                            <th>Montant facturé</th>
                            <th>Statut</th>
                            <th>Signature</th>
                            <th>Date</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (isset($devisList) && is_array($devisList) && count($devisList)): ?>
                            <?php foreach ($devisList as $d): ?>
                                <tr class="crm-devis-row" tabindex="0" style="cursor:pointer;">
                                    <!-- Cellule ID masquée -->
                                    <td style="display:none;">&nbsp;<?= htmlspecialchars((string) $d['id']) ?></td>
                                    <td onclick="window.location.href='index.php?page=devis&action=apercu&id=<?= $d['id'] ?>'" style="cursor:pointer;">
                                        <?php
                                            $numero = $d['numero'] ?? '';
                                            if ($numero === '' || $numero === null) {
                                                $fallbackYear = date('Y', strtotime($d['date_devis'] ?? 'now'));
                                                $prefix = isset($infos_gestion['prefixe_devis']) && $infos_gestion['prefixe_devis'] !== '' ? $infos_gestion['prefixe_devis'] : 'D-{year}-00';
                                                $resolved = str_replace('{year}', $fallbackYear, $prefix);
                                                $numero = $resolved . (string) $d['id'];
                                            }
                                            echo htmlspecialchars((string) $numero);
                                        ?>
                                    </td>
                                    <td onclick="window.location.href='index.php?page=devis&action=apercu&id=<?= $d['id'] ?>'" style="cursor:pointer;"><?= htmlspecialchars($d['description']) ?></td>
                                    <td onclick="window.location.href='index.php?page=devis&action=apercu&id=<?= $d['id'] ?>'" style="cursor:pointer;">
                                        <?php
                                        $prenom = isset($d['client_prenom']) ? trim((string)$d['client_prenom']) : '';
                                        $nom = isset($d['client_nom']) ? trim((string)$d['client_nom']) : '';
                                        echo htmlspecialchars(trim($prenom . ' ' . $nom));
                                        ?>
                                    </td>
                                    <td onclick="window.location.href='index.php?page=devis&action=apercu&id=<?= $d['id'] ?>'" style="cursor:pointer;"><?= number_format($d['montant'], 2, ',', ' ') ?> €</td>
                                    <td onclick="window.location.href='index.php?page=devis&action=apercu&id=<?= $d['id'] ?>'" style="cursor:pointer;"><?= number_format($d['montant_facture'], 2, ',', ' ') ?> €</td>
                                    <td onclick="window.location.href='index.php?page=devis&action=apercu&id=<?= $d['id'] ?>'" style="cursor:pointer;">
                                        <span class="crm-status <?= $devisStatusClass($d['statut'] ?? '') ?>"><?= htmlspecialchars($d['statut']) ?></span>
                                    </td>
                                    <td onclick="window.location.href='index.php?page=devis&action=apercu&id=<?= $d['id'] ?>'" style="cursor:pointer;">
                                        <?php
                                        $sig = isset($devisSignatures[$d['id']]) ? $devisSignatures[$d['id']] : null;
                                        if (!$sig || !$sig['has_data'] || $sig['global_status'] === 'none') {
                                            echo '<span style="color:#999;font-size:0.9em;">Aucune</span>';
                                        } elseif ($sig['global_status'] === 'en_attente') {
                                            $pending = (int) $sig['pending_count'];
                                            echo '<span style="display:inline-block;padding:2px 6px;border-radius:999px;background:#fff3cd;color:#856404;font-size:0.9em;">En attente'.($pending>1?' ('.$pending.')':'').'</span>';
                                        } elseif ($sig['global_status'] === 'signe') {
                                            $choice = $sig['last_client_choice'] ?? '';
                                            $option = $sig['last_payment_option'] ?? '';
                                            $labelChoice = '';
                                            if ($choice === 'bank') {
                                                $labelChoice = ' - banque';
                                            } elseif ($choice === 'online') {
                                                if ($option === 'acompte_manual') {
                                                    $labelChoice = ' - acompte manuel';
                                                } elseif ($option === 'acompte_40') {
                                                    $labelChoice = ' - acompte 40%';
                                                } elseif ($option === 'full_ht') {
                                                    $labelChoice = ' - 100% HT';
                                                } elseif ($option === 'abonnement_auto') {
                                                    $labelChoice = ' - abonnement mensuel';
                                                } else {
                                                    $labelChoice = ' - en ligne';
                                                }
                                            }
                                            echo '<a href="index.php?page=devis&action=signature_snapshot&id='.(int) $d['id'].'" style="display:inline-block;padding:2px 6px;border-radius:999px;background:#e8f7ee;color:#186a3b;font-size:0.9em;text-decoration:none;font-weight:600;" title="Voir la photographie de signature">Signé'.$labelChoice.'</a>';
                                        }
                                        ?>
                                    </td>
                                    <td onclick="window.location.href='index.php?page=devis&action=apercu&id=<?= $d['id'] ?>'" style="cursor:pointer;"><?= date('d/m/Y', strtotime($d['date_devis'])) ?></td>
                                    <td style="text-align:center;cursor:auto;">
                                        <details class="crm-row-actions" style="display:inline-block;position:relative;">
                                            <summary class="crm-row-actions-toggle" style="list-style:none;cursor:pointer;font-size:1.7em;line-height:1;vertical-align:middle;text-decoration:none;color:#232946;padding:0 6px;border:none;background:none;outline:none;">&#8942;</summary>
                                            <div class="crm-row-actions-menu" style="position:fixed;z-index:1200;background:#fff;border:1px solid #e0e0e0;border-radius:7px;box-shadow:0 2px 8px #0001;min-width:110px;">
                                                <a href="index.php?page=devis&action=edit&id=<?= $d['id'] ?>" style="display:block;padding:8px 16px;color:#232946;text-decoration:none;font-size:1em;">Modifier</a>
                                                <a href="index.php?page=devis&action=apercu&id=<?= $d['id'] ?>" style="display:block;padding:8px 16px;color:#232946;text-decoration:none;font-size:1em;">Aperçu</a>
                                                <a href="index.php?page=devis&action=pdf&id=<?= $d['id'] ?>" style="display:block;padding:8px 16px;color:#232946;text-decoration:none;font-size:1em;">Exporter en PDF</a>
                                                <?php if (($d['statut'] ?? '') !== 'Converti'): ?>
                                                    <a href="index.php?page=devis&action=convert&id=<?= $d['id'] ?>" class="crm-devis-convert-trigger" data-convert-url="index.php?page=devis&action=convert&id=<?= $d['id'] ?>" data-total="<?= htmlspecialchars((string) ($d['montant'] ?? 0), ENT_QUOTES) ?>" data-devis-label="<?= htmlspecialchars((string) ($d['numero'] ?? ('#' . $d['id'])), ENT_QUOTES) ?>" style="display:block;padding:8px 16px;color:#1769aa;text-decoration:none;font-size:1em;font-weight:600;">Convertir</a>
                                                <?php endif; ?>
                                                <a href="index.php?page=devis&action=delete&id=<?= $d['id'] ?>" onclick="return confirm('Supprimer ce devis ? Cette action est irréversible.');" style="display:block;padding:8px 16px;color:#e63946;text-decoration:none;font-size:1em;font-weight:600;">Supprimer</a>
                                            </div>
                                        </details>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="9" style="color:#888;">Aucun devis</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
                <style>
                .crm-devis-list-container {
                    background: #fff;
                    border-radius: 0px;
                    box-shadow: 0 0px 0px #0001;
                    padding: 0px 0px;
                    width: 100%;
                    margin: 0 auto;
                    overflow-x: auto;
                }
                </style>
            </div>
        </div>
    </div>
    <?php
    // Affichage de la modale d'ajout ou d'édition si action=add ou edit
    if (isset($_GET['action']) && $_GET['action'] === 'add') {
        include __DIR__ . '/devis_form.php';
    }
    if (isset($_GET['action']) && $_GET['action'] === 'edit' && isset($devis)) {
        include __DIR__ . '/devis_form.php';
    }
    ?>
    <div id="crm-devis-convert-modal" class="crm-modal" style="display:none;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:1300;">
        <div class="crm-modal-content" style="background:#fff;padding:24px;border-radius:12px;min-width:340px;max-width:560px;width:92vw;box-shadow:0 4px 24px #0002;position:relative;">
            <span id="crm-devis-convert-close" style="position:absolute;top:12px;right:18px;font-size:1.5em;cursor:pointer;">&times;</span>
            <h2 style="font-family:'Albert Sans',Arial,sans-serif;font-size:1.3em;margin:0 0 18px 0;">Convertir le devis en facture</h2>
            <form method="post" id="crm-devis-convert-form">
                <p id="crm-devis-convert-caption" style="margin:0 0 14px 0;color:#4b5563;"></p>
                <label style="display:flex;align-items:flex-start;gap:10px;margin-bottom:12px;cursor:pointer;">
                    <input type="radio" name="convert_mode" value="global" checked>
                    <span>
                        <strong>Générer facture globale</strong><br>
                        <span style="color:#6b7280;font-size:0.92em;">Une seule facture pour le montant total du devis.</span>
                    </span>
                </label>
                <label style="display:flex;align-items:flex-start;gap:10px;margin-bottom:12px;cursor:pointer;">
                    <input type="radio" name="convert_mode" value="separate_deposit">
                    <span>
                        <strong>Générer avec facture d'acompte à part</strong><br>
                        <span style="color:#6b7280;font-size:0.92em;">Crée une facture d'acompte puis une facture de solde avec déduction automatique.</span>
                    </span>
                </label>
                <div id="crm-devis-deposit-box" style="display:none;margin:0 0 16px 28px;">
                    <label style="display:block;font-weight:600;">Montant d'acompte
                        <input type="number" step="0.01" min="0.01" name="deposit_amount" id="crm-devis-deposit-amount" style="display:block;width:180px;margin-top:6px;padding:8px;border-radius:6px;border:1px solid #d1d5db;">
                    </label>
                    <div id="crm-devis-deposit-help" style="margin-top:6px;font-size:0.88em;color:#6b7280;"></div>
                </div>
                <div style="display:flex;gap:10px;justify-content:flex-end;">
                    <button type="button" id="crm-devis-convert-cancel" class="button" style="background:#f3f4f6;color:#232946;">Annuler</button>
                    <button type="submit" class="button">Valider</button>
                </div>
            </form>
        </div>
    </div>
    <div id="devis-csv-modal" class="crm-modal" style="display:none;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;border-radius:12px;min-width:340px;max-width:760px;width:92vw;box-shadow:0 4px 24px #0002;position:relative;">
            <span data-csv-close="devis-csv-modal" style="position:absolute;top:12px;right:18px;font-size:1.5em;cursor:pointer;">&times;</span>
            <h2 style="font-family:'Albert Sans',Arial,sans-serif;font-size:1.3em;margin:0 0 18px 0;">Import / Export CSV</h2>
            <div style="display:flex;gap:24px;align-items:flex-start;flex-wrap:wrap;">
                <div style="flex:1;min-width:260px;">
                    <h3 style="margin:0 0 10px 0;font-size:1.05em;">Exporter les devis</h3>
                    <form method="get" action="index.php">
                        <input type="hidden" name="page" value="devis">
                        <input type="hidden" name="action" value="export_csv">
                        <label style="display:flex;align-items:center;gap:8px;margin-bottom:10px;font-weight:600;">
                            <input type="checkbox" data-csv-select-all="devis-csv-modal" checked>
                            Tout selectionner
                        </label>
                        <div style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:8px 14px;margin-bottom:14px;">
                            <?php foreach ($devisCsvFields as $field => $label): ?>
                                <label style="display:flex;align-items:center;gap:8px;">
                                    <input type="checkbox" name="fields[]" value="<?= htmlspecialchars($field) ?>" checked>
                                    <?= htmlspecialchars($label) ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                        <button type="submit" class="button" style="width:100%;">Exporter</button>
                    </form>
                </div>
                <div style="flex:1;min-width:260px;">
                    <h3 style="margin:0 0 10px 0;font-size:1.05em;">Importer des devis</h3>
                    <p style="margin:0 0 12px 0;color:#555;">Chargez un CSV, ajustez la correspondance des colonnes si besoin, puis reutilisez ce masque sur les prochains imports.</p>
                    <a href="index.php?page=devis&action=template_csv" class="button" style="display:block;text-align:center;margin-bottom:12px;">Telecharger le gabarit</a>
                    <div style="padding:12px;border:1px solid #e5e7eb;border-radius:10px;background:#f9fafb;margin-bottom:14px;">
                        <h4 style="margin:0 0 10px 0;">Creer ou mettre a jour un masque d'import</h4>
                        <form method="post" action="index.php?page=devis" style="display:flex;flex-direction:column;gap:10px;">
                            <input type="text" name="mask_name" placeholder="Nom du masque" style="width:100%;padding:8px;border-radius:6px;border:1px solid #d1d5db;" required>
                            <div style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:8px 12px;">
                                <?php foreach ($devisImportFields as $field => $label): ?>
                                    <label style="display:flex;flex-direction:column;gap:4px;font-size:0.92em;">
                                        <span><?= htmlspecialchars($label) ?></span>
                                        <input type="text" name="mask_mapping[<?= htmlspecialchars($field) ?>]" placeholder="Nom de colonne CSV" style="width:100%;padding:8px;border-radius:6px;border:1px solid #d1d5db;">
                                    </label>
                                <?php endforeach; ?>
                            </div>
                            <button type="submit" name="save_import_mask" class="button">Enregistrer le masque</button>
                        </form>
                    </div>
                    <form method="post" action="index.php?page=devis&action=import_csv" enctype="multipart/form-data" data-import-assistant="true">
                        <label style="display:flex;flex-direction:column;gap:6px;margin-bottom:10px;">
                            <span style="font-weight:600;">Masque existant</span>
                            <select name="import_mask_id" data-import-mask-select style="width:100%;padding:8px;border-radius:6px;border:1px solid #d1d5db;">
                                <option value="">Aucun masque - detection automatique</option>
                                <?php if (!empty($importMasks)): ?>
                                    <?php foreach ($importMasks as $mask): ?>
                                        <option
                                            value="<?= htmlspecialchars((string) $mask['id']) ?>"
                                            data-mask-mappings="<?= htmlspecialchars((string) json_encode($mask['mappings'] ?? [], JSON_UNESCAPED_UNICODE), ENT_QUOTES) ?>"
                                        ><?= htmlspecialchars((string) $mask['name']) ?></option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                        </label>
                        <input type="file" name="csv_file" accept=".csv,text/csv" data-import-file style="width:100%;margin-bottom:12px;" required>
                        <div style="padding:12px;border:1px solid #e5e7eb;border-radius:10px;background:#f9fafb;margin-bottom:12px;">
                            <h4 style="margin:0 0 10px 0;">Assistant de correspondance</h4>
                            <p style="margin:0 0 10px 0;color:#555;font-size:0.95em;">Le navigateur lit l'entete du CSV pour vous proposer une correspondance automatique des colonnes.</p>
                            <div style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:8px 12px;">
                                <?php foreach ($devisImportFields as $field => $label): ?>
                                    <label style="display:flex;flex-direction:column;gap:4px;font-size:0.92em;">
                                        <span><?= htmlspecialchars($label) ?></span>
                                        <select
                                            name="import_mapping[<?= htmlspecialchars($field) ?>]"
                                            data-import-mapping-field="<?= htmlspecialchars($field) ?>"
                                            data-import-label="<?= htmlspecialchars($label, ENT_QUOTES) ?>"
                                            style="width:100%;padding:8px;border-radius:6px;border:1px solid #d1d5db;"
                                        >
                                            <option value="">Detection automatique</option>
                                        </select>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <label style="display:flex;flex-direction:column;gap:6px;margin-bottom:12px;">
                            <span style="font-weight:600;">Enregistrer aussi ce mapping comme nouveau masque</span>
                            <input type="text" name="save_mask_name" placeholder="Ex. Export cabinet comptable devis" style="width:100%;padding:8px;border-radius:6px;border:1px solid #d1d5db;">
                        </label>
                        <button type="submit" class="button" style="width:100%;">Importer</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script src="assets/js/csv-tools.js"></script>
    <script src="assets/js/actions-menu.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        var modal = document.getElementById('crm-devis-convert-modal');
        var form = document.getElementById('crm-devis-convert-form');
        var caption = document.getElementById('crm-devis-convert-caption');
        var depositBox = document.getElementById('crm-devis-deposit-box');
        var depositInput = document.getElementById('crm-devis-deposit-amount');
        var depositHelp = document.getElementById('crm-devis-deposit-help');
        var closeBtn = document.getElementById('crm-devis-convert-close');
        var cancelBtn = document.getElementById('crm-devis-convert-cancel');
        var currentTotal = 0;

        function updateDepositVisibility() {
            if (!form || !depositBox || !depositInput) {
                return;
            }
            var selected = form.querySelector('input[name="convert_mode"]:checked');
            var separate = selected && selected.value === 'separate_deposit';
            depositBox.style.display = separate ? '' : 'none';
            depositInput.required = !!separate;
            if (separate) {
                depositInput.max = currentTotal > 0 ? Math.max(0, currentTotal - 0.01).toFixed(2) : '';
                depositHelp.textContent = currentTotal > 0 ? ('Le solde sera automatiquement calculé sur un total de ' + currentTotal.toLocaleString('fr-FR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €.') : '';
            }
        }

        function closeModal() {
            if (modal) {
                modal.style.display = 'none';
            }
        }

        document.querySelectorAll('.crm-devis-convert-trigger').forEach(function(link) {
            link.addEventListener('click', function(event) {
                if (!modal || !form) {
                    return;
                }
                event.preventDefault();
                form.action = link.dataset.convertUrl || link.getAttribute('href') || '';
                currentTotal = parseFloat((link.dataset.total || '0').replace(',', '.')) || 0;
                var label = link.dataset.devisLabel || '';
                caption.textContent = label ? ('Choisissez le mode de conversion pour le devis ' + label + '.') : 'Choisissez le mode de conversion.';
                form.querySelectorAll('input[name="convert_mode"]').forEach(function(input, index) {
                    input.checked = index === 0;
                });
                if (depositInput) {
                    depositInput.value = currentTotal > 0 ? (currentTotal * 0.3).toFixed(2) : '';
                }
                updateDepositVisibility();
                modal.style.display = 'flex';
            });
        });

        if (form) {
            form.querySelectorAll('input[name="convert_mode"]').forEach(function(input) {
                input.addEventListener('change', updateDepositVisibility);
            });
        }
        if (closeBtn) closeBtn.addEventListener('click', closeModal);
        if (cancelBtn) cancelBtn.addEventListener('click', closeModal);
        if (modal) {
            modal.addEventListener('click', function(event) {
                if (event.target === modal) {
                    closeModal();
                }
            });
        }
    });
    </script>
    <script>
    (function () {
        document.querySelectorAll('.crm-reset-increment-btn').forEach(function (button) {
            button.addEventListener('click', function () {
                const page = this.getAttribute('data-page') || '';
                const value = window.prompt('Nouvelle valeur du prochain ID pour ' + page + ' :', '1');
                if (value === null) {
                    return;
                }
                const normalized = parseInt(String(value).trim(), 10);
                if (!Number.isInteger(normalized) || normalized <= 0) {
                    window.alert('Veuillez saisir un entier strictement positif.');
                    return;
                }
                window.location.href = 'index.php?page=' + encodeURIComponent(page) + '&action=reset_increment&value=' + encodeURIComponent(String(normalized));
            });
        });
    })();
    </script>
</div>