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

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

/* ===============================
CREATE OPERATIONAL METER
================================ */
if(!empty($_POST['inventory_unit_id'])){

$inventoryUnits   = $_POST['inventory_unit_id'];
$accountId        = (int)($_POST['account_id'] ?? 0);
$tariffProfileId  = $_POST['tariff_profile_id'] ?? null;
$status           = $_POST['status'] ?? 'ACTIVE';
$unitName         = trim($_POST['unit_name'] ?? '');

if($accountId === 0) die("Account not selected");
if(empty($tariffProfileId)) die("Tariff not selected");
if(empty($unitName)) die("Unit required");

$createdAnyMeter = false;

foreach($inventoryUnits as $inventoryUnit){

$stmt = $pdo->prepare("SELECT meter_number FROM inventory_units WHERE id=?");
$stmt->execute([$inventoryUnit]);
$meter = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$meter) continue;

$meterNumber = $meter['meter_number'];

/* prevent duplicate */
$stmt = $pdo->prepare("SELECT id FROM operational_meters WHERE meter_number=? LIMIT 1");
$stmt->execute([$meterNumber]);
if($stmt->fetch()) continue;

/* create meter */
$stmt = $pdo->prepare("
INSERT INTO operational_meters
(inventory_unit_id, account_id, meter_number, unit_name, tariff_id, tariff_profile_id, status)
VALUES (?,?,?,?,?,?,?)
");

$stmt->execute([
$inventoryUnit,
$accountId,
$meterNumber,
$unitName,
$tariffProfileId,
$tariffProfileId,
$status
]);

$meterId = $pdo->lastInsertId();
$createdAnyMeter = true;

/* meter charges */
if(!empty($_POST['charges'])){
foreach($_POST['charges'] as $chargeId){

$pdo->prepare("
INSERT INTO meter_charges (meter_id, charge_id, start_date)
SELECT ?, ?, CURDATE()
WHERE NOT EXISTS (
SELECT 1 FROM meter_charges WHERE meter_id=? AND charge_id=?
)
")->execute([$meterId,$chargeId,$meterId,$chargeId]);

}}
/* update inventory */
$pdo->prepare("
UPDATE inventory_units
SET status='ACTIVE', activated_at=NOW()
WHERE id=?
")->execute([$inventoryUnit]);
}

/* unit charges (once per unit) */
if($createdAnyMeter && !empty($_POST['unit_charges'])){
foreach($_POST['unit_charges'] as $chargeId){

$pdo->prepare("
INSERT INTO unit_charges (account_id, unit_name, charge_id, start_date)
SELECT ?, ?, ?, CURDATE()
WHERE NOT EXISTS (
SELECT 1 FROM unit_charges WHERE account_id=? AND unit_name=? AND charge_id=?
)
")->execute([$accountId,$unitName,$chargeId,$accountId,$unitName,$chargeId]);

}}

/* account charges */
if($createdAnyMeter && !empty($_POST['account_charges'])){
foreach($_POST['account_charges'] as $chargeId){

$pdo->prepare("
INSERT INTO account_charges (account_id, charge_id, start_date)
SELECT ?, ?, CURDATE()
WHERE NOT EXISTS (
SELECT 1 FROM account_charges WHERE account_id=? AND charge_id=?
)
")->execute([$accountId,$chargeId,$accountId,$chargeId]);

}}

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

/* ===============================
LOAD DATA
================================ */

$customers = $pdo->query("SELECT id, customer_name FROM billing_customers")->fetchAll(PDO::FETCH_ASSOC);
$accounts  = $pdo->query("SELECT id, customer_id, account_name FROM billing_accounts")->fetchAll(PDO::FETCH_ASSOC);

$tariffs = $pdo->query("
SELECT p.id, t.tariff_name
FROM tariff_profiles p
JOIN tariffs t ON p.tariff_id=t.id
")->fetchAll(PDO::FETCH_ASSOC);

$charges = $pdo->query("SELECT * FROM billing_charges WHERE applies_to='METER'")->fetchAll(PDO::FETCH_ASSOC);
$unitCharges = $pdo->query("SELECT * FROM billing_charges WHERE applies_to='UNIT'")->fetchAll(PDO::FETCH_ASSOC);
$accountCharges = $pdo->query("SELECT * FROM billing_charges WHERE applies_to='ACCOUNT'")->fetchAll(PDO::FETCH_ASSOC);

$units = $pdo->query("SELECT id, meter_number FROM inventory_units WHERE status='IN_STOCK'")->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__.'/../../includes/layout.php';
?>

<style>
.wrapper{display:flex;gap:20px;max-width:1200px;margin:0 auto;padding:20px;}
.left{flex:1;}
.right{width:300px;background:#fff;padding:15px;border:1px solid #ddd;border-radius:8px;}
input,select{width:100%;margin-bottom:10px;padding:6px;box-sizing:border-box;}
</style>

<div class="wrapper">

<!-- LEFT -->
<div class="left">
<form method="POST">

<h2>Meter Setup Wizard</h2>

<input id="meter_search" placeholder="Search meter">

<select id="inventory_unit_select" size="5">
<?php foreach($units as $u): ?>
<option value="<?= $u['id'] ?>" data-meter="<?= $u['meter_number'] ?>">
<?= $u['meter_number'] ?>
</option>
<?php endforeach; ?>
</select>

<div id="selected_meters"></div>

<h3>Meter Info</h3>

<input name="unit_name" placeholder="Unit / Room" required>

<select id="customer_select">
<option>Select Customer</option>
<?php foreach($customers as $c): ?>
<option value="<?= $c['id'] ?>"><?= $c['customer_name'] ?></option>
<?php endforeach; ?>
</select>

<select name="account_id" id="account_select" required>
<option>Select Account</option>
<?php foreach($accounts as $a): ?>
<option value="<?= $a['id'] ?>" data-customer="<?= $a['customer_id'] ?>">
<?= $a['account_name'] ?>
</option>
<?php endforeach; ?>
</select>

<select name="tariff_profile_id" id="tariff_select" required>
<option>Select Tariff</option>
<?php foreach($tariffs as $t): ?>
<option value="<?= $t['id'] ?>"><?= $t['tariff_name'] ?></option>
<?php endforeach; ?>
</select>

<h3>Meter Charges</h3>
<?php foreach($charges as $c): ?>
<label><input type="checkbox" name="charges[]" value="<?= $c['id'] ?>"> <?= $c['charge_name'] ?></label>
<?php endforeach; ?>

<h3>Unit Charges</h3>
<?php foreach($unitCharges as $c): ?>
<label><input type="checkbox" name="unit_charges[]" value="<?= $c['id'] ?>"> <?= $c['charge_name'] ?></label>
<?php endforeach; ?>

<h3>Account Charges</h3>
<?php foreach($accountCharges as $c): ?>
<label><input type="checkbox" name="account_charges[]" value="<?= $c['id'] ?>"> <?= $c['charge_name'] ?></label>
<?php endforeach; ?>

<select name="status">
<option>ACTIVE</option>
<option>SUSPENDED</option>
</select>

<button>Register Meter</button>

</form>
</div>

<!-- RIGHT -->
<div class="right">
<h3>Simulation</h3>

<div id="sim_unit">Unit: -</div>
<div id="sim_charges"></div>

<hr>

<strong>Total: <span id="sim_total">R 0.00</span></strong>
</div>

</div>

<script>

/* add meter /
document.getElementById('inventory_unit_select').addEventListener('change',function(){
let opt=this.options[this.selectedIndex];
if(!opt.value)return;

let div=document.createElement('div');
div.innerHTML=opt.text+'<input type="hidden" name="inventory_unit_id[]" value="'+opt.value+'">';
document.getElementById('selected_meters').appendChild(div);
});

/ simulation */
function updateSim(){
let total=0;

document.getElementById('sim_unit').innerText=
"Unit: "+document.querySelector('[name=unit_name]').value;

let html='';
document.querySelectorAll('input[type=checkbox]:checked').forEach(cb=>{
html+=cb.parentElement.innerText+'<br>';
});

document.getElementById('sim_charges').innerHTML=html;
document.getElementById('sim_total').innerText='R '+total.toFixed(2);
}

document.querySelectorAll('input,select').forEach(el=>{
el.addEventListener('change',updateSim);
});

</script>

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