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

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

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

$meterId = $_GET['meter_id'] ?? 0;

if(!$meterId){
    die("Missing meter_id");
}

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

if(!$meter){
    die("Meter not found");
}

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

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

    $stmt = $pdo->prepare("
    DELETE FROM meter_charges
    WHERE meter_id = ? AND charge_id = ?
    ");
    $stmt->execute([$meterId,$chargeId]);

    header("Location: manage_charges.php?meter_id=".$meterId);
    exit;
}

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

    $chargeId = $_POST['charge_id'] ?? null;

    if($chargeId){

        // VALIDATE METER CHARGE ONLY
        $checkType = $pdo->prepare("
        SELECT id FROM billing_charges 
        WHERE id = ? AND applies_to = 'METER'
        ");
        $checkType->execute([$chargeId]);

        if(!$checkType->fetch()){
            die("Invalid charge type");
        }

        // prevent duplicate
        $check = $pdo->prepare("
        SELECT 1 FROM meter_charges
        WHERE meter_id = ? AND charge_id = ?
        ");
        $check->execute([$meterId,$chargeId]);

        if(!$check->fetch()){

            $stmt = $pdo->prepare("
            INSERT INTO meter_charges (meter_id, charge_id, start_date)
            VALUES (?,?,CURDATE())
            ");
            $stmt->execute([$meterId,$chargeId]);

        }
    }

    header("Location: manage_charges.php?meter_id=".$meterId);
    exit;
}

/* ======================
LOAD ASSIGNED CHARGES
====================== */
$stmt = $pdo->prepare("
SELECT mc.charge_id, c.charge_name, c.charge_type, c.charge_value
FROM meter_charges mc
JOIN billing_charges c ON c.id = mc.charge_id
AND c.applies_to = 'METER'
WHERE mc.meter_id = ?
");
$stmt->execute([$meterId]);
$assigned = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ======================
LOAD AVAILABLE CHARGES
====================== */
$stmt = $pdo->prepare("
SELECT id, charge_name, charge_type, charge_value
FROM billing_charges
WHERE active = 1
AND applies_to = 'METER'
AND id NOT IN (
    SELECT charge_id FROM meter_charges WHERE meter_id = ?
)
ORDER BY charge_name
");
$stmt->execute([$meterId]);
$available = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<div class="container">

<h2>Manage Meter Charges</h2>
<p><strong>Meter:</strong> <?= htmlspecialchars($meter['meter_number']) ?></p>

<h3>Assigned Charges</h3>

<p style="color:#6b7280;margin-bottom:10px;">
These charges are applied directly to this meter and will be included in billing calculations.
</p>

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

<?php if(empty($assigned)): ?>
<tr>
<td colspan="4" style="text-align:center;color:#999;">
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="?meter_id=<?= $meterId ?>&remove=<?= $c['charge_id'] ?>" 
style="color:red;"
onclick="return confirm('Remove this charge?')">
Remove
</a>
</td>
</tr>
<?php endforeach; ?>

</table>

<br>

<h3>Add Charge</h3>

<p style="color:#6b7280;margin-bottom:10px;">
Select a meter-level charge to assign. Only charges configured for meters are shown.
</p>

<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']) ?> 
(<?= $c['charge_type']=='percentage' ? $c['charge_value'].'%' : 'R'.$c['charge_value'] ?>)
</option>
<?php endforeach; ?>

</select>

<br><br>

<button class="btn btn-primary">Add Charge</button>

</form>

</div>

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