<?php
/**
 * API: Liste des salariés
 * GET /apipcc/salaries.php?fonction=FONCTION&sexe=SEXE&etat=ETAT
 * Filtres optionnels: fonction (CHAUFFEUR AUTOCAR, LAVEUR, etc.), sexe, etat
 */
require_once __DIR__ . '/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendError('Méthode non autorisée', 405);
}

$conn = getConnection(DB_NAME_RH);

$fonction = $_GET['fonction'] ?? '';
$sexe = $_GET['sexe'] ?? '';
$etat = $_GET['etat'] ?? 'Actif';

$where = ["EtatSal = ?"];
$params = [$etat];
$types = "s";

if (!empty($fonction)) {
    $where[] = "Fonction IN (" . implode(',', array_fill(0, count(explode(',', $fonction)), '?')) . ")";
    $fonctions = explode(',', $fonction);
    foreach ($fonctions as $f) {
        $params[] = trim($f);
        $types .= "s";
    }
}

if (!empty($sexe)) {
    $where[] = "Sexe = ?";
    $params[] = $sexe;
    $types .= "s";
}

$sql = "SELECT NomPrenom, NomPrenomAR, Fonction, Sexe FROM salaries WHERE " . implode(' AND ', $where) . " ORDER BY NomPrenom";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

$salaries = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $salaries[] = $row;
    }
}

sendSuccess($salaries, 'Liste des salariés récupérée');
$stmt->close();
$conn->close();