<?php

header('Content-Type: application/json');

try {

    $db = new PDO(
        'sqlite:' . __DIR__ . '/database.db'
    );

    $db->setAttribute(
        PDO::ATTR_ERRMODE,
        PDO::ERRMODE_EXCEPTION
    );

    $stmt = $db->query("
        SELECT
            user_id,
            name,
            picture,
            activation_date,
            expiry_date
        FROM activated_students
        ORDER BY user_id ASC
    ");

    $students = [];

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

        $picture = null;

        if (
            isset($row['picture']) &&
            $row['picture'] !== null &&
            $row['picture'] !== ''
        ) {
            $picture = base64_encode($row['picture']);
        }

        $students[] = [
            'user_id' => $row['user_id'],
            'name' => $row['name'],
            'picture' => $picture,
            'activation_date' => $row['activation_date'],
            'expiry_date' => $row['expiry_date']
        ];
    }

    echo json_encode([
        'success' => true,
        'count' => count($students),
        'students' => $students
    ]);
} catch (Exception $e) {

    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
