<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../includes/auth.php';
requireLogin();

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/readings_helpers.php';


/* ===============================
   SAVE READING
================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

$meterId = (int)$_POST['meter_id'];
$readingValue = (float)$_POST['reading_value'];
$readingDatetime = $_POST['reading_datetime'];

$stmt = $pdo->prepare("
INSERT INTO meter_readings
(meter_id, reading_datetime, reading_value)
VALUES (?, ?, ?)
");

$stmt->execute([
$meterId,
$readingDatetime,
$readingValue
]);


/* ===============================
   AUTO DAILY CALCULATION
================================= */

$readingDate = date('Y-m-d', strtotime($readingDatetime));

recalcDailyConsumption($pdo, $meterId, $readingDate);

$nextDate = date('Y-m-d', strtotime($readingDate . ' +1 day'));

recalcDailyConsumption($pdo, $meterId, $nextDate);


header("Location: add_reading.php?success=1");
exit;

}

?>


<?php require_once __DIR__ . '/../../includes/header.php'; ?>
<?php require_once __DIR__ . '/../../includes/sidebar.php'; ?>


<div class="main-content">

<div class="page-header">
<h2>Add Meter Reading</h2>
</div>


<?php if (isset($_GET['success'])): ?>

<div class="alert-success">
Reading saved successfully.
</div>

<?php endif; ?>


<form method="POST" class="card-form">


<label>Select Operational Meter</label>

<select name="meter_id" required class="input">

<option value="">Select Meter</option>

<?php

$stmt = $pdo->query("
SELECT 
    om.id,
    om.meter_number,
    c.company_name
FROM operational_meters om
JOIN companies c ON c.id = om.company_id
WHERE om.status = 'ACTIVE'
ORDER BY om.meter_number ASC
");

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

echo '<option value="'.$m['id'].'">
'.$m['meter_number'].' — '.$m['company_name'].'
</option>';

}

?>

</select>


<label>Reading Date & Time</label>

<input type="datetime-local" name="reading_datetime" required>


<label>Cumulative Reading</label>

<input type="number" step="0.0001" name="reading_value" required>


<button type="submit" class="btn-primary">

Save Reading

</button>


</form>

</div>


<?php require_once __DIR__ . '/../../includes/footer.php'; ?>