<?php
/**
 * Fichier  : views/movements.php
 * Auteur   : KREMER Régis
 * Version  : 2.6.109
 * Date     : 2026-07-22
 * Description : Vue — Mouvements de stock — filtres, sélection BL et impressions métier
 *
 * Changelog :
 *   v2.6.79 (2026-07-17) — MOVEMENTS TERRAIN FLOW3 : actions terrain, filtres en tiroir et cartes mobiles natives.
 *   v2.6.23 (2026-07-08) — Impression mouvements : bouton dédié, export imprimable A4, cohérence BL.
 *   v2.6.21 (2026-07-08) — UX sélection BL : colonne compacte, barre d’action claire, mobile sans texte empilé.
 *   v2.6.4 (2026-07-08) — Parcours terrain mobile/tablette : filtres, actions et tableau prêts pour rendu carte.
 *   v2.3.16 (2026-06-02) — BL simple : modale large, lisible, cohérente thème clair, champs accessibles.
 *   v2.3.14 (2026-06-02) — BL simplifié : sélection de sorties → modale unique → impression directe.
 *   v2.3.11 (2026-06-02) — Sélection multiple de sorties et barre de création de BL groupé.
 *   v2.3.15 (2026-03-01) — Refonte filtres : Magasin d'abord, puis Produit filtré,
 *                           filtres avancés branchés (opérateur, site, BL, fournisseur)
 */
