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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("Invalid request.");
}

$companyId = $_SESSION['company_id'];
$userId    = $_SESSION['user_id'];

$periodId  = (int)($_POST['period_id'] ?? 0);
$readings  = $_POST['reading'] ?? [];

if (!$periodId) {
    die("Billing period missing.");
}

try {

    $pdo->beginTransaction();

    /* ===============================
       Validate Billing Period
    ================================== */
    $stmt = $pdo->prepare("
        SELECT *
        FROM billing_periods
        WHERE id = ?
        AND company_id = ?
        AND status = 'OPEN'
        LIMIT 1
    ");
    $stmt->execute([$periodId, $companyId]);
    $period = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$period) {
        throw new Exception("Invalid or locked billing period.");
    }

    foreach ($readings as $meterId => $value) {

        if ($value === '' || $value === null) {
            continue;
        }

        $meterId = (int)$meterId;
        $value   = (float)$value;

        /* ===============================
           Validate Meter is ACTIVE
        ================================== */
        $stmt = $pdo->prepare("
            SELECT status
            FROM operational_meters
            WHERE id = ?
            LIMIT 1
        ");
        $stmt->execute([$meterId]);
        $meter = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$meter || $meter['status'] !== 'ACTIVE') {
            throw new Exception("Meter {$meterId} is not ACTIVE.");
        }

        /* ===============================
           Fetch Previous Reading
        ================================== */
        $stmt = $pdo->prepare("
            SELECT reading_value
            FROM meter_readings
            WHERE meter_id = ?
            ORDER BY id DESC
            LIMIT 1
        ");
        $stmt->execute([$meterId]);
        $previous = $stmt->fetchColumn();

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

        /* ===============================
           Validate Reading Rules
        ================================== */
        if ($previous !== false && $value < $previous) {
            throw new Exception("Reading for meter {$meterId} cannot be less than previous reading.");
        }

        /* ===============================
           CHECK EXISTING (PER PERIOD)
        ================================== */
        $stmt = $pdo->prepare("
            SELECT id
            FROM meter_readings
            WHERE meter_id = ?
            AND reading_date = ?
            LIMIT 1
        ");
        $stmt->execute([
            $meterId,
            $period['period_end']
        ]);

        $existingId = $stmt->fetchColumn();

        if ($existingId) {

            /* ===============================
               UPDATE EXISTING
            ================================== */
            $stmt = $pdo->prepare("
                UPDATE meter_readings
                SET reading_value = ?
                WHERE id = ?
            ");

            $stmt->execute([
                $value,
                $existingId
            ]);

        } else {

            /* ===============================
               INSERT NEW
            ================================== */
            $stmt = $pdo->prepare("
                INSERT INTO meter_readings
                (meter_id, reading_value, reading_type, source, reading_date, created_at)
                VALUES (?, ?, 'MANUAL', 'MANUAL_ENTRY', ?, NOW())
            ");

            $stmt->execute([
                $meterId,
                $value,
                $period['period_end']
            ]);
        }
    }

    $pdo->commit();

} catch (Exception $e) {

    $pdo->rollBack();

    header("Location: index.php?period_id=".$periodId."&error=".urlencode($e->getMessage()));
    exit;
}

header("Location: index.php?period_id=".$periodId."&saved=1");
exit;