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

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

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

/* ===============================
GET CONTEXT
================================ */
$type = $_GET['type'] ?? ''; // meter | account
$id   = (int)($_GET['id'] ?? 0);

/* ===============================
LOAD LEFT PANEL DATA
================================ */

/* METERS */
$meters = $pdo->query("
SELECT id, meter_number
FROM operational_meters
WHERE status='ACTIVE'
ORDER BY meter_number
")->fetchAll(PDO::FETCH_ASSOC);

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

/* ===============================
LOAD RIGHT PANEL DATA
================================ */

$selectedTitle = "Select item to manage";

/* LOAD METER CHARGES */
if($type === 'meter' && $id){

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

    if($meter){
        $selectedTitle = "Manage Meter Charges (".$meter['meter_number'].")";
    }

    $stmt = $pdo->prepare("
    SELECT c.*
    FROM meter_charges mc
    JOIN billing_charges c ON c.id = mc.charge_id
    WHERE mc.meter_id = ?
    ");
    $stmt->execute([$id]);
    $assigned = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("
    SELECT *
    FROM billing_charges
    WHERE active=1
    AND id NOT IN (
        SELECT charge_id FROM meter_charges WHERE meter_id=?
    )
    ORDER BY charge_name
    ");
    $stmt->execute([$id]);
    $available = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

/* LOAD ACCOUNT CHARGES */
if($type === 'account' && $id){

    $stmt = $pdo->prepare("
    SELECT account_name FROM billing_accounts WHERE id=?
    ");
    $stmt->execute([$id]);
    $account = $stmt->fetch(PDO::FETCH_ASSOC);

    if($account){
        $selectedTitle = "Manage Unit Charges (".$account['account_name'].")";
    }

    $stmt = $pdo->prepare("
    SELECT c.*
    FROM account_charges ac
    JOIN billing_charges c ON c.id = ac.charge_id
    WHERE ac.account_id = ?
    ");
    $stmt->execute([$id]);
    $assigned = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("
    SELECT *
    FROM billing_charges
    WHERE active=1
    AND applies_to='ACCOUNT'
    AND id NOT IN (
        SELECT charge_id FROM account_charges WHERE account_id=?
    )
    ORDER BY charge_name
    ");
    $stmt->execute([$id]);
    $available = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

/* ===============================
ADD CHARGE
================================ */
if($_SERVER['REQUEST_METHOD'] === 'POST'){

    $chargeId = (int)$_POST['charge_id'];

    if($type === 'meter'){
        $stmt = $pdo->prepare("
        INSERT INTO meter_charges (meter_id,charge_id,start_date)
        VALUES (?,?,CURDATE())
        ");
        $stmt->execute([$id,$chargeId]);
    }

    if($type === 'account'){
        $stmt = $pdo->prepare("
        INSERT INTO account_charges (account_id,charge_id,start_date)
        VALUES (?,?,CURDATE())
        ");
        $stmt->execute([$id,$chargeId]);
    }

    header("Location: ?type=$type&id=$id");
    exit;
}

/* ===============================
REMOVE CHARGE
================================ */
if(isset($_GET['remove'])){

    $chargeId = (int)$_GET['remove'];

    if($type === 'meter'){
        $stmt = $pdo->prepare("
        DELETE FROM meter_charges
        WHERE meter_id=? AND charge_id=?
        ");
        $stmt->execute([$id,$chargeId]);
    }

    if($type === 'account'){
        $stmt = $pdo->prepare("
        DELETE FROM account_charges
        WHERE account_id=? AND charge_id=?
        ");
        $stmt->execute([$id,$chargeId]);
    }

    header("Location: ?type=$type&id=$id");
    exit;
}

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

<div class="container">

<div style="display:flex; gap:20px;">

<!-- LEFT PANEL -->
<div style="width:30%;">

<h3>Meters</h3>

<?php foreach($meters as $m): ?>
<div style="padding:10px; border-bottom:1px solid #eee;">
<a href="?type=meter&id=<?= $m['id'] ?>">
<?= htmlspecialchars($m['meter_number']) ?>
</a>
</div>
<?php endforeach; ?>

<br>

<h3>Accounts / Units</h3>

<?php foreach($accounts as $a): ?>
<div style="padding:10px; border-bottom:1px solid #eee;">
<a href="?type=account&id=<?= $a['id'] ?>">
<?= htmlspecialchars($a['account_name']) ?>
</a>
</div>
<?php endforeach; ?>

</div>

<!-- RIGHT PANEL -->
<div style="width:70%;">

<h2><?= $selectedTitle ?></h2>

<?php if($type && $id): ?>

<h3>Assigned Charges</h3>

<table border="1" width="100%">
<tr>
<th>Name</th>
<th>Type</th>
<th>Value</th>
<th>Action</th>
</tr>

<?php if(empty($assigned)): ?>
<tr><td colspan="4">No charges assigned</td></tr>
<?php endif; ?>

<?php foreach($assigned as $c): ?>
<tr>
<td><?= htmlspecialchars($c['charge_name']) ?></td>
<td><?= $c['charge_type'] ?></td>
<td>
<?= $c['charge_type']=='percentage'
? $c['charge_value'].'%'
: 'R'.number_format($c['charge_value'],2) ?>
</td>
<td>
<a href="?type=<?= $type ?>&id=<?= $id ?>&remove=<?= $c['id'] ?>"
style="color:red;"
onclick="return confirm('Remove?')">
Remove
</a>
</td>
</tr>
<?php endforeach; ?>

</table>

<br>

<h3>Add Charge</h3>

<form method="POST">
<select name="charge_id" required>
<option value="">Select Charge</option>

<?php foreach($available as $c): ?>
<option value="<?= $c['id'] ?>">
<?= htmlspecialchars($c['charge_name']) ?>
</option>
<?php endforeach; ?>

</select>

<br><br>
<button class="btn btn-primary">Add</button>
</form>

<?php else: ?>

<p>Select a meter or account to manage charges.</p>

<?php endif; ?>

</div>

</div>

</div>

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