<?php
ob_start();
session_start();
include_once("../config.php");
include_once("../functions.php");

if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  die();
}

include_once(ROOT_PATH . 'partial/report_top_common.php');
include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_fair_info_all.php');
include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_common.php');
include_once(ROOT_PATH . 'library/helper.php');

$ams_helper = new ams_helper();

function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function fmt_ordinal_date($str){
  $t = strtotime($str);
  if ($t === false) return e($str);
  return date("jS F, Y", $t);
}

/* -----------------------------
   Capture & sanitize filters
------------------------------*/
$get_data = get_input_serilization();

$bid        = isset($get_data['bid'])        ? (int)$get_data['bid']        : 0;
$uid        = isset($get_data['uid'])        ? (int)$get_data['uid']        : 0;
$tid        = isset($get_data['tid'])        ? (int)$get_data['tid']        : 0;
$ps         = isset($get_data['ps'])         ? trim($get_data['ps'])        : ''; // paid/partial/unpaid/due/1/0
$start_str  = isset($get_data['startDate'])  ? mysqli_real_escape_string($link, $get_data['startDate']) : '';
$end_str    = isset($get_data['endDate'])    ? mysqli_real_escape_string($link, $get_data['endDate'])   : '';
$type       = isset($get_data['type'])       ? trim($get_data['type'])      : '';

/* Date range title (ordinal style) */
$date_range_title = '';
if ($start_str !== '' || $end_str !== '') {
  if ($start_str !== '' && $end_str !== '') {
    $date_range_title = " (" . fmt_ordinal_date($start_str) . " - " . fmt_ordinal_date($end_str) . ")";
  } elseif ($start_str !== '') {
    $date_range_title = " (" . fmt_ordinal_date($start_str) . " - …)";
  } else {
    $date_range_title = " (… - " . fmt_ordinal_date($end_str) . ")";
  }
}

/* -----------------------------
   Build WHERE (string dates)
------------------------------*/
$where_common = "WHERE 1";
if ($type === 'query') {
  if ($bid > 0) $where_common .= " AND bid = {$bid}";
  if ($uid > 0) $where_common .= " AND uid = {$uid}";
  if ($tid > 0) $where_common .= " AND tid = {$tid}";

  // issue_date is VARCHAR, use plain string comparison (expects YYYY-MM-DD format)
  if ($start_str !== '') $where_common .= " AND issue_date >= '{$start_str}'";
  if ($end_str   !== '') $where_common   .= " AND issue_date <= '{$end_str}'";

  // Legacy ps (due/paid/0/1). Client filter will handle partial.
  if ($ps !== '') {
    $ps_l = strtolower($ps);
    if ($ps_l === 'due' || $ps_l === '0')  $where_common .= " AND bill_status = 0";
    if ($ps_l === 'paid' || $ps_l === '1') $where_common .= " AND bill_status = 1";
  }
}

/* -----------------------------
   Queries
------------------------------*/
$sql_cedi = "
  SELECT * FROM rent_tenant_cedi_units_view
  {$where_common}
  ORDER BY issue_date DESC, r_name ASC
";
$sql_fc = "
  SELECT * FROM rent_tenant_foreign_currency_unit_view
  {$where_common}
  ORDER BY issue_date DESC, r_name ASC
";

$rows_cedi = [];
$rows_fc   = [];

$res_cedi = $link->query($sql_cedi);
if ($res_cedi) { while ($r = mysqli_fetch_assoc($res_cedi)) $rows_cedi[] = $r; }

$res_fc = $link->query($sql_fc);
if ($res_fc) { while ($r = mysqli_fetch_assoc($res_fc)) $rows_fc[] = $r; }

/* Totals (server-side, unfiltered; used as initial values) */
$total_paid_ghs    = 0; $total_balance_ghs = 0; $total_rent_ghs = 0;
foreach ($rows_cedi as $r) {
  $paid = (float)$r['amt_paid']; $total = (float)$r['total_rent'];
  $total_paid_ghs += $paid; $total_rent_ghs += $total; $total_balance_ghs += ($total - $paid);
}

