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

require_once __DIR__.'/db_connect.php';

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

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

try {
    $sql = "SELECT
                a.arcode,
                a.ardesignation,
                COALESCE(SUM(s.stDisponible),0) AS stockdisponible,
                COALESCE(SUM(s.stReserve),0) AS stockreserve,
                COALESCE(SUM(s.stReel),0) AS stock,
                a.arDetail AS prixdetail,
                a.arDemiGros AS prixdemigros,
                a.arGros AS prixgros,
                a.arPrixRevient AS prixrevient,
                a.arSupGros AS prixsupergros,
                a.arprixachTTC AS prixachatttc,
                a.arprixvente AS prixvente,
                :depot_aff AS depot_demande,
                :agence_aff AS agence_demandee
            FROM tblarticles a
            LEFT JOIN tblstocks s ON s.arcode = a.arcode";

    // filtre dépôt
    if ($depot !== '') {
        $sql .= " AND s.sicode = :depot_filtre";
    }

    $sql .= " WHERE (a.arcode = :code1 OR a.arcodebarre = :code2)
              GROUP BY a.arcode
              LIMIT 1";

    $stmt = $pdo->prepare($sql);
    
    // bind chaque marqueur UNE fois
    $stmt->bindValue(':depot_aff', $depot);
    $stmt->bindValue(':agence_aff', $agence);
    $stmt->bindValue(':code1', $code);
    $stmt->bindValue(':code2', $code);
    
    if ($depot !== '') {
        $stmt->bindValue(':depot_filtre', $depot);
    }

    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        echo json_encode([
            'success' => true,
            'agence' => gethostname(),
            'ip' => $_SERVER['SERVER_ADDR'] ?? '',
            'parametres' => ['code'=>$code,'depot'=>$depot,'agence'=>$agence],
            'data' => $row
        ], JSON_UNESCAPED_UNICODE);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Article introuvable',
            'parametres' => ['code'=>$code,'depot'=>$depot,'agence'=>$agence]
        ]);
    }

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