<?php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Connexion DB
$conn = new mysqli("localhost", "destinat_archive", "@rchivekompa1", "destinat_archive");
if ($conn->connect_error) {
    echo json_encode(["error" => "Connexion échouée : " . $conn->connect_error]);
    exit;
}

// Paramètres
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$query = isset($_GET['query']) ? trim($_GET['query']) : '';
$perPage = 104;
$offset = ($page - 1) * $perPage;

$where = "1";
$params = [];
$types = "";

if ($query !== "") {
    $where .= " AND LOWER(name) LIKE ?";
    $params[] = '%' . strtolower($query) . '%';
    $types .= "s";
}

// Compter total
$countSql = "SELECT COUNT(*) FROM artists WHERE $where";
$countStmt = $conn->prepare($countSql);
if (!empty($params)) {
    $countStmt->bind_param($types, ...$params);
}
$countStmt->execute();
$countStmt->bind_result($total);
$countStmt->fetch();
$countStmt->close();

$totalPages = ceil($total / $perPage);

// Récupérer les données
$sql = "SELECT name, image_url FROM artists WHERE $where ORDER BY name ASC LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);

if (!empty($params)) {
    $types .= "ii";
    $params[] = $perPage;
    $params[] = $offset;
    $stmt->bind_param($types, ...$params);
} else {
    $stmt->bind_param("ii", $perPage, $offset);
}

$stmt->execute();
$stmt->bind_result($name, $image);

$results = [];
while ($stmt->fetch()) {
    // Générer slug
    $slug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $name));
    $firstLetter = strtoupper(substr($slug, 0, 1));

    $results[] = [
        "name" => $name,
        "image" => $image ?: "https://via.placeholder.com/250x250?text=" . urlencode($name),
        "link"  => "$firstLetter/$slug.php"
    ];
}
$stmt->close();
$conn->close();

// Résultat JSON
echo json_encode([
    "results" => $results,
    "totalPages" => $totalPages
]);
?>



