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

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

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

$companyId = $_SESSION['company_id'];

$periodId = isset($_GET['period_id']) ? (int)$_GET['period_id'] : 0;

if(!$periodId){
    die("Missing period_id");
}

/* ===============================
   FETCH PERIOD
================================= */
$stmt = $pdo->prepare("
SELECT * FROM billing_periods
WHERE id = ? AND company_id = ?
");
$stmt->execute([$periodId,$companyId]);
$period = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$period){
    die("Invalid period");
}

/* ===============================
   FETCH METERS
================================= */
$stmt = $pdo->prepare("
SELECT id, meter_number, tariff_id, tariff_profile_id
FROM operational_meters
WHERE status = 'ACTIVE'
");
$stmt->execute();
$meters = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<div class="container">
<h2>Billing Preview</h2>

<table style="width:100%;border-collapse:collapse;">
<thead>
<tr>
<th>Meter</th>
<th>Usage</th>
<th>Tariff Cost</th>
<th>Charges</th>
<th>Total</th>
</tr>
</thead>

<tbody>

<?php foreach($meters as $m): ?>

<?php

/* ===============================
   GET START READING (BEFORE PERIOD)
================================= */
$stmt = $pdo->prepare("
SELECT reading_value
FROM meter_readings
WHERE meter_id = ?
AND reading_date < ?
ORDER BY reading_date DESC, id DESC
LIMIT 1
");
$stmt->execute([$m['id'],$period['period_start']]);
$start = $stmt->fetchColumn();

/* ===============================
   GET END READING (UP TO PERIOD END)
================================= */
$stmt = $pdo->prepare("
SELECT reading_value
FROM meter_readings
WHERE meter_id = ?
AND reading_date <= ?
ORDER BY reading_date DESC, id DESC
LIMIT 1
");
$stmt->execute([$m['id'],$period['period_end']]);
$end = $stmt->fetchColumn();

if($end === false){
    continue;
}

if($start === false){
    $start = 0;
}

$usage = (float)$end - (float)$start;

/* SAFETY: prevent negative usage */
if($usage < 0){
    $usage = 0;
}

/* ===============================
   TARIFF
================================= */
if(empty($m['tariff_id'])){
    continue;
}

if($usage <= 0){

    $tariffTotal = 0;

}else{

  $profileId = $m['tariff_profile_id'];

if(empty($profileId)){
    echo "<tr><td colspan='5' style='color:red;'>
    Meter {$m['meter_number']} has no tariff profile assigned
    </td></tr>";
    continue;
}

    $calc = calculateBlockBillByProfile($pdo, $profileId, $usage);

    $tariffTotal = 0;

    foreach($calc['breakdown'] as $row){
        $tariffTotal += $row['amount'];
    }

}

/* ===============================
   CHARGES
================================= */
$stmt = $pdo->prepare("
SELECT bc.charge_name, bc.charge_type, bc.charge_value
FROM meter_charges mc
JOIN billing_charges bc ON bc.id = mc.charge_id
WHERE mc.meter_id = ?
AND bc.active = 1
");
$stmt->execute([$m['id']]);

$chargesTotal = 0;

while($c = $stmt->fetch(PDO::FETCH_ASSOC)){

    if($c['charge_type'] === 'percentage'){
        $amount = $tariffTotal * ($c['charge_value']/100);
    }else{
        $amount = $c['charge_value'];
    }

    $chargesTotal += $amount;
}

$total = $tariffTotal + $chargesTotal;

?>

<tr>
<td><?= htmlspecialchars($m['meter_number']) ?></td>
<td><?= number_format($usage,3) ?></td>
<td><?= number_format($tariffTotal,2) ?></td>
<td><?= number_format($chargesTotal,2) ?></td>
<td><b><?= number_format($total,2) ?></b></td>
</tr>

<?php endforeach; ?>

</tbody>
</table>

</div>

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