<?php
// /core/includes/readings_helpers.php

/**
 * Recalculate daily consumption for ONE meter and ONE date (YYYY-MM-DD).
 * Writes daily_consumption on the "last reading row" of that day.
 *
 * Rules:
 * - daily_consumption = last_of_day - last_before_day
 * - If no baseline (no previous reading) => daily_consumption = NULL
 * - If negative => daily_consumption = NULL (you can flag later)
 */
function recalcDailyConsumption(PDO $pdo, int $meterId, string $date): void
{
    // normalize date
    $date = date('Y-m-d', strtotime($date));

    $dayStart = $date . " 00:00:00";
    $nextDay  = date('Y-m-d', strtotime($date . " +1 day")) . " 00:00:00";

    // 1) Find the last reading row for this day
    $stmt = $pdo->prepare("
        SELECT id, reading_value
        FROM meter_readings
        WHERE meter_id = ?
          AND reading_datetime >= ?
          AND reading_datetime < ?
        ORDER BY reading_datetime DESC
        LIMIT 1
    ");
    $stmt->execute([$meterId, $dayStart, $nextDay]);
    $today = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$today) {
        // No readings that day -> nothing to update
        return;
    }

    $todayId    = (int)$today['id'];
    $todayValue = (float)$today['reading_value'];

    // 2) Find the last reading BEFORE this day (baseline)
    $stmt = $pdo->prepare("
        SELECT reading_value
        FROM meter_readings
        WHERE meter_id = ?
          AND reading_datetime < ?
        ORDER BY reading_datetime DESC
        LIMIT 1
    ");
    $stmt->execute([$meterId, $dayStart]);
    $prev = $stmt->fetch(PDO::FETCH_ASSOC);

    $daily = null;

    if ($prev && $prev['reading_value'] !== null) {
        $prevValue = (float)$prev['reading_value'];
        $calc = $todayValue - $prevValue;

        // guard against negative (reset/rollover/bad entry)
        if ($calc >= 0) {
            $daily = $calc;
        } else {
            $daily = null; // keep null; later you can add a "flag" column
        }
    }

    // 3) Update the last row of day with daily_consumption and reading_date
    $upd = $pdo->prepare("
        UPDATE meter_readings
        SET daily_consumption = :daily,
            reading_date = :rdate
        WHERE id = :id
        LIMIT 1
    ");
    $upd->execute([
        ':daily' => $daily,
        ':rdate' => $date,
        ':id'    => $todayId
    ]);
}

/**
 * Recalculate for a date range (inclusive) for one meter.
 * Useful for the "Recalculate" button and imports.
 */
function recalcDailyConsumptionRange(PDO $pdo, int $meterId, string $startDate, string $endDate): void
{
    $start = date('Y-m-d', strtotime($startDate));
    $end   = date('Y-m-d', strtotime($endDate));

    $d = strtotime($start);
    $e = strtotime($end);

    if ($d === false || $e === false) return;
    if ($d > $e) return;

    while ($d <= $e) {
        recalcDailyConsumption($pdo, $meterId, date('Y-m-d', $d));
        $d = strtotime("+1 day", $d);
    }
}