<?php
/**
 * Fichier  : api/delivery_note.php
 * Auteur   : KREMER Régis
 * Version  : 3.0.0
 * Date     : 2026-03-09
 * Description : Génération bon de livraison HTML professionnel (impression A4)
 *
 * Modes :
 *   ?movementId=XXX           -> BL individuel
 *   ?site=XXX&date=YYYY-MM-DD -> BL groupé chantier
 */
require_once dirname(__DIR__).'/config.php';
startSession(); requireAuth();

$movementId = $_GET['movementId'] ?? null;
$site       = $_GET['site']       ?? null;
$date       = $_GET['date']       ?? null;

$allMvs   = loadData('movements');
$prods    = loadData('products');
$whs      = loadData('warehouses');
$settings = loadData('settings');
$company  = ($settings[0] ?? [])['companyName'] ?? 'MageStock';
$user     = currentUser();
$selectedMvs = [];

if ($movementId) {
    foreach ($allMvs as $m) {
        if ((string)($m['id'] ?? '') === (string)$movementId) { $selectedMvs[] = $m; break; }
    }
    if (!$selectedMvs) { http_response_code(404); echo 'Mouvement introuvable.'; exit; }
} elseif ($site && $date) {
    foreach ($allMvs as $m) {
        $mvDate = substr($m['date'] ?? '', 0, 10);
        if (($m['site'] ?? '') === $site && $mvDate === $date && in_array($m['type'] ?? '', ['remove','transfer'])) {
            $selectedMvs[] = $m;
        }
    }
    if (!$selectedMvs) { http_response_code(404); echo 'Aucun mouvement trouvé.'; exit; }
} else {
    http_response_code(400); echo 'movementId ou (site + date) requis.'; exit;
}

$firstMv  = $selectedMvs[0];
$refDate  = date('d/m/Y \à H\hi', strtotime($firstMv['date'] ?? 'now'));
$refSite  = $firstMv['site'] ?? '';
$refOp    = $firstMv['operator'] ?? $firstMv['user'] ?? '';
$refWh    = findById($whs, $firstMv['warehouseId'] ?? 0);
$whName   = $refWh['name'] ?? '—';
$isGrouped = count($selectedMvs) > 1 || ($site && $date);
$blNum     = $isGrouped ? 'BL-' . strtoupper(substr(md5($site . $date), 0, 8)) : 'BL-' . ($firstMv['id'] ?? '0');
$typeLabels = ['add'=>'Ajout','remove'=>'Sortie','transfer'=>'Transfert','entry'=>'Entrée','inventory'=>'Inventaire'];
$e = function($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); };

$rows = '';
$totalQty = 0;
foreach ($selectedMvs as $idx => $mv) {
    $p = findById($prods, $mv['productId'] ?? 0);
    $w = findById($whs, $mv['warehouseId'] ?? 0);
    $dst = isset($mv['transferTo']) ? findById($whs, $mv['transferTo']) : null;
    $qty = (float)($mv['quantity'] ?? 0);
    $unit = $mv['unit'] ?? 'pce';
    $baseQty = isset($mv['baseQuantity']) ? (float)$mv['baseQuantity'] : $qty;
    $totalQty += $baseQty;
    $lotInfo = '';
    if (!empty($mv['lotNumber'])) $lotInfo .= 'Lot: ' . $e($mv['lotNumber']);
    if (!empty($mv['expiryDate'])) $lotInfo .= ($lotInfo ? ' · ' : '') . 'DLUO: ' . $e($mv['expiryDate']);
    $destination = $dst ? '→ ' . $e($dst['name'] ?? '') : '';

    $rows .= '<tr>';
    $rows .= '<td class="tc">' . ($idx + 1) . '</td>';
    $rows .= '<td><strong>' . $e($p['name'] ?? '?') . '</strong>';
    if (!empty($p['sku'])) $rows .= '<br><span class="sm">' . $e($p['sku']) . '</span>';
    $rows .= '</td>';
    $rows .= '<td>' . $e($w['name'] ?? '?') . ($destination ? '<br><span class="sm blue">' . $destination . '</span>' : '') . '</td>';
    $rows .= '<td class="tc">' . $e($typeLabels[$mv['type'] ?? ''] ?? $mv['type'] ?? '?') . '</td>';
    $rows .= '<td class="tr bold big">' . $qty . ' ' . $e($unit) . '</td>';
    $rows .= '<td class="sm muted">' . ($lotInfo ?: '—') . '</td>';
    $rows .= '<td class="sm muted">' . $e($mv['reason'] ?? $mv['note'] ?? '—') . '</td>';
    $rows .= '</tr>';
}

