<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

require_once __DIR__.'/db_connect.php';

$agence = trim($_GET['agence'] ?? '');
$depot = trim($_GET['depot'] ?? '');
$agencedest = trim($_GET['agencedest'] ?? '');
$dstnum  = trim($_GET['dstnum'] ?? '');

if ($agence === '') {
    echo json_encode(['success'=>false,'message'=>'agence manquante']);
    exit;
}

$condition =" where d.tdcode IN ('0213','0214') 
                AND d.dstEtat <> 5 
                AND (d.agcodedemande =:agdemande OR d.agcodeoffre =:agoffre)";

$params = [
    ':agdemande' => $agencedest,
    ':agoffre'   => $agencedest
];

if ($agence !== '') { 
    $condition .=" and d.agcode=:agence";
    $params[':agence'] = $agence;
}

if ($dstnum!== ''){
   $condition .= " and d.dstnum=:dstnum"; 
   $params[':dstnum'] = $dstnum;
}else{
  $condition .= " and IFNULL(d.dst_sync_ack,0) = 0";
}

$condition .= " ORDER BY d.dstDtEnreg DESC";

try {

    $sql = "SELECT
        d.dstNum, d.dstDtEnreg, d.dstMtHT,d.dstMtTTC, d.agcodeoffre, d.agcodedemande,
        d.tdcode,d.sicode,d.sicodedest, d.dstEtat,d.dstRefManuel,
        d.cmdNum,d.dstDelaiRegle,d.dstDtLivraison,d.rsCode,d.dstModeFiscal,
        d.dstDateLogin,d.dstUserLogin,
        a.arCode, ar.arDesignation, a.ardstQte, a.ardstPUTTC,
        a.ardstMtNAP, a.condCode,d.ctnum,
        a.ardstsensmvt,a.ardstStTheo,a.ardstStPhys,
        a.ardstprixrevient,a.ardstPUHTBrut,a.ardstPUHTNetCommercial,
        a.ardstPuHTNetFinancier,a.ardstPUTTC,a.ardstPUNAP, 
        a.ardstMtTTC,a.ardstMtHTBrut,a.ardstMtHTNetCommercial,
        a.ardstMtHTNetFinancier,a.ardstVisibleImpresion,
        a.ardstDateLogin,a.ardstUserLogin
    FROM tbldocstocks d
    INNER JOIN tblardocstocks a ON a.dstNum = d.dstNum
    LEFT JOIN tblarticles ar ON ar.arCode = a.arCode"; 
   
    $sql .= $condition ;
    $stmt = $pdo->prepare($sql);
    // 4. Les variables externes sont liées de manière sécurisée ici
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $docs = [];

    foreach ($rows as $r) {

        $num = $r['dstNum'];

        if (!isset($docs[$num])) {

            $docs[$num]['entete'] = [
                'dstNum' => $r['dstNum'],
                'dstDtEnreg' => $r['dstDtEnreg'],
                'dstMtTTC' => $r['dstMtTTC'],
                'agcodeoffre' => $r['agcodeoffre'],
                'agcodedemande' => $r['agcodedemande'],
                'sicode' => $r['sicode'],
                'ctnum' => $r['ctnum'],
                'dstRefManuel' => $r['dstRefManuel'],
		        'tdcode' => $r['tdcode'],
                'dstEtat' => $r['dstEtat'],
                'cmdNum' => $r['cmdNum'],
                'dstDelaiRegle' => $r['dstDelaiRegle'],
                'dstDtLivraison' => $r['dstDtLivraison'],
                'rsCode' => $r['rsCode'],
                'dstModeFiscal' => $r['dstModeFiscal'],
                'dstDateLogin' => $r['dstDateLogin'],
                'dstUserLogin' => $r['dstUserLogin'],
                'sicodedest' => $r['sicodedest']
            ];
            $docs[$num]['lignes'] = [];
        }
        $docs[$num]['lignes'][] = [
            'arCode' => $r['arCode'],
            'arDesignation' => $r['arDesignation'],
            'ardstQte' => $r['ardstQte'],
            'condCode' => $r['condCode'],
            'ardstMtNAP' => $r['ardstMtNAP'],
            'ardstsensmvt' => $r['ardstsensmvt'],
            'ardstStTheo' => $r['ardstStTheo'],
            'ardstStPhys' => $r['ardstStPhys'],
            'ardstprixrevient' => $r['ardstprixrevient'],
            'ardstPUHTBrut' => $r['ardstPUHTBrut'],
            'ardstPUHTNetCommercial' => $r['ardstPUHTNetCommercial'],
            'ardstPuHTNetFinancier' => $r['ardstPuHTNetFinancier'],
            'ardstPUNAP' => $r['ardstPUNAP'],
            'ardstMtTTC' => $r['ardstMtTTC'],
            'ardstMtHTBrut' => $r['ardstMtHTBrut'],
            'ardstMtHTNetCommercial' => $r['ardstMtHTNetCommercial'],
            'ardstMtHTNetFinancier' => $r['ardstMtHTNetFinancier'],
            'ardstVisibleImpresion' => $r['ardstVisibleImpresion'],
            'ardstDateLogin' => $r['ardstDateLogin'],
            'ardstUserLogin' => $r['ardstUserLogin'],
            'ardstPUTTC' => $r['ardstPUTTC']
        ];
    }

    echo json_encode([
        'success' => true,
        'count' => count($docs),
        'documents' => array_values($docs)
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}