<?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 (MULTI SUPPORT ADDED)
================================ */

if(!empty($_POST['inventory_unit_id'])){

$inventoryUnits   = $_POST['inventory_unit_id'];
$accountId        = isset($_POST['account_id']) ? (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 - STOP");
}

if(empty($tariffProfileId)){
    die("Tariff profile not selected");
}

if(empty($unitName)){
    die("Unit / Room is 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;

/* ASSIGN METER CHARGES (PER METER) */
if(!empty($_POST['use_custom_charges']) && !empty($_POST['charges'])){

foreach($_POST['charges'] as $chargeId){

$stmt = $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 = ?
    AND (end_date IS NULL OR end_date = '0000-00-00')
)
");

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

}
}

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

}

/* ASSIGN UNIT CHARGES (ONCE PER UNIT) */
if($createdAnyMeter && !empty($_POST['use_unit_charges']) && !empty($_POST['unit_charges'])){

foreach($_POST['unit_charges'] as $chargeId){

$stmt = $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 = ?
)
");

$stmt->execute([$accountId,$unitName,$chargeId,$accountId,$unitName,$chargeId]);

}
}

/* ASSIGN ACCOUNT CHARGES (ONCE PER ACCOUNT) */
if($createdAnyMeter && !empty($_POST['use_account_charges']) && !empty($_POST['account_charges'])){

foreach($_POST['account_charges'] as $chargeId){

$stmt = $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 = ?
    AND (end_date IS NULL OR end_date = '0000-00-00')
)
");

$stmt->execute([$accountId,$chargeId,$accountId,$chargeId]);

}
}

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

}

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

/* LOAD DATA */

