<?php
// POST /api/submit-reading

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

$payload = authenticate();

$previous_reading = trim($_POST['previous_reading'] ?? '');
$current_reading  = trim($_POST['current_reading'] ?? '');
$device_id        = trim($_POST['device_id'] ?? '');
$submitted_by     = trim($_POST['submit_by'] ?? '');
$note             = trim($_POST['note'] ?? '') ?: null;

if ($previous_reading === '' || $current_reading === '' || !$device_id || !$submitted_by) {
    sendError('previous_reading, current_reading, device_id and submit_by are required');
}

if (!is_numeric($previous_reading) || !is_numeric($current_reading)) {
    sendError('Readings must be numeric');
}

if ((float)$current_reading < (float)$previous_reading) {
    sendError('Current reading cannot be less than previous reading');
}

$units = (float)$current_reading - (float)$previous_reading;

// Handle photo upload
$photo_path = null;
if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
    $allowed = ['image/jpeg', 'image/png', 'image/jpg'];
    $mime = mime_content_type($_FILES['photo']['tmp_name']);

    if (!in_array($mime, $allowed)) {
        sendError('Only JPG/PNG images are allowed');
    }

    if ($_FILES['photo']['size'] > 5 * 1024 * 1024) {
        sendError('Image size must be under 5MB');
    }

    if (!is_dir(UPLOAD_DIR)) {
        mkdir(UPLOAD_DIR, 0755, true);
    }

    $ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
    $filename = 'reading_' . $payload['user_id'] . '_' . time() . '.' . $ext;
    $dest = UPLOAD_DIR . $filename;

    if (!move_uploaded_file($_FILES['photo']['tmp_name'], $dest)) {
        sendError('Failed to upload photo');
    }

    $photo_path = $filename;
}

$reading_date = date('Y-m-d');

$db = getDB();

// Prevent duplicate submission for the same user on the same day
$check = $db->prepare("SELECT id FROM meter_readings WHERE user_id = ? AND reading_date = ? LIMIT 1");
$user_id_check = $payload['user_id'];
$check->bind_param("is", $user_id_check, $reading_date);
$check->execute();
$check->store_result();
if ($check->num_rows > 0) {
    $check->close();
    $db->close();
    sendError('You have already submitted a reading today. Only one reading per day is allowed.', 409);
}
$check->close();

$stmt = $db->prepare("
    INSERT INTO meter_readings (user_id, device_id, previous_reading, current_reading, units, photo_path, submitted_by, reading_date, note)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$user_id = $payload['user_id'];
$stmt->bind_param(
    "isdddssss",
    $user_id,
    $device_id,
    $previous_reading,
    $current_reading,
    $units,
    $photo_path,
    $submitted_by,
    $reading_date,
    $note
);
$stmt->execute();
$stmt->close();
$db->close();
$url = "https://anl-video.companyonline.in/remainder.php";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_exec($ch);
curl_close($ch);
sendSuccess([], 'Reading submitted successfully');
