<?php
/* addrentt-multi.php — Multi-Unit Rent Capture (no audit trails) */

include_once('../header.php');
include_once(ROOT_PATH.'language/'.$lang_code_global.'/lang_add_fare.php');

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

/* -------------------------------------------------
   Small helpers
------------------------------------------------- */
function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function post_input_serilization(){
  $src = $_POST;
  foreach ($src as $k=>$v) {
    if (is_string($v)) { $src[$k] = trim($v); }
  }
  return $src;
}

/* -------------------------------------------------
   Defaults
------------------------------------------------- */
$type            = 'Rented';
$issue_date      = '';
$amt_paid        = '';
$period          = '';
$paid_date       = '';
$bill_status     = '';
$r_description   = '';

$tid             = 0;
$title           = $_data['add_new_rent'];
$button_text     = $_data['save_button_text'];
$successful_msg  = $_data['added_rent_successfully'];
$form_url        = WEB_URL . "rent/addrentt.php";
$hdnid           = "0";

/* Currencies (cid, symbol, exchange_rate) */
$currencies = [];
$cr = $link->query("SELECT cid, symbol, exchange_rate FROM currencies ORDER BY cid ASC");
while ($row = $cr->fetch_assoc()) { $currencies[] = $row; }

$default_currency_symbol = isset($currencies[0]) ? $currencies[0]['symbol'] : '¤';

/* Back-compat (kept as-is) */
$currency_result   = $link->query("SELECT symbol FROM currencies");
$default_currency  = mysqli_fetch_assoc($currency_result) ?: ['symbol' => $default_currency_symbol];
$foreign_curr      = $link->query("SELECT foreign_currency_id FROM settings");
$foreign_currencies= mysqli_fetch_assoc($foreign_curr);