$customers = $pdo->query("
SELECT id, customer_name, customer_code
FROM billing_customers
ORDER BY customer_name
")->fetchAll(PDO::FETCH_ASSOC);

$accounts = $pdo->query("
SELECT id, customer_id, account_name, municipality_name
FROM billing_accounts
ORDER BY account_name
")->fetchAll(PDO::FETCH_ASSOC);

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

$charges = $pdo->query("
SELECT 
c.id,
c.charge_name,
c.charge_type,
c.charge_value,
cat.name AS category
FROM billing_charges c
LEFT JOIN billing_charge_categories cat ON c.category_id = cat.id
WHERE c.active = 1
AND c.applies_to = 'METER'
ORDER BY cat.name, c.charge_name
")->fetchAll(PDO::FETCH_ASSOC);

$unitCharges = $pdo->query("
SELECT 
c.id,
c.charge_name,
c.charge_type,
c.charge_value,
cat.name AS category
FROM billing_charges c
LEFT JOIN billing_charge_categories cat ON c.category_id = cat.id
WHERE c.active = 1
AND c.applies_to = 'UNIT'
ORDER BY cat.name, c.charge_name
")->fetchAll(PDO::FETCH_ASSOC);

$accountCharges = $pdo->query("
SELECT 
c.id,
c.charge_name,
c.charge_type,
c.charge_value,
cat.name AS category
FROM billing_charges c
LEFT JOIN billing_charge_categories cat ON c.category_id = cat.id
WHERE c.active = 1
AND c.applies_to = 'ACCOUNT'
ORDER BY cat.name, c.charge_name
")->fetchAll(PDO::FETCH_ASSOC);

$groupedCharges = [];
foreach($charges as $c){
    $category = $c['category'] ?: 'Other';
    $groupedCharges[$category][] = $c;
}

$groupedUnitCharges = [];
foreach($unitCharges as $c){
    $category = $c['category'] ?: 'Other';
    $groupedUnitCharges[$category][] = $c;
}

$groupedAccountCharges = [];
foreach($accountCharges as $c){
    $category = $c['category'] ?: 'Other';
    $groupedAccountCharges[$category][] = $c;
}

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

<div class="container">

<div class="page-header">
<h2>Meter Setup Wizard</h2>
<p class="page-subtitle">
Register multiple operational meters
</p>
</div>

<div class="stat-card">

<form method="POST">

<label>Search Meter</label>
<input type="text" id="meter_search" placeholder="Search meter number..." style="width:100%;padding:8px;">

<br><br>

<select id="inventory_unit_select" size="5" style="width:100%;">
<option value="">Select Inventory Unit</option>

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

</select>

<br><br>

<label>Selected Meters</label>
<div id="selected_meters"></div>

<br><br>

<h3>Meter Information</h3>

<label>Unit / Room</label>
<input type="text" name="unit_name" placeholder="e.g. Unit 1 / Room A" required>

<br><br>

<label>Customer</label>
<select id="customer_select" required>
<option value="">Select Customer</option>

<?php foreach($customers as $c): ?>
<option value="<?= $c['id'] ?>">
<?= $c['customer_code'] ?> — <?= htmlspecialchars($c['customer_name']) ?>
</option>
<?php endforeach; ?>

</select>

<br><br>

<label>Account / Property</label>
<select name="account_id" id="account_select" required>

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

<?php foreach($accounts as $a): ?>
<option 
value="<?= $a['id'] ?>"
data-customer="<?= $a['customer_id'] ?>"
data-municipality="<?= htmlspecialchars($a['municipality_name']) ?>"
>
<?= htmlspecialchars($a['account_name']) ?> — <?= htmlspecialchars($a['municipality_name']) ?>
</option>
<?php endforeach; ?>

</select>

<br><br>

<label>Tariff</label>
<select name="tariff_profile_id" id="tariff_select" required>

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

<?php foreach($tariffs as $t): ?>
<option 
value="<?= $t['id'] ?>"
data-municipality="<?= htmlspecialchars($t['profile_name']) ?>"
>
<?= htmlspecialchars($t['tariff_name']) ?> — <?= htmlspecialchars($t['profile_name']) ?>
</option>
<?php endforeach; ?>

</select>

<div id="tariff_preview" style="margin-top:15px;"></div>

<br><br>

<h3>Meter Charges (Per Meter)</h3>

<label style="display:block;margin-bottom:10px;">
<input type="checkbox" id="use_custom_charges" name="use_custom_charges" value="1">
Use Meter Charges
</label>

<div id="charges_container" style="display:none;">

<div class="tabs" style="margin-bottom:10px;">
<?php $i=0; foreach($groupedCharges as $category => $items): ?>
<button type="button"
class="tab-btn <?= $i===0 ? 'active' : '' ?>"
onclick="openChargeTab(event,'tab_<?= md5('meter_'.$category) ?>')">

<?= htmlspecialchars($category) ?>

</button>
<?php $i++; endforeach; ?>
</div>

<?php $i=0; foreach($groupedCharges as $category => $items): ?>

<div id="tab_<?= md5('meter_'.$category) ?>"
class="tab-content"
style="<?= $i===0 ? '' : 'display:none;' ?>">

<strong><?= htmlspecialchars($category) ?></strong>

<?php foreach($items as $c): ?>

<label style="display:block;margin-left:15px;">
<input type="checkbox" name="charges[]" value="<?= $c['id'] ?>">
<?= htmlspecialchars($c['charge_name']) ?>
(<?= $c['charge_type'] == 'percentage' ? $c['charge_value'].'%' : 'R'.$c['charge_value'] ?>)
</label>

<?php endforeach; ?>

</div>

<?php $i++; endforeach; ?>

</div>

<br><br>

<h3>Unit Charges (Per Flat / Room)</h3>

<label style="display:block;margin-bottom:10px;">
<input type="checkbox" id="use_unit_charges" name="use_unit_charges" value="1">
Apply Unit Charges
</label>

<div id="unit_charges_container" style="display:none;">

<?php foreach($groupedUnitCharges as $category => $items): ?>

<strong><?= htmlspecialchars($category) ?></strong>

<?php foreach($items as $c): ?>

<label style="display:block;margin-left:15px;">
<input type="checkbox" name="unit_charges[]" value="<?= $c['id'] ?>">
<?= htmlspecialchars($c['charge_name']) ?>
(<?= $c['charge_type'] == 'percentage' ? $c['charge_value'].'%' : 'R'.$c['charge_value'] ?>)
</label>

<?php endforeach; ?>

<?php endforeach; ?>

</div>

<br><br>

<h3>Account Charges (Per Property)</h3>

<label style="display:block;margin-bottom:10px;">
<input type="checkbox" id="use_account_charges" name="use_account_charges" value="1">
Apply Account Charges
</label>

<div id="account_charges_container" style="display:none;">

<?php foreach($groupedAccountCharges as $category => $items): ?>

<strong><?= htmlspecialchars($category) ?></strong>

<?php foreach($items as $c): ?>

<label style="display:block;margin-left:15px;">
<input type="checkbox" name="account_charges[]" value="<?= $c['id'] ?>">
<?= htmlspecialchars($c['charge_name']) ?>
(<?= $c['charge_type'] == 'percentage' ? $c['charge_value'].'%' : 'R'.$c['charge_value'] ?>)
</label>

<?php endforeach; ?>

<?php endforeach; ?>

</div>

<br><br>

<label>Status</label>
<select name="status">
<option value="ACTIVE">ACTIVE</option>
<option value="SUSPENDED">SUSPENDED</option>
<option value="DISCONNECTED">DISCONNECTED</option>
</select>

<br><br>

<button class="btn btn-primary">
Register Meter
</button>

</form>

</div>

</div>

<script>

/* SEARCH */
document.getElementById('meter_search').addEventListener('keyup', function(){

    var search = this.value.toLowerCase();
    var options = document.getElementById('inventory_unit_select').options;

    for (var i = 0; i < options.length; i++) {
        var txt = options[i].text.toLowerCase();
        options[i].style.display = txt.includes(search) ? 'block' : 'none';
    }

});

/* ADD METER */
document.getElementById('inventory_unit_select').addEventListener('change', function(){

    var selected = this.options[this.selectedIndex];
    if(!selected.value) return;

    var meterId = selected.value;
    var meterNumber = selected.getAttribute('data-meter');

    if(document.getElementById('meter_'+meterId)) return;

    var container = document.getElementById('selected_meters');

    var div = document.createElement('div');
    div.id = 'meter_' + meterId;

    div.innerHTML = `
<div style="display:flex;gap:10px;align-items:center;margin-bottom:5px;">
    <strong style="width:120px;">${meterNumber}</strong>
    <button type="button" onclick="removeMeter(${meterId})">Remove</button>
    <input type="hidden" name="inventory_unit_id[]" value="${meterId}">
</div>
`;

    container.appendChild(div);


});

/* REMOVE */
function removeMeter(id){
    var el = document.getElementById('meter_' + id);
    if(el) el.remove();
}

/* FILTER ACCOUNTS BY CUSTOMER */
document.getElementById('customer_select').addEventListener('change', function(){

    var customerId = this.value;
    var options = document.getElementById('account_select').options;

    for (var i = 0; i < options.length; i++) {

        var opt = options[i];

        if(opt.value === ""){
            opt.style.display = 'block';
            continue;
        }

        var accCustomer = opt.getAttribute('data-customer');

        opt.style.display = (accCustomer === customerId) ? 'block' : 'none';
    }

    document.getElementById('account_select').value = "";

});

/* FILTER TARIFFS */
document.getElementById('account_select').addEventListener('change', function(){

    var options = document.getElementById('tariff_select').options;

    for (var i = 0; i < options.length; i++) {
        options[i].style.display = 'block';
    }

});

/* TARIFF PREVIEW / SIMULATION */
function refreshTariffPreview(){

    var tariffId = document.getElementById('tariff_select').value;

    if(!tariffId){
        document.getElementById('tariff_preview').innerHTML = '';
        return;
    }

    let selectedCharges = [];

    document.querySelectorAll('input[name="charges[]"]:checked').forEach(cb => {
        selectedCharges.push(cb.value);
    });

    let query = 'get_tariff_blocks.php?tariff_id=' + tariffId;

    if(selectedCharges.length > 0){
        query += '&charges=' + selectedCharges.join(',');
    }

    fetch(query)
    .then(res => res.text())
    .then(html => {
        document.getElementById('tariff_preview').innerHTML = html;
    });
}

document.getElementById('tariff_select').addEventListener('change', refreshTariffPreview);

document.getElementById('use_custom_charges').addEventListener('change', function(){
    document.getElementById('charges_container').style.display = this.checked ? 'block' : 'none';
    refreshTariffPreview();
});

document.querySelectorAll('input[name="charges[]"]').forEach(function(cb){
    cb.addEventListener('change', refreshTariffPreview);
});

function openChargeTab(evt, tabId){

    var contents = document.getElementsByClassName('tab-content');
    for (var i = 0; i < contents.length; i++){
        contents[i].style.display = 'none';
    }

    var tabs = document.getElementsByClassName('tab-btn');
    for (var i = 0; i < tabs.length; i++){
        tabs[i].classList.remove('active');
    }

    document.getElementById(tabId).style.display = 'block';
    evt.currentTarget.classList.add('active');
}

document.getElementById('use_unit_charges').addEventListener('change', function(){
    document.getElementById('unit_charges_container').style.display = this.checked ? 'block' : 'none';
});

document.getElementById('use_account_charges').addEventListener('change', function(){
    document.getElementById('account_charges_container').style.display = this.checked ? 'block' : 'none';
});
</script>

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