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

// --- Connexion centralisée ---
require_once __DIR__.'/db_connect.php'; // $pdo disponible

// --- PARAMETRES ---
$agence = isset($_GET['agence']) ? trim($_GET['agence']) : '';
$depot  = isset($_GET['depot'])  ? trim($_GET['depot'])  : '';
$datedebut  = isset($_GET['datedebut'])  ? trim($_GET['datedebut'])  : '';
$datefin = isset($_GET['datefin'])  ? trim($_GET['datefin'])  : '';
$arcode =  isset($_GET['arcode'])  ? trim($_GET['arcode'])  : '';
$critere="";
$arcodebarre = $arcode;

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

try {
    
    // Vérifier agence.
    
    $stmtAg = $pdo->prepare("SELECT agcode, agdesignation FROM tblagences WHERE agcode = ?");
    $stmtAg->execute([$agence]);
    $infoAg = $stmtAg->fetch(PDO::FETCH_ASSOC);
    if (!$infoAg) {
        echo json_encode(['success'=>false,'message'=>'agence inconnue']);
        exit;
    }

    // --- Construction dynamique de la requête et des paramètres ---
    $conditions = [];
    $params = [];

    if ($datedebut !== '' && $datefin !== '') {
        $conditions[] = "( (LEFT(arDateCreation, 10) BETWEEN :datedebut1 AND :datefin1) 
                            or (LEFT(arDateModification, 10) BETWEEN :datedebut2 AND :datefin2)
                            or (LEFT(arDtMAJPrix, 10) BETWEEN :datedebut3 AND :datefin3) )";
        $params[':datedebut1'] = $datedebut;
        $params[':datefin1']   = $datefin;
        
        $params[':datedebut2'] = $datedebut;
        $params[':datefin2']   = $datefin;
        
        $params[':datedebut3'] = $datedebut;
        $params[':datefin3']   = $datefin;

    }

    if ($arcode !== '') {
        $conditions [] = " ( arcode = :arcode or arcodebarre= :arcodebarre)";
        $params[':arcode'] = $arcode;
        $params[':arcodebarre'] = $arcodebarre;
        
    }
    
   $sql = "SELECT 
                arcode,ardesignation,
                arPrixRevient AS prixrevient,
                arprixachTTC AS prixachatttc,
                arCodeBarre as arCodeBarr,arRefOrigine,arDescription,
                tblsousfamilles.facode,fadesignation,tblarticles.sfcode,sfdesignation, 
                arsuiviStock as arsvstock,arCatProduit,arDetail,
                arDemiGros as arDemisGros,arGros,arPrixRevient as arRevient,arSupGros,
                artaxe1,artaxe2,artaxe3,
                artaxe4,arTaxeAchat1,arTaxeAchat2,arTaxeAchat3,
                arTaxeAchat4,arCtgTarif1,arCtgTarif2,arCtgTarif3,
                arCtgTarif4,arCtgTarif5,arNumCptGen,arNumCptGenAchat,
                arNumCptAnal,arCodeAbreg,arEnSommeil,
                arDetailCoef,arDemiGrosCoef,arGrosCoef,arSupGrosCoef,
                arPrixAchat as arprixachatHT,arprixachTTC as arprixachatTTC,
                arprixvte,arRevientCoef,
                arprixVteCoef,armodefiscvte,armodefiscAchat,artauxremise,
                artauxremiseAchat,arEnPromo,ardtdebutpromo,ardtfinpromo,
                arprixpromomin,arprixpromomax,arFournisseurPrincipal,
                arPrixFourPrincipal,arCoutStokageArticle,arArticleHorsCA,
                arDelaiLivraison as arDelailivraisonjour,ardureegarantiemois,arFactNegative,
                arconditionnementstock,arFactStockNul,arEmplacement,
		        arprixvente AS prixvente,arDateCreation,arRespCreation,
                arDateModification,arRespModification,
                arRespMAJPrix,arDtMAJPrix 
            FROM tblarticles
            left outer join tblsousfamilles on tblsousfamilles.sfcode=tblarticles.sfcode
            left outer join tblfamilles on tblfamilles.facode=tblsousfamilles.facode";

    // Injection des conditions si elles existent
    if (count($conditions) > 0) {
        $sql .= " WHERE " . implode(" AND ", $conditions);
    }
    $sql .= " order by ardesignation";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params); // On passe uniquement les paramètres peuplés

    $articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode([
        'success' => true,
        'date' => date('Y-m-d H:i:s'),
        'count' => count($articles),
        'articles' => $articles
    ], JSON_UNESCAPED_UNICODE);

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