<?php
/**
 * Test de diagnostic API
 * GET /apipcc/test.php
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: application/json; charset=utf-8');

$response = [
    'success' => true,
    'message' => 'API fonctionnelle',
    'php_version' => PHP_VERSION,
    'curl_enabled' => function_exists('curl_version') ? curl_version()['version'] : 'NON',
    'mysql_enabled' => function_exists('mysqli_connect') ? 'OUI' : 'NON',
];

// Test connexion base
try {
    $conn = new mysqli('localhost', 'transubd', 'Tr@nsub2@24', 'transubd_gestionparc');
    if ($conn->connect_error) {
        $response['db_connection'] = 'ECHEC: ' . $conn->connect_error;
    } else {
        $response['db_connection'] = 'SUCCÈS';
        
        // Test requête
$result = $conn->query("SELECT COUNT(*) as total FROM utilisateurs");
        if ($result) {
            $row = $result->fetch_assoc();
            $response['users_count'] = $row['total'];
            
$result2 = $conn->query("SELECT Nom FROM utilisateurs WHERE Etat = 'Actif' AND role = 'PCC' LIMIT 5");
            $users = [];
            if ($result2 && $result2->num_rows > 0) {
                while ($r = $result2->fetch_assoc()) {
                    $users[] = $r['Nom'];
                }
            }
            $response['users_sample'] = $users;
        }
        
        // Test RH
        $connRH = new mysqli('localhost', 'transubd', 'Tr@nsub2@24', 'transubd_GRH');
        if ($connRH->connect_error) {
            $response['db_rh_connection'] = 'ECHEC: ' . $connRH->connect_error;
        } else {
            $response['db_rh_connection'] = 'SUCCÈS';
            $result3 = $connRH->query("SELECT COUNT(*) as total FROM salaries");
            if ($result3) {
                $row3 = $result3->fetch_assoc();
                $response['salaries_count'] = $row3['total'];
            }
            $connRH->close();
        }
        
        $conn->close();
    }
} catch (Exception $e) {
    $response['error_exception'] = $e->getMessage();
}

echo json_encode($response, JSON_PRETTY_PRINT);