?>
<div class="movements" id="pgMovements">

    <?php if(hasAdminAccess(currentUser())): ?>
    <section class="mv-terrain-launch" aria-label="Actions terrain sur le stock">
        <button type="button" class="btn btn-primary mv-terrain-launch__primary" id="btnMvMobileCreate">
            <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>
            <span>Enregistrer un mouvement</span>
        </button>
        <button type="button" class="btn btn-secondary mv-terrain-launch__scan" id="btnMvMobileScan">
            <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 7V5a2 2 0 012-2h2M17 3h2a2 2 0 012 2v2M21 17v2a2 2 0 01-2 2h-2M7 21H5a2 2 0 01-2-2v-2M7 12h10"/></svg>
            <span>Scanner</span>
        </button>
    </section>
    <?php endif; ?>

    <section class="mv-mobile-filterbar" aria-label="Recherche et filtres des mouvements">
        <label class="mv-mobile-search" for="mvMobileSearch">
            <svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
            <span class="ms-sr-only">Rechercher un mouvement</span>
            <input type="search" id="mvMobileSearch" inputmode="search" enterkeyhint="search" placeholder="Produit, SKU, opérateur, chantier…" autocomplete="off">
        </label>
        <button type="button" class="btn btn-secondary mv-mobile-filterbar__button" id="btnMvMobileFilters" aria-haspopup="dialog">
            <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 6h16M7 12h10M10 18h4"/></svg>
            <span id="mvMobileFilterLabel">Filtres</span>
            <span class="mv-filter-count" id="mvMobileFilterCount" hidden>0</span>
        </button>
    </section>

    <!-- ═══════════════════════════════════════════════════════════
         BARRE DE FILTRES PRINCIPALE
         Ordre logique : Magasin → Produit (filtré) → Type → Dates
         ═══════════════════════════════════════════════════════════ -->
    <div class="filters-bar mv-desktop-filters">

        <!-- Recherche texte libre -->
        <div class="filters-section">
            <div class="search-box">
                <svg class="search-box-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
                </svg>
                <input type="text" id="mvSearch" placeholder="Rechercher SKU, opérateur, note…">
            </div>
        </div>

        <div class="filters-divider"></div>

        <!-- ① Magasin — en premier, pilote le filtre Produit -->
        <div class="filters-section">
            <select id="mvWhFilter" class="form-select" style="min-width:160px" title="Filtrer par magasin">
                <option value="">Tous les magasins</option>
            </select>
        </div>

        <div class="filters-divider"></div>

        <!-- ② Produit — filtré selon le magasin sélectionné -->
        <div class="filters-section">
            <select id="mvProdFilter" class="form-select" style="min-width:200px" title="Filtrer par produit (choisir un magasin d'abord)">
                <option value="">Tous les produits</option>
            </select>
        </div>

        <div class="filters-divider"></div>

        <!-- Type de mouvement -->
        <div class="filters-section">
            <select id="mvTypeFilter" class="form-select" style="min-width:140px">
                <option value="">Tous les types</option>
                <option value="entry">📥 Entrée</option>
                <option value="add">➕ Ajout</option>
                <option value="remove">➖ Sortie</option>
                <option value="transfer">↔️ Transfert</option>
                <option value="inventory">📋 Inventaire</option>
            </select>
        </div>

        <div class="filters-divider"></div>

        <!-- Dates -->
        <div class="filters-section">
            <input type="date" id="mvDateFrom" class="form-input" style="width:145px" title="Date début">
            <span class="text-muted">→</span>
            <input type="date" id="mvDateTo" class="form-input" style="width:145px" title="Date fin">
        </div>

        <!-- Boutons droite -->
        <div class="filters-section ml-auto">
            <button class="btn btn-secondary btn-sm" id="btnMvAdvanced" title="Filtres supplémentaires">
                <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="4" y1="21" x2="4" y2="14"/><line x1="4" y1="10" x2="4" y2="3"/>
                    <line x1="12" y1="21" x2="12" y2="12"/><line x1="12" y1="8" x2="12" y2="3"/>
                    <line x1="20" y1="21" x2="20" y2="16"/><line x1="20" y1="12" x2="20" y2="3"/>
                    <line x1="1" y1="14" x2="7" y2="14"/><line x1="9" y1="8" x2="15" y2="8"/><line x1="17" y1="16" x2="23" y2="16"/>
                </svg>
                Filtres +
            </button>
            <button class="btn btn-ghost btn-icon btn-sm" id="btnMvReset" title="Réinitialiser tous les filtres">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 102.13-9.36L1 10"/>
                </svg>
            </button>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════
         FILTRES AVANCÉS (masqués par défaut)
         ═══════════════════════════════════════════════════════════ -->
    <div class="card mb-4" id="mvAdvancedWrap" style="display:none">
        <div class="card-body">
            <div class="form-grid">
                <div class="form-group mb-0">
                    <label class="form-label">Opérateur</label>
                    <input type="text" class="form-input" id="mvOpFilter" placeholder="Nom de l'opérateur">
                </div>
                <div class="form-group mb-0">
                    <label class="form-label">Chantier / Site</label>
                    <input type="text" class="form-input" id="mvSiteFilter" placeholder="Nom du site">
                </div>
                <div class="form-group mb-0">
                    <label class="form-label">BL / Référence</label>
                    <input type="text" class="form-input" id="mvDeliveryFilter" placeholder="Numéro BL">
                </div>
                <div class="form-group mb-0">
                    <label class="form-label">Fournisseur</label>
                    <input type="text" class="form-input" id="mvSupplierFilter" placeholder="Nom fournisseur">
                </div>
            </div>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════
         BARRE D'ACTIONS + COMPTEUR
         ═══════════════════════════════════════════════════════════ -->
    <div class="flex items-center justify-between gap-4 mb-4 flex-wrap mv-desktop-actions-wrap">
        <span class="results-count" id="mvCount">0 mouvement(s)</span>

        <div class="flex gap-2 flex-wrap mv-actions-bar">
            <button class="btn btn-secondary" id="btnMvPrint" type="button" title="Imprimer les mouvements affichés">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="6 9 6 2 18 2 18 9"/>
                    <path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/>
                    <rect x="6" y="14" width="12" height="8"/>
                </svg>
                Imprimer
            </button>
            <?php if(hasAdminAccess(currentUser())): ?>
            <button class="btn btn-success" id="btnMvAdd">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>
                </svg>
                Ajout stock
            </button>
            <button class="btn btn-danger" id="btnMvRemove">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="5" y1="12" x2="19" y2="12"/>
                </svg>
                Sortie stock
            </button>
            <button class="btn btn-secondary" id="btnMvTransfer">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 014-4h14"/>
                    <polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 01-4 4H3"/>
                </svg>
                Transfert
            </button>
            <button class="btn btn-primary" id="btnMvEntry">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/>
                    <polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/>
                </svg>
                Entrée
            </button>
            <?php endif; ?>
        </div>
    </div>

    <div class="mv-delivery-bulk-bar" id="mvDeliveryBulkBar" hidden aria-live="polite">
        <div class="mv-delivery-bulk-main">
            <span class="mv-delivery-bulk-kicker">Bon de livraison groupé</span>
            <span class="mv-delivery-bulk-count" id="mvDeliveryBulkCount">0 sortie sélectionnée</span>
            <span class="mv-delivery-bulk-hint">Les lignes cochées seront regroupées dans un seul document imprimable.</span>
        </div>
        <div class="mv-delivery-bulk-actions">
            <button type="button" class="btn btn-secondary btn-sm" id="btnMvSelectPageBl">Tout cocher sur la page</button>
            <button type="button" class="btn btn-ghost btn-sm" id="btnMvClearGroupedBl">Vider</button>
            <button type="button" class="btn btn-primary" id="btnMvCreateGroupedBl">Créer le bon</button>
        </div>
    </div>


    <section class="mv-mobile-history" aria-labelledby="mvMobileHistoryTitle">
        <div class="mv-mobile-history__head">
            <div>
                <span class="mv-mobile-history__kicker">Historique terrain</span>
                <h2 id="mvMobileHistoryTitle">Mouvements récents</h2>
            </div>
            <span class="results-count" id="mvMobileCount">0 mouvement</span>
        </div>
        <div class="mv-mobile-list" id="mvMobileList" aria-live="polite" aria-busy="false"></div>
    </section>

    <!-- ═══════════════════════════════════════════════════════════
         TABLEAU DESKTOP
         ═══════════════════════════════════════════════════════════ -->
    <div class="card mv-desktop-table">
        <div class="table-container">
            <table class="data-table" id="mvTable">
                <thead>
                    <tr>
                        <th class="cell-center mv-select-head" title="Sélection bon de livraison">
                            <label class="mv-delivery-head-check" title="Cocher toutes les sorties visibles">
                                <input type="checkbox" id="mvDeliveryPageToggle" aria-label="Cocher toutes les sorties visibles pour le bon de livraison">
                                <span>BL</span>
                            </label>
                        </th>
                        <th data-sort="date">Date / Heure</th>
                        <th data-sort="type">Type</th>
                        <th data-sort="__product">Produit</th>
                        <th data-sort="__sku">SKU</th>
                        <th data-sort="__warehouse">Magasin</th>
                        <th class="cell-center" data-sort="quantity">Qté</th>
                        <th class="cell-center" data-sort="__stock">Stock</th>
                        <th data-sort="reason">Raison / Chantier</th>
                        <th data-sort="operator">Opérateur</th>
                        <th>Note</th>
                        <th>Document</th>
                        <th class="cell-center" title="BL = Bon de Livraison individuel | Site = BL groupé par chantier | BC = Bon de Commande">Pièce <svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2.5" style="vertical-align:-1px;opacity:.5"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg></th>
                    </tr>
                </thead>
                <tbody id="mvBody"></tbody>
            </table>
        </div>

        <!-- Pagination -->
        <div class="pagination-bar">
            <div class="pagination-info" id="mvPageInfo">Page 1 / 1</div>
            <div class="pagination-controls">
                <button class="pagination-btn" id="mvPrev" disabled>
                    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
                        <polyline points="15 18 9 12 15 6"/>
                    </svg>
                    Précédent
                </button>
                <button class="pagination-btn" id="mvNext">
                    Suivant
                    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
                        <polyline points="9 18 15 12 9 6"/>
                    </svg>
                </button>
                <select id="mvPageSize" class="form-select" style="width:auto">
                    <option value="20">20 / page</option>
                    <option value="50">50 / page</option>
                    <option value="100">100 / page</option>
                </select>
            </div>
        </div>
    </div>
