<?php
require_once __DIR__ . '/core/db_connect.php';
require_once __DIR__ . '/core/functions.php';
require_once __DIR__ . '/core/invoice_engine.php'; // 🔥 NEW central engine
include 'landlord-nav.php';

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

// -----------------------------------------
// INPUTS
// -----------------------------------------
$tenant_id = isset($_GET['tenant_id']) ? (int)$_GET['tenant_id'] : 0;
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date   = $_GET['end_date']   ?? date('Y-m-d');

if ($tenant_id <= 0) {
    die("Invalid tenant_id.");
}

// -----------------------------------------
// LOAD INVOICE VIA ENGINE
// -----------------------------------------
$invoice = calculate_invoice($conn_rbe, $tenant_id, $start_date, $end_date);

if (isset($invoice['error'])) {
    die("Invoice Engine Error: " . htmlspecialchars($invoice['error']));
}

// Extract values for easy use
$tenant_name = $invoice['tenant']['name'];
$landlord_id = $invoice['tenant']['landlord_id'];
$lines       = $invoice['lines'];
$total_due   = $invoice['totals']['grand_total'];

// Fee mode legend (needed for invoice UI)
$modes = [
    'sewage' => 'flat',
    'refuse' => 'flat',
    'rates'  => 'flat',
    'other'  => 'flat'
];
$st = $conn_rbe->prepare("SELECT fee_type, mode FROM billing_fee_modes WHERE landlord_id = ?");
$st->execute([$landlord_id]);
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $modes[strtolower($row['fee_type'])] = $row['mode'];
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>RBE Utility Report</title>
<link rel="stylesheet" href="/assets/css/theme.css">
<style>
  :root {
    --page-w: 210mm;
    --page-h: 297mm;
    --pad: 10mm;         /* inner padding on print */
  }

  body {
    font-family: Arial, sans-serif;
    margin: 0;
    background: #f9f9f9;
    color: #051a25;
  }

  .invoice-wrapper {
    max-width: 1100px;
    margin: 50px 260px;
    background: #fff;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 0 15px rgba(0,0,0,0.1);
  }

  .invoice-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 3px solid #7ed957;
    padding-bottom: 16px;
    margin-bottom: 16px;
  }

  .logo { max-height: 80px; }

  .invoice-summary {
    display: flex;
    justify-content: space-between;
    gap: 16px;
    background: #051a25;
    color: #fff;
    padding: 16px;
    border-radius: 8px;
    margin-bottom: 16px;
  }
  .invoice-summary h2, .invoice-summary h3 { margin: 0 0 8px 0; color: #7ed957; }

  .invoice-table { width: 100%; border-collapse: collapse; margin-bottom: 12px; }
  .invoice-table thead { background: #7ed957; color: #051a25; }
  .invoice-table th, .invoice-table td { padding: 10px 12px; text-align: left; border-bottom: 1px solid #ddd; }
  .invoice-table tfoot { font-weight: bold; background: #051a25; color: #7ed957; }
  .total-label, .total-amount { text-align: right; }

  .invoice-footer { text-align: center; font-size: 0.9em; color: #777; border-top: 1px solid #eee; padding-top: 10px; }

  /* ===== PRINT (A4, one page, no browser margins) ===== */
  @media print {
    @page { size: A4 portrait; margin: 0; }   /* browser margins = 0 */

    html, body { width: var(--page-w); height: var(--page-h); background: #fff; }
    body { margin: 0 !important; }

    /* Remove UI-only bits */
    .no-print { display: none !important; }

    /* Fit everything neatly on one page */
    .invoice-wrapper {
      width: var(--page-w);
      min-height: var(--page-h);
      margin: 0 !important;
      padding: var(--pad);
      box-shadow: none !important;
      border-radius: 0 !important;

      /* Compact mode: shrink slightly for safety; tweak if needed */
      font-size: 11px;
      line-height: 1.2;
    }

    .invoice-header { padding-bottom: 8px; margin-bottom: 8px; border-bottom-width: 2px; }
    .logo { max-height: 48px; }

    .invoice-summary { padding: 10px; gap: 10px; }
    .invoice-summary h2, .invoice-summary h3 { margin-bottom: 6px; }

    .invoice-table th, .invoice-table td { padding: 6px 8px; }
    .invoice-table th { font-size: 12px; }
    .invoice-table td { font-size: 11px; }

    /* Avoid unintended page breaks; keep whole doc together */
    .invoice-wrapper,
    .invoice-summary,
    .invoice-table,
    .invoice-table thead,
    .invoice-table tbody,
    .invoice-table tfoot,
    .invoice-table tr,
    .invoice-table td,
    .invoice-table th {
      page-break-inside: avoid !important;
    }

    /* Ensure brand colors print nicely */
    * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }

    /* Last-resort scaling if content still tries to spill:
       If you have LOTS of rows, lower zoom to 0.85/0.80. */
    .invoice-wrapper { zoom: 0.90; }
  }

  /* Fallback for browsers that ignore zoom in @media print (e.g., some Firefox versions) */
  @supports not (zoom: 1) {
    @media print {
      .invoice-wrapper {
        transform: scale(0.90);
        transform-origin: top left;
        width: calc(var(--page-w) / 0.90);
        height: calc(var(--page-h) / 0.90);
        overflow: hidden;
      }
    }
  }
</style>
</head>
<body>

<div class="invoice-wrapper">

  <header class="invoice-header">
    <img src="https://rbelectrical.enterprises/wp-content/uploads/2024/07/RBE-Electrical-Logo-clear2.png"
         alt="RBE Logo" class="logo">
  </header>

  <section class="invoice-summary">
    <div>
      <h2>Utility Report</h2>
      <p><strong>Tenant:</strong> <?= htmlspecialchars($tenant_name) ?></p>
      <p><strong>Period:</strong> <?= htmlspecialchars($start_date) ?> to <?= htmlspecialchars($end_date) ?></p>
    </div>
    <div>
      <h3>Total Due</h3>
      <p style="font-size:1.4em; color:#7ed957; font-weight:bold;">
        R <?= number_format($total_due, 2) ?>
      </p>
    </div>
  </section>

  <section style="display:flex; gap:20px; margin:10px 0;">
    <div style="background:#eef7f2; color:#09313f; padding:12px 16px; border-radius:10px;">
      <b>Fee Distribution Legend</b><br>
      <small>
        Sewage: <?= htmlspecialchars($modes['sewage']) ?>,
        Refuse: <?= htmlspecialchars($modes['refuse']) ?>,
        Rates: <?= htmlspecialchars($modes['rates']) ?>,
        Other: <?= htmlspecialchars($modes['other']) ?>
      </small>
    </div>
  </section>

  <table class="invoice-table">
    <thead>
      <tr>
        <th>Type</th>
        <th>Property</th>
        <th>Meter</th>
        <th>Usage</th>
        <th>Unit</th>
        <th>Cost (R)</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($lines as $r): ?>
      <tr>
        <td><?= htmlspecialchars($r['type']) ?></td>
        <td><?= htmlspecialchars($r['property']) ?></td>
        <td><?= htmlspecialchars($r['meter']) ?></td>
        <td><?= is_numeric($r['usage']) ? number_format($r['usage'], 3) : '-' ?></td>
        <td><?= htmlspecialchars($r['unit']) ?></td>
        <td><?= number_format($r['cost'], 2) ?></td>
      </tr>
      <?php endforeach; ?>
    </tbody>
    <tfoot>
      <tr>
        <td colspan="5" class="total-label">TOTAL DUE</td>
        <td class="total-amount">R <?= number_format($total_due, 2) ?></td>
      </tr>
    </tfoot>
  </table>

  <div class="no-print" style="text-align:center; margin-top:20px;">
    <button onclick="window.print()">🖨️ Print Invoice</button>
    <a href="reports.php?landlord_id=<?= urlencode((string)$landlord_id) ?>"
       style="margin-left:16px;">⬅️ Back to Reports</a>
  </div>

</div>

</body>
</html>