$total_paid_fc     = 0; $total_balance_fc  = 0; $total_rent_fc  = 0;
foreach ($rows_fc as $r) {
  $paid = (float)$r['amt_paid']; $total = (float)$r['total_rent'];
  $total_paid_fc  += $paid; $total_rent_fc  += $total; $total_balance_fc  += ($total - $paid);
}
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title><?= e($building_name); ?> — Rent Report</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <?php include_once(ROOT_PATH . '/partial/header_script.php'); ?>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <style>
    :root{
      --bg:#f8fafc; --bg2:#eef2ff; --card:#fff;
      --ink:#0f172a; --ink2:#334155; --muted:#6b7280; --line:#e5e7eb;
      --brand:#2563eb; --ok:#16a34a; --warn:#d97706; --danger:#dc2626;
      --chip:#e2e8f0;
    }
    body, .box, .table, .btn, .label, .badge {
      font-family:'Inter',system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial;
      color:var(--ink2);
      -webkit-font-smoothing:antialiased;
      -moz-osx-font-smoothing:grayscale;
      font-weight:400;
    }

    h1, h2, h3, .box-title, strong, b, th { font-weight:600; }
    .content-header h1{
      font-weight:600;
      color:var(--ink);
      letter-spacing:.1px;
      display:flex; gap:10px; align-items:center;
      margin-bottom:8px;
    }
    .subtle{ color:var(--muted); font-size:12px; font-weight:500; }

    .card{
      background:var(--card);
      border:1px solid var(--line);
      border-radius:14px;
      overflow:hidden;
      box-shadow:0 10px 28px rgba(2,6,23,.06);
      margin-bottom:16px;
    }
    .card-header{
      display:flex; align-items:center; justify-content:space-between; gap:12px;
      padding:12px 14px;
      background:linear-gradient(135deg,var(--bg),var(--bg2));
      border-bottom:1px solid var(--line);
    }
    .card-title{
      margin:0; font-weight:600;
      color:var(--ink); letter-spacing:.1px;
      font-size:16px;
    }

    .btn{ border:none; font-weight:600; border-radius:10px; }
    .btn-compact{ padding:6px 10px !important; font-size:12px !important; line-height:1.25 !important; }
    .btn-primary{ background:var(--brand); color:#fff; }
    .btn-success{ background:var(--ok); color:#fff; }
    .btn-danger{ background:var(--danger); color:#fff; }
    .btn-soft{ background:#fff; border:1px solid var(--line); color:var(--ink2); }
    .btn:hover{ filter:brightness(.97); }
    .btn + .btn{ margin-left:6px; }

    .filter-group{ display:flex; gap:8px; flex-wrap:wrap; align-items:center; }
    .filter-group .btn.active{ box-shadow:0 0 0 2px rgba(37,99,235,.18) inset; }

    .table thead th{
      background:#f8fafc;
      color:var(--ink);
      font-weight:600;
      border-bottom:1px solid var(--line) !important;
    }
    .table tbody td{ vertical-align:middle; font-weight:500; }
    .table tfoot th{ font-weight:600; color:var(--ink); }
    .table tfoot th span{ font-weight:600; }

    .chip{
      display:inline-flex; align-items:center; gap:6px;
      padding:3px 8px; border-radius:999px; border:1px solid var(--line);
      font-weight:600;
      font-size:11px;
    }
    .chip.paid{ background:#ecfdf5; color:#065f46; border-color:#bbf7d0; }
    .chip.partial{ background:#fff7ed; color:#92400e; border-color:#fed7aa; }
    .chip.unpaid{ background:#fef2f2; color:#991b1b; border-color:#fecaca; }

    .print-fab{
      position:fixed; right:12px; top:12px; z-index:999;
      border-radius:999px; padding:8px 10px; box-shadow:0 10px 24px rgba(2,6,23,.12);
      font-weight:600;
    }

    @media print {
      .print-hide { display:none !important; }
      .card { box-shadow:none; border:1px solid #ddd; }
      .table thead th, .table tfoot th { color:#000; }
    }
  </style>
  <script>
    function printContent(area, title) {
      // Prints only the section identified by "area"
      $("#" + area).printThis({ pageTitle: title });
    }
  </script>
</head>
<body>
<section class="content">

  <!-- Header -->
  <section class="content-header print-hide">
    <h1>
      <i class="fa fa-file-text-o"></i> Rent Report
      <span class="subtle">filtered by <code>issue_date</code> (stored as text)</span>
    </h1>
    <ol class="breadcrumb">
      <li><a href="<?= WEB_URL ?>dashboard.php"><i class="fa fa-dashboard"></i><?= e($_data['home_breadcam']); ?></a></li>
      <li class="active"><?= e($_data['text_2'] ?? 'Reports'); ?></li>
      <li class="active"><?= e($_data['text_1]'] ?? 'Rent Report'); ?></li>
    </ol>
  </section>

  <!-- Printable wrapper for "Print All" -->
  <div id="printable">
    <div style="margin:20px 12px 50px 12px;">
      <input type="hidden" id="web_url" value="<?= WEB_URL; ?>" />

      <!-- Report top (logo/title/address/etc.) -->
      <?php include_once(ROOT_PATH . 'partial/report_top_title.php'); ?>

      <!-- Global quick filter (Paid / Partial / Unpaid) -->
      <div class="card print-hide">
        <div class="card-header">
          <h3 class="card-title"><i class="fa fa-filter"></i> Quick Status Filter<?= e($date_range_title); ?></h3>
          <div class="filter-group">
            <button class="btn btn-soft btn-compact status-filter active" data-filter="all"><i class="fa fa-list"></i> All</button>
            <button class="btn btn-soft btn-compact status-filter" data-filter="paid"><i class="fa fa-check-circle"></i> Paid</button>
            <button class="btn btn-soft btn-compact status-filter" data-filter="partial"><i class="fa fa-adjust"></i> Partial</button>
            <button class="btn btn-soft btn-compact status-filter" data-filter="unpaid"><i class="fa fa-exclamation-circle"></i> Unpaid</button>
          </div>
        </div>
      </div>

      <!-- CEDI REPORT (own print section) -->
      <div id="print-cedi" class="card">
        <div class="card-header">
          <h3 class="card-title">
            Cedi Currency Rent Report<?= e($date_range_title); ?>
          </h3>
          <div class="print-hide">
            <!-- Print ONLY the CEDI section -->
            <button class="btn btn-primary btn-compact" onclick="printContent('print-cedi','Cedi Currency Rent Report')"><i class="fa fa-print"></i> Print</button>
          </div>
        </div>
        <div class="box-body" style="padding:16px;">
          <div style="overflow:auto;">
            <table id="table-cedi" class="table table-bordered table-striped dt-responsive" data-cur="<?= e(CURRENCY); ?>">
              <thead>
                <tr>
                  <th>Tenant</th>
                  <th>Block</th>
                  <th>Unit</th>
                  <th>Start Date</th>
                  <th>End Date</th>
                  <th>Paid <?= e(CURRENCY); ?></th>
                  <th>Balance <?= e(CURRENCY); ?></th>
                  <th><?= "Total Rent " . e(CURRENCY); ?></th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
              <?php if (count($rows_cedi) === 0): ?>
                <tr><td colspan="9">No Data Available</td></tr>
              <?php else:
                foreach ($rows_cedi as $row):
                  $paid   = (float)$row['amt_paid'];
                  $total  = (float)$row['total_rent'];
                  $bal    = $total - $paid;
                  $status_key = ($paid >= $total) ? 'paid' : (($paid > 0) ? 'partial' : 'unpaid');
                  $status_txt = ($status_key === 'paid') ? 'Paid' : (($status_key === 'partial') ? 'Partial' : 'Unpaid');
              ?>
                <tr data-status="<?= $status_key; ?>" data-paid="<?= number_format($paid, 2, '.', ''); ?>" data-balance="<?= number_format($bal, 2, '.', ''); ?>" data-total="<?= number_format($total, 2, '.', ''); ?>">
                  <td><?= e($row['r_name']); ?></td>
                  <td><?= e($row['b_name']); ?></td>
                  <td><?= e($row['unit_no']); ?></td>
                  <td><?= date("jS F, Y", strtotime($row['start_date'])); ?></td>
                  <td><?= date("jS F, Y", strtotime($row['end_date'])); ?></td>
                  <td><?= number_format($paid, 2); ?></td>
                  <td><?= number_format($bal, 2); ?></td>
                  <td><?= number_format($total, 2); ?></td>
                  <td><span class="chip <?= $status_key; ?>"><?= $status_txt; ?></span></td>
                </tr>
              <?php endforeach; endif; ?>
              </tbody>
              <tfoot>
                <tr>
                  <th colspan="5" style="text-align:right;">Totals:</th>
                  <th style="color:#1e40af;"><span id="cedi_paid_total"><?= money_print($total_paid_ghs); ?></span></th>
                  <th style="color:#b91c1c;"><span id="cedi_balance_total"><?= money_print($total_balance_ghs); ?></span></th>
                  <th style="color:#14532d;"><span id="cedi_rent_total"><?= money_print($total_rent_ghs); ?></span></th>
                  <th>&nbsp;</th>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>
      </div>

      <!-- FOREIGN CURRENCY REPORT (own print section) -->
      <div id="print-fc" class="card">
        <div class="card-header">
          <h3 class="card-title">
            Foreign Currency Rent Report<?= e($date_range_title); ?>
          </h3>
          <div class="print-hide">
            <!-- Print ONLY the FOREIGN CURRENCY section -->
            <button class="btn btn-primary btn-compact" onclick="printContent('print-fc','Foreign Currency Rent Report')"><i class="fa fa-print"></i> Print</button>
          </div>
        </div>
        <div class="box-body" style="padding:16px;">
          <div style="overflow:auto;">
            <table id="table-fc" class="table table-bordered table-striped dt-responsive" data-cur="USD">
              <thead>
                <tr>
                  <th>Tenant</th>
                  <th>Block</th>
                  <th>Unit</th>
                  <th>Start Date</th>
                  <th>End Date</th>
                  <th>Paid USD</th>
                  <th>Balance USD</th>
                  <th>Total Rent USD</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
              <?php if (count($rows_fc) === 0): ?>
                <tr><td colspan="9">No Data Available</td></tr>
              <?php else:
                foreach ($rows_fc as $row):
                  $paid   = (float)$row['amt_paid'];
                  $total  = (float)$row['total_rent'];
                  $bal    = $total - $paid;
                  $status_key = ($paid >= $total) ? 'paid' : (($paid > 0) ? 'partial' : 'unpaid');
                  $status_txt = ($status_key === 'paid') ? 'Paid' : (($status_key === 'partial') ? 'Partial' : 'Unpaid');
              ?>
                <tr data-status="<?= $status_key; ?>" data-paid="<?= number_format($paid, 2, '.', ''); ?>" data-balance="<?= number_format($bal, 2, '.', ''); ?>" data-total="<?= number_format($total, 2, '.', ''); ?>">
                  <td><?= e($row['r_name']); ?></td>
                  <td><?= e($row['b_name']); ?></td>
                  <td><?= e($row['unit_no']); ?></td>
                  <td><?= date("jS F, Y", strtotime($row['start_date'])); ?></td>
                  <td><?= date("jS F, Y", strtotime($row['end_date'])); ?></td>
                  <td><?= number_format($paid, 2); ?></td>
                  <td><?= number_format($bal, 2); ?></td>
                  <td><?= number_format($total, 2); ?></td>
                  <td><span class="chip <?= $status_key; ?>"><?= $status_txt; ?></span></td>
                </tr>
              <?php endforeach; endif; ?>
              </tbody>
              <tfoot>
                <tr>
                  <th colspan="5" style="text-align:right;">Totals:</th>
                  <th style="color:#1e40af;"><span id="fc_paid_total"><?= money_sym($total_paid_fc); ?></span></th>
                  <th style="color:#b91c1c;"><span id="fc_balance_total"><?= money_sym($total_balance_fc); ?></span></th>
                  <th style="color:#14532d;"><span id="fc_rent_total"><?= money_sym($total_rent_fc); ?></span></th>
                  <th>&nbsp;</th>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>
      </div>

    </div>
  </div>

  <!-- Floating Print All Button -->
  <div class="print-hide">
    <a title="<?= e($_data['text_16'] ?? 'Print'); ?>" class="btn btn-success btn-compact print-fab"
       onclick="printContent('printable','Rent Collection Report')" href="javascript:void(0);">
      <i class="fa fa-print"></i>
    </a>
  </div>

</section>

<script>
  // Utility: format number with 2 decimals and thousands separators
  function fmt(n){
    return (n||0).toLocaleString(undefined,{minimumFractionDigits:2, maximumFractionDigits:2});
  }

  function sumVisible(tableSel){
    var t = document.querySelector(tableSel);
    var rows = t.querySelectorAll('tbody tr');
    var sumPaid=0, sumBal=0, sumTot=0;
    rows.forEach(function(tr){
      if (tr.style.display === 'none') return;
      sumPaid += parseFloat(tr.dataset.paid || '0');
      sumBal  += parseFloat(tr.dataset.balance || '0');
      sumTot  += parseFloat(tr.dataset.total || '0');
    });
    return {paid:sumPaid, bal:sumBal, tot:sumTot, cur:(t.dataset.cur||'')};
  }

  function updateFooter(tableSel, ids){
    var s = sumVisible(tableSel);
    var pref = s.cur ? (s.cur + ' ') : '';
    document.getElementById(ids.paid).textContent    = pref + fmt(s.paid);
    document.getElementById(ids.balance).textContent = pref + fmt(s.bal);
    document.getElementById(ids.total).textContent   = pref + fmt(s.tot);
  }

  function applyFilter(mode){
    // Toggle button active state
    document.querySelectorAll('.status-filter').forEach(function(b){ b.classList.remove('active'); });
    var btn = document.querySelector('.status-filter[data-filter="'+mode+'"]');
    if (btn) btn.classList.add('active');

    // Show/hide rows for both tables
    ['#table-cedi','#table-fc'].forEach(function(sel){
      document.querySelectorAll(sel + ' tbody tr').forEach(function(tr){
        if (mode === 'all') { tr.style.display = ''; return; }
        var st = (tr.getAttribute('data-status')||'').toLowerCase();
        tr.style.display = (st === mode) ? '' : 'none';
      });
    });

    // Recalculate totals based on visible rows
    updateFooter('#table-cedi', {paid:'cedi_paid_total', balance:'cedi_balance_total', total:'cedi_rent_total'});
    updateFooter('#table-fc',   {paid:'fc_paid_total',   balance:'fc_balance_total',   total:'fc_rent_total'});
  }

  // Wire up filter buttons
  document.querySelectorAll('.status-filter').forEach(function(b){
    b.addEventListener('click', function(){
      applyFilter(this.getAttribute('data-filter'));
    });
  });

  // Initial calc (All)
  applyFilter('all');
</script>
</body>
</html>
