<?php

function getMeterReadingsForPeriod($pdo, $meterId, $periodStart, $periodEnd) {

    // START READING (before period)
    $stmt = $pdo->prepare("
        SELECT reading_value
        FROM meter_readings
        WHERE meter_id = ?
        AND reading_date < ?
        ORDER BY reading_date DESC, id DESC
        LIMIT 1
    ");
    $stmt->execute([$meterId, $periodStart]);
    $start = $stmt->fetchColumn();

    // END READING (within period)
    $stmt = $pdo->prepare("
        SELECT reading_value
        FROM meter_readings
        WHERE meter_id = ?
        AND reading_date <= ?
        ORDER BY reading_date DESC, id DESC
        LIMIT 1
    ");
    $stmt->execute([$meterId, $periodEnd]);
    $end = $stmt->fetchColumn();

    if ($start === false) {
        $start = 0;
    }

    if ($end === false) {
        return [
            'start' => $start,
            'end' => null,
            'usage' => 0
        ];
    }

    $usage = (float)$end - (float)$start;

    if ($usage < 0) {
        $usage = 0;
    }

    return [
        'start' => (float)$start,
        'end' => (float)$end,
        'usage' => $usage
    ];
}