<?php
// get_enrollment_status.php
// Returns JSON with BioStar2 user enrollment status (face + fingerprint)
// Detection: JOIN against t_fctmpl and t_fngptmpl (both tables exist, are empty until templates enrolled)

$servername = "192.168.0.39";
$username   = "vanaeph";
$password   = "Tykun.2026";
$dbname     = "biostar2_ac";
$port       = 3312;

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

$conn = new mysqli($servername, $username, $password, $dbname, $port);
if ($conn->connect_error) {
    http_response_code(500);
    echo json_encode(['error' => 'DB connection failed: ' . $conn->connect_error]);
    exit;
}
$conn->set_charset("utf8");

$sql = "
    SELECT
        u.USRUID  AS usruid,
        u.USRID   AS usrid,
        u.NM      AS nm,
        u.SECLVL  AS seclvl,
        u.DSBDUSR AS dsbdusr,
        u.CREATEDT AS createdt,
        CASE WHEN COUNT(DISTINCT f.FCTMPLUID) > 0 THEN 1 ELSE 0 END AS face_enrolled,
        CASE WHEN COUNT(DISTINCT fp.FNGPUID)  > 0 THEN 1 ELSE 0 END AS finger_enrolled
    FROM t_usr u
    LEFT JOIN t_fctmpl  f  ON f.USRUID  = u.USRUID
    LEFT JOIN t_fngptmpl fp ON fp.USRUID = u.USRUID
    WHERE u.DEL = 'N'
      AND u.USRUID >= 1001
    GROUP BY u.USRUID, u.USRID, u.NM, u.SECLVL, u.DSBDUSR, u.CREATEDT
    ORDER BY u.USRUID ASC
";

$result = $conn->query($sql);
if (!$result) {
    http_response_code(500);
    echo json_encode(['error' => 'Query failed: ' . $conn->error]);
    $conn->close();
    exit;
}

$users = [];
$enrolled_count = 0;
while ($row = $result->fetch_assoc()) {
    $face = (int)$row['face_enrolled'];
    $finger = (int)$row['finger_enrolled'];
    if ($face) $enrolled_count++;
    $users[] = [
        'usruid'          => (int)$row['usruid'],
        'usrid'           => $row['usrid'],
        'nm'              => $row['nm'],
        'seclvl'          => $row['seclvl'],
        'dsbdusr'         => $row['dsbdusr'],
        'createdt'        => $row['createdt'],
        'face_enrolled'   => (bool)$face,
        'finger_enrolled' => (bool)$finger,
    ];
}

$conn->close();

echo json_encode([
    'users'   => $users,
    'summary' => [
        'enrolled' => $enrolled_count,
        'total'    => count($users),
    ],
], JSON_UNESCAPED_UNICODE);
