<?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'])  : '';

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;
    }

    // Requête stock de tous les dépôts de l'agence
    $sql = "SELECT
                si.agcode,
                s.sicode,
                si.sidesignation ,
                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.arPrixRevient AS prixrevient,
                a.arprixachTTC AS prixachatttc,
                a.arprixvente AS prixvente
            FROM tblstocks s
            INNER JOIN tblsites si ON si.sicode = s.sicode
            INNER JOIN tblarticles a ON a.arcode = s.arcode
            WHERE si.agcode = :agence";

    $params = [':agence' => $agence];

    if ($depot !== '') {
        $sql .= " AND s.sicode = :depot";
        $params[':depot'] = $depot;
    }

    $sql .= " GROUP BY s.sicode, s.arcode
              HAVING stock <> 0
              ORDER BY s.sicode, a.ardesignation";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'agence' => $infoAg['agcode'],
        'agdesignation' => $infoAg['agdesignation'],
        'ip' => $_SERVER['SERVER_ADDR'] ?? '',
        'hostname' => gethostname(),
        'parametres' => ['agence'=>$agence, 'depot'=>$depot ?: 'TOUS'],
        'date' => date('Y-m-d H:i:s'),
        'count' => count($rows),
        'stocks' => $rows
    ], JSON_UNESCAPED_UNICODE);

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