<?php
// GET /api/reading-history

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendError('Method not allowed', 405);
}

$payload = authenticate();

$from_date = $_GET['from_date'] ?? '';
$to_date   = $_GET['to_date'] ?? date('Y-m-d');

$db = getDB();

if ($from_date) {
    $stmt = $db->prepare("
        SELECT reading_date AS date, previous_reading AS previous, current_reading AS current,
               units, photo_path, submitted_by, created_at AS posted_at,note
        FROM meter_readings
        WHERE  reading_date BETWEEN ? AND ?
        ORDER BY created_at DESC
    ");
    $stmt->bind_param("ss", $from_date, $to_date);
} else {
    $stmt = $db->prepare("
        SELECT reading_date AS date, previous_reading AS previous, current_reading AS current,
               units, photo_path, submitted_by, created_at AS posted_at,note
        FROM meter_readings

        ORDER BY created_at DESC
    ");
}

$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
$db->close();

// Build photo URL
$data = array_map(function($row) {
    $row['photo_url'] = ($row['photo_path'] && file_exists(UPLOAD_DIR . $row['photo_path']))
        ? UPLOAD_URL . $row['photo_path']
        : null;
    unset($row['photo_path']);
    return $row;
}, $rows);

sendSuccess(['data' => $data]);