$logoPath = dirname(__DIR__) . '/assets/img/sm.png';
$logoUrl  = '../assets/img/sm.png';
$hasLogo  = file_exists($logoPath);

header('Content-Type: text/html; charset=UTF-8');
?><!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title><?=$isGrouped?'BL Chantier — '.$e($refSite):'Bon de livraison — '.$e($blNum)?></title>
<style>
@page{size:A4;margin:14mm 16mm}
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Segoe UI',Arial,sans-serif;color:#1e293b;font-size:13px;line-height:1.5;background:#fff}
.page{max-width:780px;margin:0 auto;padding:20px}
.sm{font-size:11px;color:#64748b}.blue{color:#3b82f6}.muted{color:#64748b}.tc{text-align:center}.tr{text-align:right}.bold{font-weight:700}.big{font-size:14px}

/* Header */
.hdr{display:flex;justify-content:space-between;align-items:flex-start;padding-bottom:14px;border-bottom:3px solid #1e40af;margin-bottom:18px}
.brand{display:flex;align-items:center;gap:12px}
.logo{width:52px;height:52px;border-radius:12px;object-fit:contain}
.logo-ph{width:52px;height:52px;border-radius:12px;background:linear-gradient(135deg,#3b82f6,#22c55e);display:flex;align-items:center;justify-content:center;color:#fff;font-size:20px;font-weight:800}
.co{font-size:18px;font-weight:800;color:#1e40af}
.co-sub{font-size:11px;color:#64748b;margin-top:1px}
.ref{text-align:right}
.ref-num{font-size:15px;font-weight:800;color:#1e40af;font-family:monospace;letter-spacing:1px}
.ref-date{font-size:12px;color:#64748b;margin-top:3px}

/* Title */
.tbar{background:#1e40af;color:#fff;padding:9px 16px;border-radius:8px;margin-bottom:18px;display:flex;justify-content:space-between;align-items:center}
.tbar h1{font-size:15px;font-weight:700;margin:0;letter-spacing:.4px}
.tbar .cnt{font-size:12px;opacity:.85}

/* Info */
.info{display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin-bottom:18px}
.info-b{background:#f8fafc;border:1px solid #e2e8f0;border-radius:7px;padding:10px 12px}
.info-l{font-size:10px;text-transform:uppercase;letter-spacing:.5px;color:#64748b;font-weight:700;margin-bottom:3px}
.info-v{font-size:13px;font-weight:600;color:#0f172a}

/* Table */
.tbl{width:100%;border-collapse:collapse;margin-bottom:14px}
.tbl thead th{background:#f1f5f9;padding:8px 10px;text-align:left;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.4px;color:#475569;border-bottom:2px solid #cbd5e1}
.tbl tbody td{padding:9px 10px;border-bottom:1px solid #e2e8f0;vertical-align:top}
.tbl tbody tr:nth-child(even) td{background:#fafbfc}

/* Summary */
.sum{display:flex;justify-content:flex-end;gap:20px;padding:10px 0;border-top:2px solid #1e40af;margin-bottom:20px}
.sum-i{text-align:right}
.sum-l{font-size:10px;color:#64748b;text-transform:uppercase;letter-spacing:.4px}
.sum-v{font-size:17px;font-weight:800;color:#1e40af}

/* Sign */
.signs{display:grid;grid-template-columns:1fr 1fr;gap:36px;margin-top:28px;page-break-inside:avoid}
.sign-l{font-size:10px;text-transform:uppercase;letter-spacing:.4px;color:#64748b;font-weight:700;margin-bottom:5px}
.sign-n{font-size:13px;font-weight:600;color:#0f172a;margin-bottom:26px}
.sign-line{border-top:1px solid #94a3b8;padding-top:5px;font-size:10px;color:#94a3b8}

/* Footer */
.foot{margin-top:20px;padding-top:10px;border-top:1px solid #e2e8f0;text-align:center;font-size:10px;color:#94a3b8}

/* Print bar */
.pbar{position:sticky;top:0;z-index:10;background:#1e293b;padding:8px 16px;display:flex;justify-content:center;gap:10px}
.pbtn{padding:7px 20px;border:none;border-radius:7px;font-size:13px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:6px}
.pbtn-p{background:#3b82f6;color:#fff}.pbtn-p:hover{background:#2563eb}
.pbtn-s{background:#334155;color:#e2e8f0}.pbtn-s:hover{background:#475569}
@media print{.pbar{display:none!important}body{-webkit-print-color-adjust:exact;print-color-adjust:exact}.page{padding:0}}
@media(max-width:640px){.info{grid-template-columns:1fr}.hdr{flex-direction:column;gap:10px}.ref{text-align:left}}
</style>
</head>
<body>
<div class="pbar">
    <button class="pbtn pbtn-p" onclick="window.print()">🖨 Imprimer</button>
    <button class="pbtn pbtn-s" onclick="window.close()">Fermer</button>
</div>
<div class="page">
    <div class="hdr">
        <div class="brand">
            <?php if($hasLogo):?><img src="<?=$e($logoUrl)?>" class="logo" alt="Logo"><?php else:?><div class="logo-ph">M</div><?php endif;?>
            <div><div class="co"><?=$e($company)?></div><div class="co-sub">Gestion de stock · MageStock</div></div>
        </div>
        <div class="ref"><div class="ref-num"><?=$e($blNum)?></div><div class="ref-date"><?=$refDate?></div></div>
    </div>
    <div class="tbar">
        <h1><?=$isGrouped?'BON DE LIVRAISON — CHANTIER':'BON DE LIVRAISON'?></h1>
        <span class="cnt"><?=count($selectedMvs)?> article<?=count($selectedMvs)>1?'s':''?></span>
    </div>
    <div class="info">
        <div class="info-b"><div class="info-l">Magasin</div><div class="info-v"><?=$e($whName)?></div></div>
        <?php if($refSite):?><div class="info-b"><div class="info-l">Chantier / Destination</div><div class="info-v"><?=$e($refSite)?></div></div><?php endif;?>
        <div class="info-b"><div class="info-l">Opérateur</div><div class="info-v"><?=$e($refOp?:($user['name']??'—'))?></div></div>
    </div>
    <table class="tbl">
        <thead><tr><th style="width:30px" class="tc">#</th><th>Désignation</th><th>Magasin</th><th class="tc">Type</th><th class="tr">Quantité</th><th>Lot / DLUO</th><th>Motif / Note</th></tr></thead>
        <tbody><?=$rows?></tbody>
    </table>
    <div class="sum">
        <div class="sum-i"><div class="sum-l">Lignes</div><div class="sum-v"><?=count($selectedMvs)?></div></div>
        <div class="sum-i"><div class="sum-l">Total unités</div><div class="sum-v"><?=$totalQty?></div></div>
    </div>
    <div class="signs">
        <div><div class="sign-l">Opérateur / Livreur</div><div class="sign-n"><?=$e($refOp?:'—')?></div><div class="sign-line">Signature</div></div>
        <div><div class="sign-l">Réceptionnaire</div><div class="sign-n">&nbsp;</div><div class="sign-line">Nom, date et signature</div></div>
    </div>
    <div class="foot">Document généré par MageStock · <?=$e($company)?> · <?=date('d/m/Y à H:i')?></div>
</div>
</body>
</html>
