<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once __DIR__.'/../../config/database.php';

$tariffId = $_GET['tariff_id'] ?? 0;
$selectedCharges = [];

if(!empty($_GET['charges'])){
    $selectedCharges = explode(',', $_GET['charges']);
}
if(!$tariffId){
    exit;
}

$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([$tariffId]);

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

/* ===============================
LOAD CHARGES
================================ */

if(!empty($selectedCharges)){

    $placeholders = implode(',', array_fill(0, count($selectedCharges), '?'));

    $stmt = $pdo->prepare("
        SELECT 
        c.charge_name,
        c.charge_type,
        c.amount,
        cat.name AS category
        FROM charges c
        LEFT JOIN charge_categories cat ON c.category_id = cat.id
        WHERE c.id IN ($placeholders)
        ORDER BY cat.name, c.charge_name
    ");

    $stmt->execute($selectedCharges);
    $charges = $stmt->fetchAll(PDO::FETCH_ASSOC);

}else{
    $charges = [];
}

$groupedCharges = [];

foreach($charges as $c){
    $groupedCharges[$c['category']][] = $c;
}
if(!$blocks){
    echo "<div style='color:#999;'>No tariff blocks configured</div>";
    exit;
}

echo "<div style='border:1px solid #eee;border-radius:8px;padding:10px;'>";

echo "<strong>Tariff Pricing</strong>";

echo "<table style='width:100%;margin-top:10px;'>";

echo "<tr>
<th style='text-align:left;'>Units</th>
<th style='text-align:right;'>Price</th>
</tr>";

foreach($blocks as $b){

$range = $b['block_from']." - ".$b['block_to'];

echo "<tr>
<td>$range</td>
<td style='text-align:right;'>R".number_format($b['price_per_unit'],2)."</td>
</tr>";

}

echo "</table>";

echo "</div>";
echo "<br>";

echo "<div style='border:1px solid #eee;border-radius:8px;padding:10px;'>";

echo "<strong>Charges</strong>";

foreach($groupedCharges as $category => $items){

    echo "<div style='margin-top:10px;'>";
    echo "<strong>".$category."</strong><br>";

    foreach($items as $c){

        if($c['charge_type'] == 'percentage'){
            echo "- ".$c['charge_name']." (".$c['amount']."%)<br>";
        }else{
            echo "- ".$c['charge_name']." (R".number_format($c['amount'],2).")<br>";
        }

    }

    echo "</div>";
}

echo "</div>";
/* ===============================
CALCULATION PREVIEW
================================ */

$usageUnits = 10;
$total = 0;
$tariffCost = 0;

/* CALCULATE TARIFF (TIERED) */

$remainingUnits = $usageUnits;
$tariffCost = 0;

foreach($blocks as $b){

    if($remainingUnits <= 0) break;

    $blockStart = $b['block_from'];
    $blockEnd   = $b['block_to'];
    $blockSize  = $blockEnd - $blockStart + 1;

    // units to charge in this block
    $unitsInBlock = min($remainingUnits, $blockSize);

    $cost = $unitsInBlock * $b['price_per_unit'];

    $tariffCost += $cost;
    $remainingUnits -= $unitsInBlock;

}
$total += $tariffCost;

/* APPLY CHARGES */
$chargeBreakdown = [];

foreach($charges as $c){

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

    $total += $amount;

    $chargeBreakdown[] = [
        'name' => $c['charge_name'],
        'amount' => $amount
    ];
}

/* DISPLAY RESULT */

echo "<div style='border:2px solid #f2531e;border-radius:8px;padding:10px;margin-top:15px;'>";

echo "<strong>Calculation Preview (10 Units)</strong><br><br>";

echo "Tariff Cost (Tiered): R".number_format($tariffCost,2)."<br>";

foreach($chargeBreakdown as $cb){
    echo $cb['name'].": R".number_format($cb['amount'],2)."<br>";
}

echo "<br><strong>Total: R".number_format($total,2)."</strong>";

echo "</div>";