<?php

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

/* ===============================
   INPUT
================================ */

$invoiceId = (int)$invoice['id'];
$usage = (float)$usage;

/* ===============================
   LOAD TARIFF BLOCKS
================================ */

$stmt = $pdo->prepare("
SELECT *
FROM tariff_blocks
WHERE tariff_id = ?
ORDER BY block_from ASC
");

$stmt->execute([$invoice['tariff_id']]);

$blocks = $stmt->fetchAll(PDO::FETCH_ASSOC);

$remaining = $usage;

foreach($blocks as $block){

$from = (float)$block['block_from'];
$to = $block['block_to'];
$rate = (float)$block['rate'];

if($remaining <= 0) break;

if($to === null){

$units = $remaining;

}else{

$range = $to - $from;

$units = min($remaining,$range);

}

$amount = $units * $rate;

$stmt = $pdo->prepare("
INSERT INTO invoice_lines
(invoice_id,description,quantity,unit_price,total)
VALUES (?,?,?,?,?)
");

$stmt->execute([
$invoiceId,
"Usage ".$from." - ".($to ?? '+'),
$units,
$rate,
$amount
]);

$remaining -= $units;

}
/* ===============================
   ADD BILLING 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([$invoice['meter_id']]);
$charges = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* Get current subtotal (usage only) */
$stmt = $pdo->prepare("
SELECT COALESCE(SUM(total),0) as subtotal
FROM invoice_lines
WHERE invoice_id = ?
");
$stmt->execute([$invoiceId]);

$row = $stmt->fetch(PDO::FETCH_ASSOC);
$subtotal = (float)$row['subtotal'];

foreach($charges as $charge){

    if($charge['charge_type'] == 'percentage'){
        $amount = ($subtotal * $charge['charge_value']) / 100;
    } else {
        $amount = (float)$charge['charge_value'];
    }

    $stmt = $pdo->prepare("
    INSERT INTO invoice_lines
    (invoice_id,description,quantity,unit_price,total)
    VALUES (?,?,?,?,?)
    ");

    $stmt->execute([
        $invoiceId,
        $charge['charge_name'],
        1,
        $amount,
        $amount
    ]);
}