<?php
// ============================================================
// reports.php — RBE Utilities Tenant Utility Report
// EXACT MATCH TO print_invoice.php BILLING MODEL
// ============================================================

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once __DIR__ . '/core/db_connect.php';
require_once __DIR__ . '/core/functions.php';
// Detect CSV export early so we do not render any HTML (nav/sidebar)
$action = $_GET['action'] ?? '';
$do_export_csv = ($action === 'export_csv');

if (!$do_export_csv) {
    include 'landlord-nav.php';
}

// ---------------- Access Control ----------------
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }
$user_id = (int)$_SESSION['user_id'];
$stmt = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id=? LIMIT 1");
$stmt->execute([$user_id]);
$role = $stmt->fetchColumn();
if (!in_array($role, ['admin','landlord'])) exit("Unauthorized.");
$is_admin = ($role === 'admin');
$landlord_id = $is_admin ? (int)($_GET['landlord_id'] ?? 0) : $user_id;
if (!$landlord_id) exit("landlord_id required");

// ---------------- Helpers ----------------
function calculateTieredCost(float $amount, array $tiers): float {
    if ($amount <= 0) return 0.0;
    $total = 0.0;
    foreach ($tiers as $t) {
        $from = isset($t['tier_from']) ? (float)$t['tier_from'] : 0.0;
        $to   = ($t['tier_to'] !== null) ? (float)$t['tier_to'] : INF;
        $rate = (float)($t['rate'] ?? 0.0);

        if ($to <= $from || $amount <= $from) continue;
        $billable = min($amount, $to) - $from;
        if ($billable > 0) $total += $billable * $rate;
    }
    return round($total, 2);
}
function flectoSum($r){
    return floatval($r['reg_a'] ?? 0)
         + floatval($r['reg_e'] ?? 0)
         + floatval($r['reg_f'] ?? 0)
         + floatval($r['reg_h'] ?? 0)
         + floatval($r['reg_l'] ?? 0);
}

function tiersToString(array $tiers): string {
    if (!$tiers) return '';
    $parts = [];
    foreach ($tiers as $t) {
        $from = isset($t['tier_from']) ? (float)$t['tier_from'] : 0.0;
        $toRaw = $t['tier_to'] ?? null;
        $to = ($toRaw === null || $toRaw === '') ? null : (float)$toRaw;
        $rate = (float)($t['rate'] ?? 0.0);
        $range = ($to === null) ? sprintf('%.4g+', $from) : sprintf('%.4g-%.4g', $from, $to);
        $parts[] = $range . '@' . sprintf('%.4g', $rate);
    }
    return implode('; ', $parts);
}

// ---------------- Filters ----------------
$selected_tenant_id = $_GET['tenant_id'] ?? null;
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date   = $_GET['end_date'] ?? date('Y-m-d');

// ---------------- Tenant List ----------------
$stmt = $conn_rbe->prepare("
    SELECT tlm.tenant_id, u.fullname
    FROM tenant_landlord_map tlm
    JOIN rbe_users u ON tlm.tenant_id=u.id
    WHERE tlm.landlord_id=?
");
$stmt->execute([$landlord_id]);
$tenants = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);


// ---------------- Property Map (for CSV export) ----------------
$property_map = [];
$stP = $conn_rbe->prepare("SELECT id, property_number, address FROM properties WHERE landlord_id=?");
$stP->execute([$landlord_id]);
foreach ($stP->fetchAll(PDO::FETCH_ASSOC) as $pRow) {
    $pid = (int)$pRow['id'];
    $property_map[$pid] = [
        'property_number' => (string)($pRow['property_number'] ?? ''),
        'address' => (string)($pRow['address'] ?? '')
    ];
}

// ---------------- Load fee modes ----------------
$modes = ['sewage'=>'flat','refuse'=>'flat','rates'=>'flat','other'=>'flat'];
$stmt = $conn_rbe->prepare("SELECT fee_type, mode FROM billing_fee_modes WHERE landlord_id=?");
$stmt->execute([$landlord_id]);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
    $modes[strtolower($r['fee_type'])] = $r['mode'];
}

