<?php
$db_host = 'localhost';
$db_name = 'transubd_PointageBus';
$db_user = 'transubd_transub_user';
$db_pass = 'Tr@nsub2@24';

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 100;
$offset = ($page - 1) * $limit;

$conn = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);

// Compter le total
$countStmt = $conn->query("SELECT COUNT(*) as total FROM buses WHERE type = 'Bus' AND actif = 1");
$total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];

$sql = "SELECT b.id, b.matricule, l.name as ligne_name, o.name as operator_name
FROM buses b
LEFT JOIN lignes l ON b.id_ligne = l.ligne_code
LEFT JOIN operators o ON b.id_operateur = o.id
WHERE b.type = 'Bus' AND b.actif = 1
ORDER BY b.matricule ASC
LIMIT $limit OFFSET $offset";

$stmt = $conn->query($sql);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

header('Content-Type: application/json');
echo json_encode([
    'data' => $rows,
    'page' => $page,
    'limit' => $limit,
    'total' => (int)$total,
    'totalPages' => ceil($total / $limit)
]);