</div>

<style>
/* v2.6.21 — Sélection BL compacte, lisible et sans texte empilé */
.mv-select-head,
.mv-select-cell{width:54px;min-width:54px;text-align:center;vertical-align:middle}
.mv-delivery-head-check{display:inline-flex;align-items:center;justify-content:center;gap:5px;min-width:44px;min-height:34px;padding:4px 7px;border:1px solid rgba(148,163,184,.35);border-radius:10px;background:#f8fafc;color:#334155;font-size:11px;font-weight:900;letter-spacing:.04em;cursor:pointer;user-select:none}
.mv-delivery-head-check input{width:16px;height:16px;margin:0;accent-color:#2563eb;cursor:pointer}
.mv-delivery-select{position:relative;display:inline-flex;align-items:center;justify-content:center;width:36px;height:36px;border:1px solid rgba(148,163,184,.38);border-radius:12px;background:#fff;cursor:pointer;transition:background .15s,border-color .15s,box-shadow .15s,transform .15s;user-select:none}
.mv-delivery-select input{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer;margin:0}
.mv-delivery-mark{display:block;width:17px;height:17px;border:2px solid #94a3b8;border-radius:5px;background:#fff;box-shadow:inset 0 0 0 2px #fff;transition:background .15s,border-color .15s,box-shadow .15s}
.mv-delivery-select:hover{background:#eff6ff;border-color:#60a5fa;box-shadow:0 6px 18px rgba(37,99,235,.12)}
.mv-delivery-select:has(input:focus-visible){outline:3px solid rgba(37,99,235,.22);outline-offset:2px}
.mv-delivery-select.is-checked{background:#dbeafe;border-color:#2563eb;box-shadow:0 8px 22px rgba(37,99,235,.18)}
.mv-delivery-select.is-checked .mv-delivery-mark{background:#2563eb;border-color:#2563eb;box-shadow:inset 0 0 0 4px #2563eb}
.mv-delivery-select.is-checked .mv-delivery-mark::after{content:'✓';display:block;color:#fff;font-size:13px;font-weight:900;line-height:13px;text-align:center;margin-top:-1px}
.mv-delivery-na{display:inline-flex;align-items:center;justify-content:center;width:36px;height:36px;color:#cbd5e1;font-weight:800;font-size:1rem}
#mvTable tr.is-delivery-selected>td{background:#eff6ff!important}
#mvTable tr.is-delivery-selected>td:first-child{box-shadow:inset 4px 0 0 #2563eb}
.mv-delivery-bulk-bar{position:sticky;bottom:12px;z-index:20;margin:0 0 16px;padding:12px 14px;border:1px solid rgba(37,99,235,.38);border-radius:16px;background:rgba(15,23,42,.97);box-shadow:0 16px 42px rgba(0,0,0,.28);display:flex;align-items:center;justify-content:space-between;gap:14px;color:#e5edf8;backdrop-filter:blur(14px)}
.mv-delivery-bulk-bar[hidden]{display:none!important}
.mv-delivery-bulk-main{display:flex;align-items:center;gap:10px;min-width:0;flex-wrap:wrap}
.mv-delivery-bulk-kicker{font-size:10px;line-height:1;text-transform:uppercase;letter-spacing:.08em;color:#93c5fd;font-weight:900}
.mv-delivery-bulk-count{display:inline-flex;align-items:center;padding:7px 11px;border-radius:999px;background:rgba(59,130,246,.18);color:#bfdbfe;font-weight:900;white-space:nowrap}
.mv-delivery-bulk-hint{color:#cbd5e1;font-size:.9rem}
.mv-delivery-bulk-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap;justify-content:flex-end}
.mv-bl-modal{display:flex;flex-direction:column;gap:14px}
.mv-bl-warning{padding:10px 12px;border:1px solid rgba(245,158,11,.45);border-radius:12px;background:rgba(245,158,11,.12);color:#fbbf24;font-weight:700}
.mv-bl-form-grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}
.mv-bl-form-wide{grid-column:1/-1}
.mv-bl-options{display:flex;gap:14px;flex-wrap:wrap;padding:10px 0;color:var(--text-muted,#94a3b8)}
.mv-bl-options label{display:inline-flex;align-items:center;gap:8px;min-height:34px}
.mv-bl-options input{width:18px;height:18px;accent-color:#3b82f6}
.mv-bl-preview{border:1px solid rgba(148,163,184,.24);border-radius:14px;overflow:hidden}
.mv-bl-preview-title{padding:10px 12px;font-weight:800;background:rgba(59,130,246,.12);color:#93c5fd}
.mv-bl-table{margin:0}.mv-bl-table td,.mv-bl-table th{vertical-align:top}
@media(max-width:760px){
  .mv-select-head,.mv-select-cell{width:auto;min-width:0}
  .mv-delivery-bulk-bar{left:8px;right:8px;bottom:8px;flex-direction:column;align-items:stretch;border-radius:16px}
  .mv-delivery-bulk-main{display:flex;flex-direction:column;align-items:flex-start;gap:6px}
  .mv-delivery-bulk-hint{margin-left:0}
  .mv-delivery-bulk-actions{justify-content:stretch}.mv-delivery-bulk-actions .btn{flex:1 1 auto;min-height:44px}
  .mv-bl-form-grid{grid-template-columns:1fr}
}

/* v2.3.16 — BL simple : modale large, lisible et cohérente thème clair */
#modalBox.mv-bl-wide-modal:has(.mv-bl-modal-v216){width:min(940px,calc(100vw - 32px));max-width:940px;background:#ffffff;color:#0f172a;border:1px solid #dbe5f2;border-radius:22px;box-shadow:0 28px 80px rgba(2,6,23,.34)}
#modalBox.mv-bl-wide-modal:has(.mv-bl-modal-v216) .modal-hdr{border-bottom:1px solid #e5edf7;background:#ffffff;color:#0f172a}
#modalBox.mv-bl-wide-modal:has(.mv-bl-modal-v216) .modal-hdr h3{color:#0f172a;font-weight:900}
#modalBox.mv-bl-wide-modal:has(.mv-bl-modal-v216) .modal-close{color:#64748b}
#modalBox.mv-bl-wide-modal:has(.mv-bl-modal-v216) .modal-body{padding:22px 26px;background:#ffffff;color:#0f172a;max-height:min(68vh,720px);overflow:auto}
#modalBox.mv-bl-wide-modal:has(.mv-bl-modal-v216) .modal-footer{background:#f8fafc;border-top:1px solid #e5edf7;padding:16px 26px}
.mv-bl-modal-v216{color:#0f172a;gap:18px}
.mv-bl-modal-v216 .mv-bl-help{margin:0;padding:12px 14px;border-radius:14px;background:#f1f5f9;color:#334155;line-height:1.55;font-weight:600}
.mv-bl-modal-v216 .form-group{gap:7px}
.mv-bl-modal-v216 .form-input,
.mv-bl-modal-v216 .form-select{min-height:48px;background:#ffffff!important;color:#0f172a!important;border:1px solid #cbd5e1!important;border-radius:12px;box-shadow:none;font-size:15px;font-weight:700}
.mv-bl-modal-v216 .form-input:focus,
.mv-bl-modal-v216 .form-select:focus{border-color:#2563eb!important;box-shadow:0 0 0 4px rgba(37,99,235,.16);outline:0}
.mv-bl-modal-v216 .form-input::placeholder{color:#64748b!important;font-weight:600}
.mv-bl-modal-v216 .form-label{color:#334155!important;font-weight:900;letter-spacing:.01em}
.mv-bl-warehouses{padding:14px;border:1px solid #dbeafe;background:#eff6ff;border-radius:16px;color:#1e3a8a}
.mv-bl-warehouses strong{display:block;margin-bottom:9px;color:#172554;font-weight:900}
.mv-bl-warehouses div{display:flex;gap:8px;flex-wrap:wrap}
.mv-bl-warehouses span{display:inline-flex;align-items:center;min-height:30px;padding:5px 10px;border-radius:999px;background:#ffffff;border:1px solid #bfdbfe;color:#1d4ed8;font-weight:800}
.mv-bl-preview{border:1px solid #dbe5f2;background:#ffffff;border-radius:16px;overflow:hidden}
.mv-bl-preview-title{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:12px 14px;background:#eff6ff;color:#1d4ed8;font-weight:900}
.mv-bl-preview-title small{color:#64748b;font-weight:700}
.mv-bl-table{margin:0;background:#ffffff;color:#0f172a}
.mv-bl-table th{background:#f8fafc!important;color:#475569!important;border-bottom:1px solid #dbe5f2;font-size:12px;letter-spacing:.06em;text-transform:uppercase}
.mv-bl-table td{background:#ffffff!important;color:#0f172a!important;border-bottom:1px solid #e5edf7;vertical-align:top}
.mv-bl-table .muted{color:#475569!important;font-weight:600}
.mv-bl-table .text-right{text-align:right;font-weight:900;white-space:nowrap}
@media(min-width:761px){.mv-bl-form-grid{grid-template-columns:minmax(220px,.85fr) minmax(260px,1fr) minmax(260px,1fr)}.mv-bl-form-wide{grid-column:auto}}
@media(max-width:760px){#modalBox.mv-bl-wide-modal:has(.mv-bl-modal-v216){width:100vw;max-width:100vw;height:100dvh;max-height:100dvh;border-radius:0}.mv-bl-form-grid{grid-template-columns:1fr}.mv-bl-modal-v216 .form-input,.mv-bl-modal-v216 .form-select{min-height:50px}.mv-bl-preview .table-container{max-height:300px;overflow:auto}.mv-bl-preview-title{align-items:flex-start;flex-direction:column}.mv-bl-table th:nth-child(2),.mv-bl-table td:nth-child(2){display:none}}

</style>

