<?php

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

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

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

$meterNumber    = trim($_POST['meter_number']);

$accountId = (int)$_POST['account_id'];

if($accountId === 0){
    die("Account required");
}

$tariffId       = (int)$_POST['tariff_id'];
$openingReading = $_POST['opening_reading'] ?? null;

/* ===============================
CHECK DUPLICATE METER
================================ */

$stmt = $pdo->prepare("
    SELECT id
    FROM operational_meters
    WHERE meter_number = ?
    LIMIT 1
");

$stmt->execute([$meterNumber]);

if ($stmt->fetch()) {
    die("Meter already exists.");
}

try {

    $pdo->beginTransaction();

    /* ===============================
       STEP 1 — CREATE INVENTORY UNIT
    ================================ */

   $stmt = $pdo->prepare("
INSERT INTO inventory_units
(account_id, product_id, meter_number, status, created_at)
VALUES (?,?,?,?,NOW())
");

$stmt->execute([
$companyId,
1,                // product id for meter type
$meterNumber,
'ACTIVE'
]);
    $inventoryUnitId = $pdo->lastInsertId();

    /* ===============================
       STEP 2 — CREATE OPERATIONAL METER
    ================================ */

    $stmt = $pdo->prepare("
        INSERT INTO operational_meters
        (inventory_unit_id, meter_number, account_id, tariff_id, status)
        VALUES (?,?,?,?,?)
    ");

    $stmt->execute([
    $inventoryUnitId,
    $meterNumber,
    $accountId,
    $tariffId,
    'ACTIVE'
]);
    $meterId = $pdo->lastInsertId();

    /* ===============================
       STEP 3 — ADD OPENING READING
    ================================ */

    if ($openingReading !== "" && $openingReading !== null) {

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

        $stmt->execute([
            $meterId,
            date('Y-m-d H:i:s'),
            $openingReading,
            'INITIAL',
            'METER_SETUP'
        ]);
    }

    $pdo->commit();

} catch (Exception $e) {

    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    die($e->getMessage());
}

header("Location: index.php?saved=1");
exit;