/* -------------------------------------------------
   CREATE / UPDATE
------------------------------------------------- */
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $data = post_input_serilization();

  // Parse start date
  $startRaw = $data['txtStartDate'] ?? '';
  $startDate= date("Y-m-d", strtotime($startRaw));
  $start_ts = strtotime($startDate);

  // Parse period
  $period_type = ($data["period_type"] ?? 'Y') === 'M' ? 'M' : 'Y';
  $dur         = max(0, (int)($data['duration'] ?? 0));
  if ($dur <= 0) {
    $_SESSION["message"] = "Please enter a valid period.";
    $_SESSION["message_type"] = "error";
    header("Location: " . WEB_URL . "rent/addrentt.php");
    exit;
  }

  // Units payload (JSON lines from UI)
  $units_json    = $data['units_json'] ?? '[]';
  $units_payload = json_decode($units_json, true);
  if (!is_array($units_payload) || count($units_payload) === 0) {
    $_SESSION["message"] = "Please add at least one unit.";
    $_SESSION["message_type"] = "error";
    header("Location: " . WEB_URL . "rent/addrentt.php");
    exit;
  }

  // Ensure all units share same currency id
  $currency_ids = array_unique(array_map(function($u){
    return (string)($u['rate_currency_id'] ?? '');
  }, $units_payload));
  if (count($currency_ids) !== 1 || $currency_ids[0] === '') {
    $_SESSION["message"] = "All selected units must use the same currency.";
    $_SESSION["message_type"] = "error";
    header("Location: " . WEB_URL . "rent/addrentt.php");
    exit;
  }
  $rent_currency_id = (int)$currency_ids[0];

  // Resolve exchange rate for that currency
  $ex_rate = 1.0;
  foreach ($currencies as $c) {
    if ((int)$c['cid'] === $rent_currency_id) { $ex_rate = (float)$c['exchange_rate']; break; }
  }

  // Inclusive end date: (start + duration) - 1 day
  if ($period_type === "Y") {
    $tmp = strtotime("+{$dur} years", $start_ts);
    $endDate = date("Y-m-d", strtotime("-1 day", $tmp));
  } else {
    $tmp = strtotime("+{$dur} months", $start_ts);
    $endDate = date("Y-m-d", strtotime("-1 day", $tmp));
  }

  // Compute totals across units
  $sum_monthly_rate = 0.0;
  foreach ($units_payload as &$u) {
    $u_rate = (float)($u['monthly_rate'] ?? 0);
    $sum_monthly_rate += $u_rate;
    $u_total = ($period_type === 'Y') ? ($u_rate * 12 * $dur) : ($u_rate * $dur);
    $u['line_total'] = round($u_total, 2);
  }
  unset($u);

  $grand_total = array_reduce($units_payload, function($acc, $u){ return $acc + (float)$u['line_total']; }, 0.0);
  $rent_yearly = $sum_monthly_rate * 12;

  // Tenant check
  $tid = (int)($data['tid'] ?? 0);
  if ($tid <= 0) {
    $_SESSION["message"] = "Please select a tenant.";
    $_SESSION["message_type"] = "error";
    header("Location: " . WEB_URL . "rent/addrentt.php");
    exit;
  }

  // Prevent overlap: last inclusive end date for each unit
  $conflict = null;
  foreach ($units_payload as $u) {
    $uid_i = (int)$u['uid'];
    $prev = mysqli_fetch_assoc($link->query(
      "SELECT end_date FROM rent WHERE JSON_CONTAINS(uid, '\"$uid_i\"') ORDER BY end_date DESC, added_date DESC LIMIT 1"
    ));
    if ($prev) {
      $prev_end_ts = strtotime($prev['end_date']);
      if ($prev_end_ts >= $start_ts) {
        $conflict = [
          'uid' => $uid_i,
          'previous_end' => $prev['end_date']
        ];
        break;
      }
    }
  }
  if ($conflict) {
    $_SESSION["message"] = "New Rent must start AFTER the previous rent period for Unit ID ".$conflict['uid'].": " . date("jS M, Y", strtotime($conflict['previous_end']));
    $_SESSION["message_type"] = "error";
    header("Location: " . WEB_URL . "rent/rentlist.php");
    exit;
  }

  // Decorate units with unit_no (for display elsewhere if needed)
  $first_unit_no = null;
  foreach ($units_payload as $u) {
    $res = mysqli_fetch_assoc($link->query("SELECT unit_no FROM units WHERE uid=".(int)$u['uid']." LIMIT 1"));
    if ($res && isset($res['unit_no'])) { $u['unit_no'] = $res['unit_no']; }
    if ($first_unit_no === null && isset($u['unit_no'])) $first_unit_no = $u['unit_no'];
  }

  $issueDate = $link->real_escape_string($data['txtIssueDate'] ?? '');
  $paidNow   = (float)(($data["amt_paid"] ?? '') === "" ? 0 : $data["amt_paid"]);
  $desc_note = $link->real_escape_string($data['r_description'] ?? '');

  // Insert rent row — store the UNITS JSON in `uid`
  $sqlRent = "INSERT INTO `rent`
              (`uid`,`tid`,`rate`,`rate_currency_id`,`currency_exchange_rate`,`rent_yearly`,
               `period`,`period_type`,`amt_paid`,`start_date`,`end_date`,`issue_date`,`added_by`,`total_rent`,`r_description`)
              VALUES (
                '".$link->real_escape_string(json_encode(array_values(array_map(function($u){ return (int)$u['uid']; }, $units_payload))))."',
                ".$tid.",
                ".number_format($sum_monthly_rate, 2, ".", "").",
                ".$rent_currency_id.",
                ".$ex_rate.",
                ".number_format($rent_yearly, 2, ".", "").",
                ".$dur.",
                '".$period_type."',
                ".$paidNow.",
                '".$startDate."',
                '".$endDate."',
                '".$issueDate."',
                ".(int)$_SESSION['user_id'].",
                ".number_format($grand_total, 2, ".", "").",
                '".$desc_note."'
              )";
  $okRent = $link->query($sqlRent);
  $rent_id = $link->insert_id;

  if (!$okRent) {
    $_SESSION["message"] = "Failed to add rent: " . $link->error;
    $_SESSION["message_type"] = "error";
    header("Location: " . WEB_URL . 'rent/rentlist.php');
    exit;
  }

  // Tenant account (credit full bill)
  $current_year = date('Y');
  $desc = "Rent Processed for ".count($units_payload)." unit(s)".
          ($first_unit_no ? (" (e.g., ".$first_unit_no.")") : "").
          " for ".$dur." ".($period_type === "Y" ? "year(s)" : "month(s)");
  $sqlTA = "INSERT INTO `tenant_accounts`(`tid`,`rid`,`trans_type`,`description`,`transaction_amt`,`added_by`)
            VALUES (".$tid.", ".$rent_id.", 'credit', '".$link->real_escape_string($desc)."', ".number_format($grand_total,2,'.','').", ".(int)$_SESSION['user_id'].")";
  $okTA = $link->query($sqlTA);

  // Route by currency
  if ($rent_currency_id == 15) {
    $link->query("INSERT INTO `main_account`(`rent_id`,`fiscal_year`,`trans_type`,`amount`,`added_by`)
                  VALUES (".$rent_id.", ".$current_year.", 'debit', ".number_format($grand_total,2,'.','').", ".(int)$_SESSION['user_id'].")");
  } else {
    $link->query("INSERT INTO `foreign_currency_main_account`(`rent_id`,`fiscal_year`,`trans_type`,`amount`,`added_by`)
                  VALUES (".$rent_id.", ".$current_year.", 'debit', ".number_format($grand_total,2,'.','').", ".(int)$_SESSION['user_id'].")");
  }

  // Payment now?
  if ($paidNow > 0) {
    $link->query("INSERT INTO `tenant_accounts`(`tid`,`rid`,`trans_type`,`description`,`transaction_amt`,`added_by`)
                  VALUES (".$tid.", ".$rent_id.", 'debit', 'Rent Payment From Tenant', ".number_format($paidNow,2,'.','').", ".(int)$_SESSION['user_id'].")");
    $link->query("INSERT INTO `rent_payment_updates`(`rent_id`,`amount`,`added_by`)
                  VALUES (".$rent_id.", ".number_format($paidNow,2,'.','').", ".(int)$_SESSION['user_id'].")");
    if ($paidNow >= (float)$grand_total) {
      $link->query("UPDATE `rent` SET `bill_status` = 1 WHERE id = ".$rent_id);
    }
  }

  @mysqli_commit($link);

  $_SESSION["message"] = "Rent Added Successfully";
  header("Location: " . WEB_URL . 'security_deposit/addsecuritydeposit.php');
  exit;
}

/* -------------------------------------------------
   If editing (prefill)
------------------------------------------------- */
$editing = false;
if (isset($_GET['id']) && ctype_digit((string)$_GET['id'])) {
  $res = $link->query("SELECT * FROM rent WHERE id=".(int)$_GET['id']." LIMIT 1");
  if ($row = mysqli_fetch_array($res)) {
    $editing = true;
    $tid           = (int)$row['tid'];
    $issue_date    = $row['issue_date'];
    $amt_paid      = $row['amt_paid'];
    $period        = $row['period'];
    $bill_status   = $row['bill_status'];
    $r_description = $row['r_description'] ?? '';
    $title         = $_data['update_rent'];
    $button_text   = $_data['update_button_text'];
    $successful_msg= $_data['update_rent_successfully'];
    $form_url      = WEB_URL . "rent/addrentt.php?id=".(int)$_GET['id'];
  }
}
?>
<!-- Content Header -->
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;margin-bottom:8px;">
    <span style="display:inline-flex;width:36px;height:36px;border-radius:10px;background:#2563eb15;align-items:center;justify-content:center;">
      <i class="fa fa-file-text-o" style="color:#1e40af;"></i>
    </span>
    <span><?= e($title); ?></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['add_new_rent_information_breadcam']);?></li>
    <li class="active"><?= e($title); ?></li>
  </ol>
</section>

<!-- Fonts & styles -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<link href="<?= WEB_URL; ?>assets/css/toggleSwitch.css" rel="stylesheet" type="text/css" />
<link id="fp-css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.css">
<style>
  :root{
    --ink:#0f172a; --ink2:#334155; --muted:#64748b; --line:#e5e7eb;
    --brand:#2563eb; --brand-2:#1e40af; --ok:#16a34a; --warn:#d97706; --danger:#dc2626;
    --soft:#f8fafc; --soft2:#eef2ff; --card:#ffffff;
  }
  .content-wrapper, .box, .table, label, .btn, .alert, input, select, textarea {
    font-family:'Inter',system-ui,Segoe UI,Roboto,Helvetica,Arial;
    color:var(--ink2);
  }
  .box.box-success{
    border-radius:16px; overflow:hidden; border:1px solid var(--line);
    box-shadow:0 12px 32px rgba(2,6,23,.08); background:var(--card);
  }
  .box .box-header{ background:linear-gradient(135deg,var(--soft),var(--soft2)); border-bottom:1px solid var(--line); padding:14px 16px; }
  .box .box-title{ font-weight:800; color:var(--ink); margin:0; letter-spacing:.2px; }
  .card{ background:#fff; border:1px solid var(--line); border-radius:16px; padding:16px; }
  .section-title{ display:flex; align-items:center; gap:8px; font-weight:800; color:var(--ink); margin:0 0 10px; }
  .section-title i{ color:#1e40af; }
  .form-control{ height:44px; border-radius:12px; border:1px solid var(--line); box-shadow:none !important; }
  .form-control:focus{ border-color:#93c5fd; box-shadow:0 0 0 3px rgba(59,130,246,.15); }
  .input-group-addon{ background:#fff; border:1px solid var(--line); border-right:0; border-radius:12px 0 0 12px; min-width:44px; text-align:center; }
  .help-note{ font-size:12px; color:var(--muted); margin-top:6px; }
  .btn{ border-radius:12px; font-weight:700; }
  .btn-success{ background:var(--ok); border-color:var(--ok); }
  .btn-warning{ background:#f59e0b; border-color:#f59e0b; }
  .btn-default{ background:#e5e7eb; border-color:#e5e7eb; color:#111827; }
  .btn:hover{ filter:brightness(.98); }
  .pill{ display:inline-flex; align-items:center; gap:6px; padding:6px 10px; border-radius:999px; background:#f3f4f6; color:#111827; font-size:12px; font-weight:700; border:1px solid var(--line); }
  .pill i{ color:#6b7280; }
  .info-block{ background:#fff; border:1px dashed var(--line); color:#64748b; border-radius:12px; }
  .form-grid{ display:grid; grid-template-columns: 1fr 360px; gap:16px; align-items:start; }
  @media (max-width: 1100px){ .form-grid{ grid-template-columns: 1fr; } }
  table.table { width:100%; border:1px solid var(--line); border-radius:12px; overflow:hidden; }
  table.table thead th{ background:#f8fafc; border-bottom:1px solid var(--line); }
  table.table td, table.table th{ padding:10px; vertical-align:middle; }
  .currency-pill{ font-weight:700; padding:4px 8px; background:#eef2ff; border:1px solid var(--line); border-radius:999px; display:inline-block; }
</style>

<section class="content">
  <div class="box box-success">
    <div class="box-header">
      <h3 class="box-title"><?= e($_data['add_new_rent_entry_form']);?></h3>
    </div>

    <div class="box-body">
      <form id="addRentForm" name="addRentForm" action="<?= e($form_url); ?>" method="post" enctype="multipart/form-data">
        <div class="form-grid">

          <!-- Left column -->
          <div class="card">
            <h4 class="section-title"><i class="fa fa-user-circle"></i> Tenant & Units</h4>

            <div class="row">
              <!-- Tenant -->
              <div class="form-group col-md-6">
                <label><span style="color:#dc2626">*</span> Tenant</label>
                <div class="input-group">
                  <span class="input-group-addon"><i class="fa fa-user"></i></span>
                  <select required name="tid" id="tid" class="form-control">
                    <option value="">-- Select Tenant --</option>
                    <?php
                      $result_tenant = $link->query("SELECT * FROM current_tenants_view ORDER BY r_name ASC");
                      while ($row_tenant = mysqli_fetch_array($result_tenant)) { ?>
                        <option value="<?= (int)$row_tenant['tid'];?>" <?= $tid == $row_tenant['tid']? "selected": ""; ?>>
                          <?= e($row_tenant['r_name']);?>
                        </option>
                    <?php } ?>
                  </select>
                </div>
                <div class="help-note">Choose a tenant to load their available units.</div>
              </div>

              <!-- Multi Unit selector -->
              <div class="form-group col-md-6">
                <label><span style="color:#dc2626">*</span> Units (multiple)</label>
                <div class="input-group">
                  <span class="input-group-addon"><i class="fa fa-building-o"></i></span>
                  <select id="multiUnits" class="form-control" multiple size="6" style="height:150px;">
                  </select>
                </div>
                <div class="help-note">Hold Ctrl/Cmd to select multiple units, then click “Add Selected Units”.</div>
                <div style="margin-top:8px;">
                  <button type="button" class="btn btn-default" id="btnAddSelected"><i class="fa fa-plus"></i> Add Selected Units</button>
                </div>
              </div>
            </div>

            <!-- Previous rent info -->
            <div class="row">
              <div class="form-group col-md-12">
                <label>Previous Rent (latest per unit)</label>
                <div id="previousRentReport" class="alert info-block" style="margin:0;">Select units to see previous periods.</div>
              </div>
            </div>

            <hr>

            <h4 class="section-title"><i class="fa fa-money"></i> Rates per Unit</h4>

            <div class="table-responsive">
              <table class="table" id="unitsTable">
                <thead>
                  <tr>
                    <th style="width:28%;">Unit</th>
                    <th style="width:18%;">Currency</th>
                    <th style="width:18%;">Monthly Rate</th>
                    <th style="width:18%;">Line Total</th>
                    <th style="width:18%;">Actions</th>
                  </tr>
                </thead>
                <tbody id="unitsBody">
                  <tr id="unitsEmptyRow"><td colspan="5" class="text-center" style="text-align:center;color:#64748b;">No units added yet.</td></tr>
                </tbody>
              </table>
            </div>
            <div id="currencyMismatch" class="help-note" style="display:none;color:#dc2626;font-weight:700;">All units must share the same currency.</div>

            <hr>

            <h4 class="section-title"><i class="fa fa-calendar-o"></i> Period</h4>
            <div class="row">
              <div class="form-group col-md-6">
                <label><span style="color:#dc2626">*</span> Start Date</label>
                <div class="input-group">
                  <span class="input-group-addon"><i class="fa fa-calendar-o"></i></span>
                  <input type="text" name="txtStartDate" id="txtStartDate" class="form-control date-input" required placeholder="YYYY-MM-DD" inputmode="none" />
                </div>
              </div>

              <div class="form-group col-md-3">
                <label><span style="color:#dc2626">*</span> Period Value</label>
                <input type="number" min="1" required name="duration" id="duration" class="form-control" placeholder="e.g., 1" />
              </div>

              <div class="form-group col-md-3">
                <label>&nbsp;</label>
                <div class="input-group">
                  <div class="input-group-addon" style="padding:0;">
                    <select name="period_type" id="period_type" required style="border:0;height:44px;width:100%;border-radius:12px;">
                      <option value="Y">Years</option>
                      <option value="M">Months</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>

            <div class="row">
              <div class="form-group col-md-6">
                <label>End Date</label>
                <div class="input-group">
                  <span class="input-group-addon"><i class="fa fa-calendar-check-o"></i></span>
                  <input type="text" id="endDateDisplay" class="form-control" readonly placeholder="Auto-calculated" />
                </div>
                <input type="hidden" name="end_date" id="end_date" />
              </div>

              <div class="form-group col-md-6">
                <label>Grand Total</label>
                <div class="input-group">
                  <div class="input-group-addon" id="sym_total">¤</div>
                  <input type="text" id="grand_total" class="form-control" readonly placeholder="0.00" />
                </div>
              </div>
            </div>

            <hr>

            <h4 class="section-title"><i class="fa fa-credit-card"></i> Payment & Issue</h4>
            <div class="row">
              <div class="form-group col-md-6">
                <label>Amount / Advance Paid</label>
                <div class="input-group">
                  <div class="input-group-addon" id="sym_paid">¤</div>
                  <input type="number" step="0.01" min="0" value="<?= e($amt_paid ?: '0'); ?>" name="amt_paid" id="amt_paid" class="form-control" />
                </div>
                <div class="help-note">Optional.</div>
              </div>

              <div class="form-group col-md-6">
                <label><span style="color:#dc2626">*</span> <?= e($_data['add_new_form_field_text_15']);?></label>
                <div class="input-group">
                  <span class="input-group-addon"><i class="fa fa-calendar-o"></i></span>
                  <input type="text" required name="txtIssueDate" value="<?= e($issue_date);?>" id="txtIssueDate" class="form-control date-input" placeholder="YYYY-MM-DD" inputmode="none" />
                </div>
              </div>
            </div>

            <hr>

            <h4 class="section-title"><i class="fa fa-sticky-note-o"></i> Description / Notes</h4>
            <div class="form-group">
              <label for="r_description">Additional details (optional)</label>
              <textarea name="r_description" id="r_description" rows="4" class="form-control" placeholder="e.g., deposit terms, special conditions…"><?= e($r_description); ?></textarea>
            </div>

          </div>

          <!-- Right column: Live Summary -->
          <aside class="card">
            <h4 class="section-title"><i class="fa fa-info-circle"></i> Summary</h4>
            <div style="display:grid; gap:10px;">
              <div class="pill"><i class="fa fa-user"></i> <span id="sum_tenant">Tenant: —</span></div>
              <div class="pill"><i class="fa fa-building-o"></i> <span id="sum_units">Units: 0</span></div>
              <div class="pill"><i class="fa fa-money"></i> <span id="sum_currency">Currency: —</span></div>
              <div class="pill"><i class="fa fa-calculator"></i> <span id="sum_monthly">Monthly Sum: —</span></div>
              <div class="pill"><i class="fa fa-calculator"></i> <span id="sum_total">Grand Total: —</span></div>
              <div class="pill"><i class="fa fa-calendar"></i> <span id="sum_start">Start: —</span></div>
              <div class="pill"><i class="fa fa-hourglass"></i> <span id="sum_period">Period: —</span></div>
              <div class="pill"><i class="fa fa-calendar-check-o"></i> <span id="sum_end">Ends: —</span></div>
              <div class="pill"><i class="fa fa-credit-card"></i> <span id="sum_paid">Paid: —</span></div>
            </div>
            <div class="help-note" style="margin-top:10px;">Updates as you edit.</div>
          </aside>

        </div>

        <div class="box-footer" style="padding:16px 0 0; display:flex; justify-content:flex-end; gap:10px;">
          <input type="hidden" name="units_json" id="units_json" value="[]">
          <button type="submit" id="btnSubmit" class="btn btn-success">
            <i class="fa fa-floppy-o"></i> <?= e($button_text); ?>
          </button>
          <a class="btn btn-warning" href="<?= WEB_URL; ?>rent/rentlist.php">
            <i class="fa fa-reply"></i> <?= e($_data['back_text']);?>
          </a>
        </div>
      </form>
    </div>
  </div>
</section>

<!-- Existing helpers (if any) -->
<script src="<?= WEB_URL; ?>assets/js/addrentt.js"></script>

<!-- Flatpickr loader + init -->
<script>
(function ensureFlatpickrAndInit(){
  function initPickers(){
    if (!window.flatpickr) return;
    var opts = { dateFormat: 'Y-m-d', allowInput: true, clickOpens: true };
    flatpickr('#txtIssueDate', Object.assign({}, opts, {
      defaultDate: document.getElementById('txtIssueDate').value || null
    }));
    flatpickr('#txtStartDate', Object.assign({}, opts, {
      defaultDate: document.getElementById('txtStartDate').value || null,
      onChange: function(){ updateEnd(); recomputeAll(); }
    }));
  }
  if (window.flatpickr) { initPickers(); return; }
  var s = document.createElement('script');
  s.src = 'https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.js';
  s.onload = initPickers;
  document.head.appendChild(s);
})();
</script>

<script>
/* Currency map for summary pills */
const currencyMap = {
  <?php foreach ($currencies as $c): ?>
    "<?= (int)$c['cid'] ?>": "<?= e($c['symbol']) ?>",
  <?php endforeach; ?>
};

const elTenant = document.getElementById('tid');
const elMulti  = document.getElementById('multiUnits');
const elUnitsBody = document.getElementById('unitsBody');
const elEmptyRow = document.getElementById('unitsEmptyRow');
const elUnitsJson= document.getElementById('units_json');

const elStart  = document.getElementById('txtStartDate');
const elDur    = document.getElementById('duration');
const elType   = document.getElementById('period_type');
const elEndDisp= document.getElementById('endDateDisplay');
const elEnd    = document.getElementById('end_date');
const elPaid   = document.getElementById('amt_paid');

const symPaid  = document.getElementById('sym_paid');
const symTotal = document.getElementById('sym_total');
const currencyMismatch = document.getElementById('currencyMismatch');
const btnSubmit = document.getElementById('btnSubmit');

const SUM = {
  tenant:  document.getElementById('sum_tenant'),
  units:   document.getElementById('sum_units'),
  curr:    document.getElementById('sum_currency'),
  monthly: document.getElementById('sum_monthly'),
  total:   document.getElementById('sum_total'),
  start:   document.getElementById('sum_start'),
  period:  document.getElementById('sum_period'),
  end:     document.getElementById('sum_end'),
  paid:    document.getElementById('sum_paid'),
};
const GRAND_TOTAL = document.getElementById('grand_total');

// Internal state
let lineItems = []; // [{uid, unit_no, rate_currency_id, currency_symbol, monthly_rate, line_total}]
function stateToHidden(){
  elUnitsJson.value = JSON.stringify(lineItems.map(function(li){
    return {
      uid: li.uid,
      monthly_rate: +li.monthly_rate,
      rate_currency_id: li.rate_currency_id
    };
  }));
}
function refreshEmptyRow(){
  elEmptyRow.style.display = (lineItems.length === 0) ? '' : 'none';
}
function fmt2(n){ return (isFinite(n) ? (+n).toFixed(2) : '0.00'); }

function currentCurrencySymbol(){
  if (lineItems.length === 0) return '¤';
  const cid = lineItems[0].rate_currency_id;
  return currencyMap[cid] || '¤';
}
function setSymbolsEverywhere(){
  const sym = currentCurrencySymbol();
  symPaid.textContent  = sym;
  symTotal.textContent = sym;
}

function parseDateInput(val){
  if (!val) return null;
  const dt = new Date(val);
  return isNaN(dt) ? null : dt;
}
function fmtDate(d){
  if (!d) return '—';
  const dt = new Date(d);
  if (isNaN(dt)) return d;
  const y = dt.getFullYear(), m = (dt.getMonth()+1).toString().padStart(2,'0'), dd = dt.getDate().toString().padStart(2,'0');
  return `${y}-${m}-${dd}`;
}

/* Inclusive End Date Logic (matches server-side) */
function updateEnd(){
  const start = parseDateInput(elStart.value);
  const dur   = parseInt(elDur.value || '0', 10);
  const type  = elType.value;
  if (!start || !dur) { elEndDisp.value = ''; elEnd.value = ''; updateSummary(); return; }

  const dt = new Date(start.getTime());
  if (type === 'Y') {
    dt.setFullYear(dt.getFullYear() + dur);
  } else {
    const targetMonth = dt.getMonth() + dur;
    dt.setMonth(targetMonth);
  }
  dt.setDate(dt.getDate() - 1); // inclusive end

  const out = fmtDate(dt);
  elEndDisp.value = out;
  elEnd.value     = out;
  updateSummary();
}

function recomputeAll(){
  const dur = parseInt(elDur.value || '0', 10);
  const type = elType.value;
  lineItems.forEach(function(li){
    const rate = parseFloat(li.monthly_rate) || 0;
    li.line_total = type === 'Y' ? (rate * 12 * dur) : (rate * dur);
  });
  ensureSingleCurrency();
  renderRows();
  updateSummary();
  stateToHidden();
}

function ensureSingleCurrency(){
  const ids = Array.from(new Set(lineItems.map(li => String(li.rate_currency_id))));
  const ok = (ids.length <= 1);
  currencyMismatch.style.display = ok ? 'none' : '';
  btnSubmit.disabled = !ok;
  return ok;
}

function renderRows(){
  elUnitsBody.querySelectorAll('tr').forEach(function(tr){
    if (tr.id !== 'unitsEmptyRow') tr.remove();
  });
  lineItems.forEach(function(li){
    const tr = document.createElement('tr');

    const tdUnit = document.createElement('td');
    tdUnit.textContent = (li.unit_no || ('Unit #'+li.uid));
    tr.appendChild(tdUnit);

    const tdCur = document.createElement('td');
    tdCur.innerHTML = `<span class="currency-pill">${li.currency_symbol || '¤'}</span>`;
    tr.appendChild(tdCur);

    const tdRate = document.createElement('td');
    const inp = document.createElement('input');
    inp.type = 'number'; inp.min = '0'; inp.step = '0.01'; inp.className = 'form-control';
    inp.value = fmt2(li.monthly_rate);
    inp.oninput = function(){
      li.monthly_rate = parseFloat(inp.value) || 0;
      recomputeAll();
    };
    tdRate.appendChild(inp);
    tr.appendChild(tdRate);

    const tdLine = document.createElement('td');
    tdLine.textContent = fmt2(li.line_total || 0);
    tdLine.dataset.role = 'line_total';
    tr.appendChild(tdLine);

    const tdAct = document.createElement('td');
    const btnDel = document.createElement('button');
    btnDel.type = 'button'; btnDel.className = 'btn btn-default';
    btnDel.innerHTML = '<i class="fa fa-trash"></i> Remove';
    btnDel.onclick = function(){
      lineItems = lineItems.filter(function(x){ return x.uid !== li.uid; });
      refreshEmptyRow();
      recomputeAll();
    };
    tdAct.appendChild(btnDel);
    tr.appendChild(tdAct);

    elUnitsBody.appendChild(tr);
  });
  refreshEmptyRow();

  const rows = elUnitsBody.querySelectorAll('tr');
  let i = 0;
  rows.forEach(function(tr){
    if (tr.id === 'unitsEmptyRow') return;
    const cell = tr.querySelector('[data-role="line_total"]');
    if (cell && lineItems[i]) cell.textContent = fmt2(lineItems[i].line_total || 0);
    i++;
  });
}

function updateSummary(){
  const sym    = currentCurrencySymbol();
  const paid   = parseFloat(elPaid.value) || 0;
  const monthlySum = lineItems.reduce(function(acc, li){ return acc + (parseFloat(li.monthly_rate)||0); }, 0);
  const grand  = lineItems.reduce(function(acc, li){ return acc + (parseFloat(li.line_total)||0); }, 0);

  SUM.tenant.textContent = 'Tenant: ' + (elTenant.options[elTenant.selectedIndex]?.text || '—');
  SUM.units.textContent  = 'Units: ' + lineItems.length;
  SUM.curr.textContent   = 'Currency: ' + (sym || '—');
  SUM.monthly.textContent= 'Monthly Sum: ' + sym + ' ' + fmt2(monthlySum);
  SUM.total.textContent  = 'Grand Total: ' + sym + ' ' + fmt2(grand);
  SUM.start.textContent  = 'Start: ' + (elStart.value || '—');
  SUM.period.textContent = 'Period: ' + (elDur.value || '0') + ' ' + (elType.value === 'Y' ? 'year(s)' : 'month(s)');
  SUM.end.textContent    = 'Ends: ' + (document.getElementById('endDateDisplay').value || '—');
  SUM.paid.textContent   = 'Paid: ' + sym + ' ' + fmt2(paid);

  GRAND_TOTAL.value = fmt2(grand);
  setSymbolsEverywhere();
}

/* Tenant -> Units loader */
function loadTenantUnits(tid){
  if (!tid) {
    elMulti.innerHTML = '<option value="">-- Select Tenant First --</option>';
    return;
  }
  if (window.jQuery) {
    $.ajax({
      url: '../ajax/getunit.php',
      type: 'POST',
      data: { tid: tid, token: 'get_tenant_unit' },
      dataType: 'html',
      success: function(data){
        if (data == '-99') { window.location.href = '../index.php'; return; }
        elMulti.innerHTML = data;
      }
    });
  }
}

/* Fetch unit info */
function fetchUnit(uid, cb){
  if (!uid) return;
  if (window.jQuery) {
    $.ajax({
      url: '../ajax/getunit.php',
      type: 'POST',
      data: { uid: uid, token: 'getUnitRent' },
      dataType: 'html',
      success: function(data){
        if (data == '-99'){ window.location.href = '../index.php'; return; }
        let res;
        try { res = JSON.parse(data); } catch(e){ return; }
        cb && cb(res);
      }
    });
  }
}

/* Add selected units */
document.getElementById('btnAddSelected').addEventListener('click', function(){
  const selected = Array.from(elMulti.selectedOptions).map(function(o){ return { uid: parseInt(o.value,10), unit_no: o.text.trim() }; });
  if (selected.length === 0) return;

  let pending = selected.length;
  selected.forEach(function(sel){
    if (lineItems.some(function(li){ return li.uid === sel.uid; })) {
      if (--pending === 0) { recomputeAll(); }
      return;
    }
    fetchUnit(sel.uid, function(res){
      const mrate = (typeof res.rate !== 'undefined') ? parseFloat(res.rate) : parseFloat(res.d_rate || 0);
      const cid   = parseInt(res.rate_currency_id || 0, 10);
      const sym   = currencyMap[cid] || '¤';
      const li = {
        uid: sel.uid,
        unit_no: sel.unit_no,
        rate_currency_id: cid,
        currency_symbol: sym,
        monthly_rate: isFinite(mrate) ? mrate : 0,
        line_total: 0
      };
      lineItems.push(li);
      if (--pending === 0){
        refreshEmptyRow();
        recomputeAll();
        showPreviousInfo();
      }
    });
  });
});

function showPreviousInfo(){
  const wrap = document.getElementById('previousRentReport');
  if (lineItems.length === 0) { wrap.textContent = 'Select units to see previous periods.'; return; }
  const html = lineItems.map(function(li){ return '<div>Unit: <b>'+ (li.unit_no || li.uid) +'</b></div>'; }).join('');
  wrap.innerHTML = html;
}

/* Listeners / init */
elTenant.addEventListener('change', function(){
  loadTenantUnits(this.value);
  lineItems = [];
  renderRows();
  recomputeAll();
  stateToHidden();
});

elDur.addEventListener('input', function(){ updateEnd(); recomputeAll(); });
elDur.addEventListener('change', function(){ updateEnd(); recomputeAll(); });

elType.addEventListener('change', function(){ updateEnd(); recomputeAll(); });

elStart.addEventListener('change', function(){ updateEnd(); recomputeAll(); });
elPaid.addEventListener('input', updateSummary);

document.getElementById('addRentForm').addEventListener('submit', function(e){
  if (lineItems.length === 0){
    alert('Please add at least one unit.');
    e.preventDefault(); return false;
  }
  if (!ensureSingleCurrency()){
    alert('All selected units must share the same currency.');
    e.preventDefault(); return false;
  }
  stateToHidden();
  return true;
});

// Init
setSymbolsEverywhere();
updateEnd();
recomputeAll();

/* Back-compat wrappers */
function getUnitRent(value_element_id, rent_rate_element_id, yearly_rate_element_id, rate_currency_elem_id) {
  const uid = (window.$ ? $("#" + value_element_id).val() : null);
  if (!uid) return;
  fetchUnit(uid, function(result){
    if (rate_currency_elem_id) {
      const options = document.getElementById(rate_currency_elem_id);
      if (options) {
        for (let i = 0; i < options.length; i++) {
          let value = options[i].value;
          if (value.split("-")[0] == result["rate_currency_id"]) {
            options.value = value;
            break;
          }
        }
      }
    }
  });
}

function initGetTenantUnit(value_element_id, return_element_id, rate_rate_elem) {
  if (typeof value_element_id === "undefined" || typeof return_element_id === "undefined") return;
  const tid = (window.$ ? $("#" + value_element_id).val() : null);
  if (!tid) {
    const placeholder = '<option value="">--Select Tenant First--</option>';
    if (window.$) $("#" + return_element_id).html(placeholder);
    return;
  }
  if (window.$) {
    $.ajax({
      url: '../ajax/getunit.php',
      type: 'POST',
      data: '&tid=' + tid + '&token=get_tenant_unit',
      dataType: 'html',
      success: function(data) {
        if (data != '-99') {
          $("#" + return_element_id).html(data);
        } else {
          window.location.href = '../index.php';
        }
      }
    });
  }
}
</script>

<?php include_once('../footer.php'); ?>
