<?php

/* =========================================================
   MAIN FUNCTION (USED BY OLD SYSTEM - STILL WORKS)
========================================================= */
function calculateBlockBill(PDO $pdo, int $tariffId, float $consumption): array
{
    return calculateBlockBillByProfile($pdo, 1, $consumption);
}


/* =========================================================
   NEW PROFILE-BASED FUNCTION (YOUR SYSTEM USES THIS)
========================================================= */
function calculateBlockBillByProfile(PDO $pdo, int $profileId, float $consumption): array
{

    /* ===============================
       LOAD BLOCKS BY PROFILE
    ================================= */
    $stmt = $pdo->prepare("
        SELECT block_from, block_to, price_per_unit
        FROM tariff_blocks
        WHERE tariff_profile_id = ?
        ORDER BY block_from ASC
    ");

    $stmt->execute([$profileId]);
    $blocks = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $total = 0;
    $breakdown = [];
    $remaining = $consumption;

    /* ===============================
       BLOCK CALCULATION (TIERED)
    ================================= */

    foreach ($blocks as $block) {

        $from = (float)$block['block_from'];
        $to   = $block['block_to'] !== null ? (float)$block['block_to'] : null;
        $rate = (float)$block['price_per_unit'];

        if ($remaining <= 0) break;

        if ($consumption <= $from) {
            continue;
        }

        if ($to === null) {
            $unitsInBlock = $remaining;
            $label = $from . '+';
        } else {
            $blockRange = $to - $from;
            $unitsInBlock = min($remaining, $blockRange);
            $label = $from . ' - ' . $to;
        }

        if ($unitsInBlock <= 0) {
            continue;
        }

        $amount = round($unitsInBlock * $rate, 2);

        $breakdown[] = [
            'label'  => $label,
            'units'  => $unitsInBlock,
            'rate'   => $rate,
            'amount' => $amount
        ];

        $total += $amount;
        $remaining -= $unitsInBlock;
    }

    return [
        'total' => round($total,2),
        'breakdown' => $breakdown
    ];
}