<?php
require_once __DIR__ . '/../../../includes/auth.php';
requireLogin();
requirePermission('view_billing');

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

$companyId = $_SESSION['company_id'] ?? null;
$role      = $_SESSION['role_name'] ?? '';
$isSuper   = !empty($_SESSION['is_super_admin']);


/* ===============================
   Fetch Open Billing Periods
================================= */
if ($isSuper) {
    $stmt = $pdo->prepare("
        SELECT *
        FROM billing_periods
        WHERE status = 'OPEN'
        ORDER BY period_start DESC
    ");
    $stmt->execute();
} else {

    if (!$companyId) {
        $periods = [];
        $selectedPeriod = null;
        $breadcrumb = "Manual Meter Readings";
        require_once __DIR__ . '/../../../includes/layout.php';
        echo "<div class='container'><div class='muted'>Company session is missing. Please log out and log in again.</div></div>";
        require_once __DIR__ . '/../../../includes/layout_footer.php';
        exit;
    }

    $stmt = $pdo->prepare("
        SELECT *
        FROM billing_periods
        WHERE company_id = ?
        AND status = 'OPEN'
        ORDER BY period_start DESC
    ");
    $stmt->execute([$companyId]);
}

$periods = $stmt->fetchAll(PDO::FETCH_ASSOC);

$selectedPeriod = isset($_GET['period_id'])
    ? (int)$_GET['period_id']
    : ($periods[0]['id'] ?? null);


/* ===============================
   Fetch ACTIVE Operational Meters
================================= */
if ($isSuper) {

    $stmt = $pdo->prepare("
        SELECT *
        FROM operational_meters
        WHERE status = 'ACTIVE'
        ORDER BY id ASC
    ");
    $stmt->execute();

} else {

    $stmt = $pdo->prepare("
        SELECT *
        FROM operational_meters
        WHERE company_id = ?
        AND status = 'ACTIVE'
        ORDER BY id ASC
    ");
    $stmt->execute([$companyId]);
}

$meters = $stmt->fetchAll(PDO::FETCH_ASSOC);

$breadcrumb = "Manual Meter Readings";
require_once __DIR__ . '/../../../includes/layout.php';
?>

<div class="container">
<?php if(isset($_GET['saved'])): ?>
    <div style="background:#e8f5e9;color:#2e7d32;padding:12px;border-radius:6px;margin-bottom:15px;">
        Readings saved successfully.
    </div>
<?php endif; ?>

<?php if(isset($_GET['error'])): ?>
    <div style="background:#ffebee;color:#c62828;padding:12px;border-radius:6px;margin-bottom:15px;">
        <?= htmlspecialchars($_GET['error']) ?>
    </div>
<?php endif; ?>
<div class="page-header">
<h2>Manual Meter Readings</h2>
<p class="page-subtitle">
Enter readings for ACTIVE operational meters.
</p>
</div>

<!-- ===============================
     PERIOD SELECTOR
================================== -->
<form method="GET" style="margin-bottom:20px;">
<select name="period_id" onchange="this.form.submit()" style="padding:8px;">
<option value="">Select Billing Period</option>

<?php foreach ($periods as $p): ?>

<option value="<?= (int)$p['id'] ?>"
<?= ((string)$selectedPeriod === (string)$p['id']) ? 'selected' : '' ?>>

<?= htmlspecialchars($p['period_start']) ?>
to
<?= htmlspecialchars($p['period_end']) ?>

</option>

<?php endforeach; ?>

</select>
</form>


<?php if (!empty($selectedPeriod)) : ?>

<div style="margin-bottom:20px;">

<a href="generate.php?period_id=<?= (int)$selectedPeriod ?>"
class="btn success"
onclick="return confirm('Are you sure you want to generate invoices for this period?');">
Generate Invoices
</a>

<a href="preview.php?period_id=<?= (int)$selectedPeriod ?>"
class="btn"
style="background:#f2531e;color:#fff;margin-right:10px;">
Preview Billing
</a>

</div>

<?php endif; ?>


<?php if ($selectedPeriod && !empty($meters)): ?>
<!-- ✅ ADD HERE -->
<h3>Upload Bulk Readings</h3>

<form method="POST" action="import_readings.php" enctype="multipart/form-data" style="margin-bottom:20px;">

<input type="hidden" name="period_id" value="<?= $selectedPeriod ?>">

<input type="file" name="file" accept=".csv,.xlsx" required>

<button class="btn success">Upload Sheet</button>

</form>

<form method="POST" action="save.php">

<input type="hidden"
name="period_id"
value="<?= htmlspecialchars($selectedPeriod) ?>">


<div class="table-wrap" style="overflow-x:auto;">

<table style="min-width:1300px;width:100%;border-collapse:collapse;">

<thead>

<tr>

<th>ID</th>
<th>Meter Number</th>
<th>Previous Reading</th>
<th>New Reading</th>
<th>Consumption (Preview)</th>

</tr>

</thead>


<tbody>

<?php foreach ($meters as $m): ?>

<?php

$lastReading = null;

try {

$stmtLast = $pdo->prepare("
SELECT reading_value
FROM meter_readings
WHERE meter_id = ?
ORDER BY id DESC
LIMIT 1
");

$stmtLast->execute([$m['id']]);

$lastReading = $stmtLast->fetchColumn();

if($lastReading !== false){
$lastReading = (float)$lastReading;
}

} catch (Exception $e) {

$lastReading = null;

}

?>


<tr>

<td><?= (int)$m['id'] ?></td>

<td><?= htmlspecialchars($m['meter_number']) ?></td>


<td>

<?= ($lastReading !== null)
? number_format($lastReading,4)
: '—' ?>

</td>


<td>

<input
type="number"
step="0.001"
name="reading[<?= (int)$m['id'] ?>]"
data-last="<?= ($lastReading !== null ? $lastReading : 0) ?>"
class="reading-input"
style="width:120px;padding:6px;"
>

</td>


<td class="consumption-cell">

<?php if($lastReading !== null): ?>
    <span style="color:#757575;">Waiting...</span>
<?php else: ?>
    <span style="color:#bdbdbd;">No previous reading</span>
<?php endif; ?>

</td>

</tr>


<?php endforeach; ?>

</tbody>

</table>

</div>


<script>

document.querySelectorAll('.reading-input').forEach(input => {

    input.addEventListener('input', function() {

        let last = parseFloat(this.dataset.last || 0);
        let current = parseFloat(this.value || 0);

        let row = this.closest('tr');
        let cell = row.querySelector('.consumption-cell');

        /* reset border */
        this.style.border = "1px solid #ccc";

        if (this.value === "") {
            cell.innerHTML = "—";
            return;
        }

        if (current < last) {

            this.style.border = "2px solid #e53935"; // red

            cell.innerHTML =
            "<span style='color:#e53935;font-weight:600;'>Reading lower than previous</span>";

        }
        else if (current === last) {

            this.style.border = "2px solid #ff9800"; // orange

            cell.innerHTML =
            "<span style='color:#ff9800;font-weight:600;'>Duplicate reading</span>";

        }
    else {

    let diff = current - last;

    if(diff < 0){
        cell.innerHTML =
        "<span style='color:#e53935;font-weight:600;'>Invalid</span>";
        return;
    }

    /* maximum allowed consumption */
    let MAX_USAGE = 1000;

    if(diff > MAX_USAGE){

        this.style.border = "2px solid #9c27b0";

        cell.innerHTML =
        "<span style='color:#9c27b0;font-weight:600;'>Unusually high (" + diff.toFixed(3) + ")</span>";

    }
    else{

        this.style.border = "2px solid #2e7d32";

        cell.innerHTML =
        "<span style='color:#2e7d32;font-weight:600;'>OK (" + diff.toFixed(3) + ")</span>";

    }

}

    });

});

</script>


<div style="margin-top:20px;">
<button class="btn success">Save Readings</button>
</div>

</form>

<?php elseif ($selectedPeriod): ?>

<div class="muted">
No ACTIVE operational meters found.
</div>

<?php endif; ?>

</div>

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