// ---------------- Main Data Loop ----------------
$reports = [];
$total_e = 0;
$total_w = 0;

foreach ($tenants as $tid => $tname) {
    if ($selected_tenant_id && $selected_tenant_id != $tid) continue;

    $entries = [];

    // Load tiers (tenant-first precedence)
    $st = $conn_rbe->prepare("
        SELECT * FROM billing_tiers
        WHERE landlord_id=? AND (tenant_id=? OR tenant_id IS NULL)
        ORDER BY tenant_id DESC, type, tier_from
    ");
    $st->execute([$landlord_id, $tid]);
    $tiers_by_type = [];
    foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $t) {
        $type = strtolower($t['type']);
        $tiers_by_type[$type][] = $t;
    

    // Tariff strings (for CSV export)
    $tariff_e = tiersToString($tiers_by_type['electricity'] ?? []);
    $tariff_w = tiersToString($tiers_by_type['water'] ?? []);
}

    // Load tenant + global settings
    $tenant_settings = [];
    $global_settings = [];

    $qt = $conn_rbe->prepare("
        SELECT * FROM billing_settings 
        WHERE landlord_id=? AND tenant_id=? ORDER BY id DESC LIMIT 1
    ");
    $qt->execute([$landlord_id, $tid]);
    $tenant_settings = $qt->fetch(PDO::FETCH_ASSOC) ?: [];

    // detect if tenant overrides any other_fee slots
    $tenant_other_override = false;
    foreach (['other_fee','other_fee_2','other_fee_3','other_fee_4','other_fee_5'] as $col) {
        if (!empty($tenant_settings[$col])) { $tenant_other_override = true; break; }
    }

    if (!$tenant_other_override) {
        $qg = $conn_rbe->prepare("
            SELECT * FROM billing_settings 
            WHERE landlord_id=? AND tenant_id IS NULL 
            ORDER BY id DESC LIMIT 1
        ");
        $qg->execute([$landlord_id]);
        $global_settings = $qg->fetch(PDO::FETCH_ASSOC) ?: [];
    }

    // Determine tenant properties
    $qprop = $conn_rbe->prepare("
        SELECT DISTINCT property_id 
        FROM tenant_landlord_map 
        WHERE tenant_id=? AND landlord_id=?
    ");
    $qprop->execute([$tid, $landlord_id]);
    $tenant_properties = array_map('intval', $qprop->fetchAll(PDO::FETCH_COLUMN));
    if (!$tenant_properties) $tenant_properties = [null];


    $prop_numbers = [];
    $prop_addresses = [];
    foreach ($tenant_properties as $pid) {
        if ($pid && isset($property_map[$pid])) {
            $prop_numbers[] = $property_map[$pid]['property_number'];
            $prop_addresses[] = $property_map[$pid]['address'];
        }
    }
    $prop_numbers_str = implode(' | ', array_filter($prop_numbers));
    $prop_addresses_str = implode(' | ', array_filter($prop_addresses));

    // ---------------- Electricity: IAMMETER ----------------
    $q = $conn_rbe->prepare("SELECT id, serial FROM smart_meters WHERE tenant_id=?");
    $q->execute([$tid]);

    foreach ($q->fetchAll(PDO::FETCH_ASSOC) as $m) {
        $mid = $m['id'];

        // first + last timestamp with 3 phases
        $qr = $conn_rbe->prepare("
            SELECT reading_timestamp
            FROM smart_meter_readings
            WHERE meter_id=? 
              AND reading_timestamp BETWEEN ? AND ?
            GROUP BY reading_timestamp
            HAVING COUNT(DISTINCT phase)=3
            ORDER BY reading_timestamp ASC
        ");
        $qr->execute([$mid, "$start_date 00:00:00", "$end_date 23:59:59"]);
        $ts = $qr->fetchAll(PDO::FETCH_COLUMN);

        if (count($ts) >= 2) {
            $first = $ts[0];
            $last  = end($ts);

            $qr2 = $conn_rbe->prepare("
                SELECT reading_timestamp, energy_total
                FROM smart_meter_readings
                WHERE meter_id=? AND reading_timestamp IN (?,?)
            ");
            $qr2->execute([$mid, $first, $last]);
            $rows = $qr2->fetchAll(PDO::FETCH_ASSOC);

            $sum = [$first=>0.0, $last=>0.0];
            foreach ($rows as $r) {
                $sum[$r['reading_timestamp']] += (float)$r['energy_total'];
            }

            $kwh = max(0, $sum[$last] - $sum[$first]);
            $cost = calculateTieredCost($kwh, $tiers_by_type['electricity'] ?? []);

            $entries[] = [
                'tenant'=>$tname,
                'type'=>'Electricity (IAMMETER)',
                'meter'=>$m['serial'],
                'usage'=>$kwh,
                'unit'=>'kWh',
                'cost'=>$cost,
                'tariff'=>$tariff_e,
                'property_numbers'=>$prop_numbers_str,
                'property_addresses'=>$prop_addresses_str
            ];
            $total_e += $kwh;
        }
    }

    // ---------------- Electricity: FLECTO ----------------
    $q = $conn_rbe->prepare("SELECT serial_number FROM flecto_meters WHERE tenant_id=?");
    $q->execute([$tid]);

    foreach ($q->fetchAll(PDO::FETCH_COLUMN) as $serial) {
        $qA = $conn_rbe->prepare("
            SELECT * FROM flecto_meter_readings
            WHERE serial=? 
              AND created_at BETWEEN ? AND ?
            ORDER BY created_at ASC LIMIT 1
        ");
        $qB = $conn_rbe->prepare("
            SELECT * FROM flecto_meter_readings
            WHERE serial=? 
              AND created_at BETWEEN ? AND ?
            ORDER BY created_at DESC LIMIT 1
        ");
        $params = [$serial, "$start_date 00:00:00", "$end_date 23:59:59"];
        $qA->execute($params);
        $qB->execute($params);

        $a = $qA->fetch(PDO::FETCH_ASSOC);
        $b = $qB->fetch(PDO::FETCH_ASSOC);
        if ($a && $b) {
            $kwh = max(0, flectoSum($b) - flectoSum($a));
            $cost = calculateTieredCost($kwh, $tiers_by_type['electricity'] ?? []);

            $entries[] = [
                'tenant'=>$tname,
                'type'=>'Electricity (FLECTO)',
                'meter'=>$serial,
                'usage'=>$kwh,
                'unit'=>'kWh',
                'cost'=>$cost,
                'tariff'=>$tariff_e,
                'property_numbers'=>$prop_numbers_str,
                'property_addresses'=>$prop_addresses_str
            ];
            $total_e += $kwh;
        }
    }

    // ---------------- WATER (invoice-style) ----------------
    $qFirst = $conn_rbe->prepare("
        SELECT wr.volume_liters
        FROM water_meter_readings wr
        JOIN water_meters wm ON wm.serial_number=wr.serial_number
        WHERE wm.tenant_id=? 
          AND reading_datetime BETWEEN ? AND ?
        ORDER BY reading_datetime ASC
        LIMIT 1
    ");
    $qLast = $conn_rbe->prepare("
        SELECT wr.volume_liters
        FROM water_meter_readings wr
        JOIN water_meters wm ON wm.serial_number=wr.serial_number
        WHERE wm.tenant_id=? 
          AND reading_datetime BETWEEN ? AND ?
        ORDER BY reading_datetime DESC
        LIMIT 1
    ");
    $params = [$tid, "$start_date 00:00:00", "$end_date 23:59:59"];
    $qFirst->execute($params);
    $qLast->execute($params);
    $vFirst = $qFirst->fetchColumn();
    $vLast  = $qLast->fetchColumn();

    if ($vFirst !== false && $vLast !== false) {
        $kl = max(0, (float)$vLast - (float)$vFirst) / 1000.0;
        $cost = calculateTieredCost($kl, $tiers_by_type['water'] ?? []);

        $entries[] = [
            'tenant'=>$tname,
            'type'=>'Water',
            'meter'=>'-',
            'usage'=>$kl,
            'unit'=>'kl',
            'cost'=>$cost,
            'tariff'=>$tariff_w,
            'property_numbers'=>$prop_numbers_str,
            'property_addresses'=>$prop_addresses_str
        ];
        $total_w += $kl;
    }

    // ---------------- FIXED FEES ----------------
    $fee_map = [
        'sewage_fee'           => 'Sewage Fee',
        'refuse_removal_fee'   => 'Refuse Removal Fee',
        'rates_and_taxes'      => 'Rates & Taxes'
    ];

    foreach ($fee_map as $col => $label) {
        $tenant_val = floatval($tenant_settings[$col] ?? 0);

        if ($tenant_val > 0) {
            $entries[] = ['tenant'=>$tname,'type'=>$label,'meter'=>'-','usage'=>'-','unit'=>'-','cost'=>$tenant_val, 'tariff'=>'flat', 'property_numbers'=>$prop_numbers_str, 'property_addresses'=>$prop_addresses_str];
            continue;
        }

        $global_val = floatval($global_settings[$col] ?? 0);
        if ($global_val > 0) {
            $mode = $modes[str_replace('_fee','',$col)] ?? 'flat';
            $share = 0.0;

            foreach ($tenant_properties as $pid) {
                $alloc = distribute_fee($conn_rbe, $landlord_id, $global_val, $mode, $pid);
                if (isset($alloc[$tid])) $share += $alloc[$tid];
            }

            if ($share > 0) {
                $entries[] = ['tenant'=>$tname,'type'=>$label,'meter'=>'-','usage'=>'-','unit'=>'-','cost'=>$share, 'tariff'=>'distributed:' . $mode, 'property_numbers'=>$prop_numbers_str, 'property_addresses'=>$prop_addresses_str];
            }
        }
    }

    // ---------------- OTHER FEES ----------------
    if ($tenant_other_override) {
        $other_slots = [
            ['name'=>$tenant_settings['other_fee_name']   ?? '', 'amt'=>$tenant_settings['other_fee']   ?? 0],
            ['name'=>$tenant_settings['other_fee_name_2'] ?? '', 'amt'=>$tenant_settings['other_fee_2'] ?? 0],
            ['name'=>$tenant_settings['other_fee_name_3'] ?? '', 'amt'=>$tenant_settings['other_fee_3'] ?? 0],
            ['name'=>$tenant_settings['other_fee_name_4'] ?? '', 'amt'=>$tenant_settings['other_fee_4'] ?? 0],
            ['name'=>$tenant_settings['other_fee_name_5'] ?? '', 'amt'=>$tenant_settings['other_fee_5'] ?? 0],
        ];

        foreach ($other_slots as $slot) {
            if ($slot['amt'] > 0) {
                $label = trim($slot['name']) !== '' ? $slot['name'] : 'Other Fee';
                $entries[] = ['tenant'=>$tname,'type'=>$label,'meter'=>'-','usage'=>'-','unit'=>'-','cost'=>floatval($slot['amt']), 'tariff'=>'flat', 'property_numbers'=>$prop_numbers_str, 'property_addresses'=>$prop_addresses_str];
            }
        }
    } else {
        // GLOBAL distribution for other fees
        $other_global = [
            ['label'=>$global_settings['other_fee_name']   ?? 'Other Fee', 'amt'=>$global_settings['other_fee']   ?? 0],
            ['label'=>$global_settings['other_fee_name_2'] ?? 'Other Fee', 'amt'=>$global_settings['other_fee_2'] ?? 0],
            ['label'=>$global_settings['other_fee_name_3'] ?? 'Other Fee', 'amt'=>$global_settings['other_fee_3'] ?? 0],
            ['label'=>$global_settings['other_fee_name_4'] ?? 'Other Fee', 'amt'=>$global_settings['other_fee_4'] ?? 0],
            ['label'=>$global_settings['other_fee_name_5'] ?? 'Other Fee', 'amt'=>$global_settings['other_fee_5'] ?? 0],
        ];

        foreach ($other_global as $og) {
            if (($og['amt'] ?? 0) <= 0) continue;

            $share = 0.0;
            $mode = $modes['other'] ?? 'flat';

            foreach ($tenant_properties as $pid) {
                $alloc = distribute_fee($conn_rbe, $landlord_id, floatval($og['amt']), $mode, $pid);
                if (isset($alloc[$tid])) $share += $alloc[$tid];
            }

            if ($share > 0) {
                $entries[] = [
                    'tenant'=>$tname,
                    'type'=>($og['label'] ?: 'Other Fee'),
                    'meter'=>'-',
                    'usage'=>'-',
                    'unit'=>'-',
                    'cost'=>$share,
                    'tariff'=>'distributed:' . $mode,
                    'property_numbers'=>$prop_numbers_str,
                    'property_addresses'=>$prop_addresses_str
                ];
            }
        }
    }

    // ---------------- EXTRA FEES ----------------
    $qEf = $conn_rbe->prepare("
        SELECT fee_type, custom_label, amount
        FROM extra_fees
        WHERE tenant_id=? AND landlord_id=? AND active=1
    ");
    $qEf->execute([$tid, $landlord_id]);

    foreach ($qEf->fetchAll(PDO::FETCH_ASSOC) as $ef) {
        $label = trim($ef['custom_label'] ?? '');
        if ($label === '') {
            switch (strtolower($ef['fee_type'])) {
                case 'aircon_fee':      $label='Aircon Fee'; break;
                case 'generator_fee':   $label='Generator Fee'; break;
                case 'elec_avail_fee':  $label='Electricity Availability Fee'; break;
                case 'elec_basic_fee':  $label='Electricity Basic Fee'; break;
                case 'water_avail_fee': $label='Water Availability Fee'; break;
                case 'water_basic_fee': $label='Water Basic Fee'; break;
                default: $label='Extra Fee';
            }
        }

        $entries[] = [
            'tenant'=>$tname,
            'type'=>$label,
            'meter'=>'-',
            'usage'=>'-',
            'unit'=>'-',
            'cost'=>floatval($ef['amount']),
            'tariff'=>'flat',
            'property_numbers'=>$prop_numbers_str,
            'property_addresses'=>$prop_addresses_str
        ];
    }

    // ✔ Save tenant block
    $reports[$tid] = $entries;
}



// ---------------- CSV Export ----------------
if ($do_export_csv) {
    // Landlord name (for metadata)
    $stL = $conn_rbe->prepare('SELECT fullname FROM rbe_users WHERE id=? LIMIT 1');
    $stL->execute([$landlord_id]);
    $landlord_name = (string)($stL->fetchColumn() ?: '');

    $filename = sprintf('utility_report_landlord_%d_%s_to_%s.csv', $landlord_id, $start_date, $end_date);

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Pragma: no-cache');
    header('Expires: 0');

    $out = fopen('php://output', 'w');

    // Excel-friendly UTF-8 BOM
    fwrite($out, "\xEF\xBB\xBF");

    fputcsv($out, [
        'Landlord ID',
        'Landlord Name',
        'Tenant ID',
        'Tenant Name',
        'Property Numbers',
        'Property Addresses',
        'Period Start',
        'Period End',
        'Item Type',
        'Meter',
        'Usage',
        'Unit',
        'Tariff/Tiers',
        'Cost (R)',
        'Tenant Total (R)'
    ]);

    $grand_total = 0.0;

    foreach ($reports as $tid => $entries) {
        $tenant_total = 0.0;
        foreach ($entries as $e) {
            $tenant_total += (float)($e['cost'] ?? 0);
        }
        $tenant_total = round($tenant_total, 2);
        $grand_total += $tenant_total;

        foreach ($entries as $e) {
            $usage = $e['usage'] ?? '';
            if (is_numeric($usage)) $usage = round((float)$usage, 4);

            fputcsv($out, [
                $landlord_id,
                $landlord_name,
                $tid,
                (string)($e['tenant'] ?? ''),
                (string)($e['property_numbers'] ?? ''),
                (string)($e['property_addresses'] ?? ''),
                $start_date,
                $end_date,
                (string)($e['type'] ?? ''),
                (string)($e['meter'] ?? ''),
                $usage,
                (string)($e['unit'] ?? ''),
                (string)($e['tariff'] ?? ''),
                number_format((float)($e['cost'] ?? 0), 2, '.', ''),
                number_format($tenant_total, 2, '.', '')
            ]);
        }

        // Tenant summary line
        fputcsv($out, [
            $landlord_id,
            $landlord_name,
            $tid,
            (string)($entries[0]['tenant'] ?? ''),
            (string)($entries[0]['property_numbers'] ?? ''),
            (string)($entries[0]['property_addresses'] ?? ''),
            $start_date,
            $end_date,
            'TOTAL',
            '',
            '',
            '',
            '',
            number_format($tenant_total, 2, '.', ''),
            number_format($tenant_total, 2, '.', '')
        ]);
    }

    // Grand total line
    fputcsv($out, []);
    fputcsv($out, ['GRAND TOTAL', '', '', '', '', '', $start_date, $end_date, '', '', '', '', '', number_format(round($grand_total, 2), 2, '.', ''), '']);

    fclose($out);
    exit;
}

// ---------------- END PHP ----------------
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tenant Utility Reports — RBE Utilities</title>
<style>
/* ==========================================================
   RBE Utilities Tenant Report Inline Styles
   Version 2.0 — Standalone (no external CSS)
   ========================================================== */

body {
  margin: 0;
  padding: 0;
  font-family: 'Inter', 'Segoe UI', sans-serif;
  background: #041622;
  color: #e6f5ff;
  min-height: 100vh;
}

.container {
  margin-left: 260px;
  padding: 40px;
}

/* ------------------ Summary Cards ------------------ */
.summary {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 30px;
}

.summary .card {
  flex: 1;
  background: #0b2333;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 0 18px rgba(0, 0, 0, 0.4);
  text-align: center;
  transition: 0.25s ease;
}
.summary .card:hover {
  box-shadow: 0 0 25px rgba(0, 204, 255, 0.15);
}
.summary .card h3 {
  color: #00ccff;
  margin-bottom: 10px;
}
.summary .card p {
  font-size: 1.3em;
  font-weight: 600;
  color: #7ed957;
}

/* ------------------ Tenant Section ------------------ */
.tenant-section {
  background: #0b2333;
  border-radius: 12px;
  margin-bottom: 30px;
  box-shadow: 0 0 18px rgba(0, 0, 0, 0.4);
  overflow: hidden;
  transition: 0.3s ease;
}

.tenant-header {
  background: #072236;
  padding: 14px 18px;
  color: #00ccff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  font-weight: 600;
  letter-spacing: 0.3px;
  transition: 0.2s ease;
}
.tenant-header:hover {
  background: rgba(0, 204, 255, 0.15);
}

.tenant-body {
  padding: 18px;
  display: none;
  animation: fadeIn 0.3s ease;
}
.tenant-section.active .tenant-body {
  display: block;
}

/* ------------------ Tables ------------------ */
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
  font-size: 14.5px;
}

th, td {
  padding: 10px 12px;
  border: 1px solid rgba(255, 255, 255, 0.08);
  text-align: center;
}

th {
  background: #072236;
  color: #00ccff;
  font-weight: 600;
}

tr:nth-child(even) {
  background: rgba(255, 255, 255, 0.03);
}

tr:hover {
  background: rgba(0, 204, 255, 0.05);
}

/* ------------------ Buttons ------------------ */
.btn {
  display: inline-block;
  background: #7ed957;
  color: #000;
  border: none;
  border-radius: 10px;
  padding: 10px 16px;
  font-weight: 600;
  font-size: 14px;
  text-decoration: none;
  cursor: pointer;
  margin-top: 10px;
  transition: 0.25s ease;
}
.btn:hover {
  background: #a8f77b;
  transform: translateY(-1px);
}

/* ------------------ Final Total ------------------ */
.final-total {
  text-align: center;
  font-size: 1.2em;
  background: #0b2333;
  color: #7ed957;
  padding: 16px 24px;
  border-radius: 12px;
  font-weight: 600;
  box-shadow: 0 0 15px rgba(0, 204, 255, 0.15);
}

/* ------------------ Animations ------------------ */
@keyframes fadeIn {
  from { opacity: 0; transform: scale(0.98); }
  to { opacity: 1; transform: scale(1); }
}

/* ------------------ Responsive ------------------ */
@media (max-width: 900px) {
  .container {
    margin-left: 0;
    padding: 20px;
  }
  .summary {
    flex-direction: column;
  }
  table {
    font-size: 13.5px;
  }
}
</style>

</head>
<body>
<div class="container">

<h1>📊 Tenant Utility Reports</h1>

<!-- 🔥 PERIOD FILTER (NEW, CLEAN, MATCHING YOUR UI) -->
<form method="get" style="margin-bottom:25px; display:flex; gap:12px;">
    <?php if ($is_admin): ?>
        <input type="hidden" name="landlord_id" value="<?= htmlspecialchars($landlord_id) ?>">
    <?php endif; ?>

    <select name="tenant_id">
        <option value="">All Tenants</option>
        <?php foreach($tenants as $id=>$name): ?>
            <option value="<?= $id ?>" <?= ($selected_tenant_id==$id?'selected':'') ?>>
                <?= htmlspecialchars($name) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <input type="date" name="start_date" value="<?= $start_date ?>">
    <input type="date" name="end_date" value="<?= $end_date ?>">
    
    <button class="btn" name="action" value="apply">Apply</button>
    <button class="btn" name="action" value="export_csv">Export to CSV</button>
</form>


<div class="summary">
  <div class="card"><h3>⚡ Electricity</h3><p><?= round($total_e,2) ?> kWh</p></div>
  <div class="card"><h3>💧 Water</h3><p><?= round($total_w,2) ?> kl</p></div>
</div>

<?php if(!$reports): ?>
  <div class="card" style="text-align:center;">No report data</div>

<?php else: ?>
  <?php foreach($reports as $tid=>$entries): ?>
    <div class="tenant-section active">
      <div class="tenant-header" onclick="this.parentNode.classList.toggle('active')">
        👤 <?= htmlspecialchars($entries[0]['tenant']) ?>
        <span>💰 Total: R<?= number_format(array_sum(array_column($entries,'cost')),2) ?></span>
      </div>

      <div class="tenant-body">
        <table>
          <thead>
            <tr>
              <th>Type</th><th>Meter</th><th>Usage</th><th>Unit</th><th>Cost (R)</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($entries as $r): ?>
              <tr>
                <td><?= htmlspecialchars($r['type']) ?></td>
                <td><?= htmlspecialchars($r['meter']) ?></td>
                <td><?= is_numeric($r['usage']) ? round($r['usage'],2) : '-' ?></td>
                <td><?= htmlspecialchars($r['unit']) ?></td>
                <td><?= number_format($r['cost'],2) ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>

        <a href="print_invoice.php?tenant_id=<?= $tid ?>&start_date=<?= $start_date ?>&end_date=<?= $end_date ?>" class="btn">
          🧾 Print Bill
        </a>
      </div>
    </div>
  <?php endforeach; ?>
<?php endif; ?>

<div class="card" style="text-align:center;font-weight:600;">
  ✅ Grand Total:  
  R<?= number_format(array_sum(array_column(array_merge(...array_values($reports)),'cost')),2) ?>
</div>

</div>

<script>
// expand all by default
document.querySelectorAll('.tenant-section').forEach(sec => sec.classList.add('active'));
</script>

</body>
</html>