<?php
function getConnection()
{
    static $conn = null;

    if ($conn === null) {
        $host = getenv('DB_HOST') ?: 'https://dwarves.iut-fbleau.fr';
        $login = getenv('DB_USER') ?: getenv('USER') ?: getenv('USERNAME') ?: 'root';
        $password = getenv('DB_PASSWORD') ?: $login;
        $database = getenv('DB_NAME') ?: $login;
        $conn = mysqli_connect($host, $login, $password, $database);

        if ($conn !== false) {
            mysqli_set_charset($conn, 'utf8mb4');
        }
    }

    return $conn;
}

function getFilms($page = 1, $perPage = 10)
{
    $conn = getConnection();
    if ($conn === false) {
        return [
            'films' => [],
            'total' => 0,
            'error' => 'Connexion MySQL impossible.',
        ];
    }

    $page = max(1, (int) $page);
    $perPage = max(1, (int) $perPage);
    $offset = ($page - 1) * $perPage;

    $sql = "SELECT SQL_CALC_FOUND_ROWS
                F.idFilm,
                F.titre,
                F.annee,
                G.code AS genre,
                A.prenom,
                A.nom
            FROM Film AS F
            INNER JOIN Artiste AS A ON F.idMes = A.idArtiste
            INNER JOIN Genre AS G ON F.genre = G.code
            ORDER BY F.titre ASC
            LIMIT {$offset}, {$perPage}";

    $result = mysqli_query($conn, $sql);
    if ($result === false) {
        return [
            'films' => [],
            'total' => 0,
            'error' => 'Exécution de la requête impossible.',
        ];
    }

    $films = mysqli_fetch_all($result, MYSQLI_ASSOC);

    $totalResult = mysqli_query($conn, 'SELECT FOUND_ROWS() AS total');
    $totalRow = $totalResult ? mysqli_fetch_assoc($totalResult) : ['total' => 0];
    $total = isset($totalRow['total']) ? (int) $totalRow['total'] : 0;

    return [
        'films' => $films,
        'total' => $total,
        'error' => null,
    ];
}
