<?php
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();
}

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

/* -------------------------------------------------
   Helpers & Defaults
------------------------------------------------- */
function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$title          = $_data['add_new_service'];
$button_text    = $_data['save_button_text'];
$success_msg    = $_data['added_service_successfully'];
$form_url       = WEB_URL . "service_fee/addservicefee.php?action=add";

$tid            = 0;
$uid            = null;
$issue_date     = '';
$amt_paid       = '0';
$period         = '';
$period_type    = 'Y';
$start_date     = '';
$end_date       = '';

/* Load 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 = $currencies ? $currencies[0]['symbol'] : '$';

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

  if (isset($_GET["action"]) && $_GET["action"] === "add") {
    // 'rate_currency' is "cid-exchangerate"
    $tmp                  = explode("-", $data['rate_currency']);
    $rate_currency_id     = isset($tmp[0]) ? (int)$tmp[0] : 0;
    $currency_exchange    = isset($tmp[1]) ? (float)$tmp[1] : 1.0;

    $rent_rate   = (float)($data['rent_rate'] ?? 0);     // monthly service fee
    $duration    = (int)($data['duration'] ?? 0);
    $period_type = $data['period_type'] === 'M' ? 'M' : 'Y';

    // Dates
    $startDate = date('Y-m-d', strtotime($data['txtStartDate'])); // calendar input
    $start_ts  = strtotime($startDate);
    if ($period_type === 'Y') {
      $endDate = date('Y-m-d', strtotime("+{$duration} years",  $start_ts));
    } else {
      $endDate = date('Y-m-d', strtotime("+{$duration} months", $start_ts));
    }

    // Totals
    $rent_yearly = number_format($rent_rate * 12, 2, ".", "");
    $rent_total  = ($period_type === 'Y')
      ? number_format(($rent_rate * 12) * $duration, 2, ".", "")
      : number_format($rent_rate * $duration,        2, ".", "");

    // Insert into service_fee
    $sql = sprintf(
      "INSERT INTO `service_fee`
        (`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`)
       VALUES (%d,%d,%.2f,%d,%.4f,%.2f,%d,'%s',%.2f,'%s','%s','%s',%d,%.2f)",
      (int)$data['uid'], (int)$data['tid'], $rent_rate, $rate_currency_id, $currency_exchange, $rent_yearly,
      $duration, $link->real_escape_string($period_type), (float)($data['amt_paid'] ?: 0),
      $link->real_escape_string($startDate), $link->real_escape_string($endDate),
      $link->real_escape_string($_POST['txtIssueDate']), (int)$_SESSION['user_id'], $rent_total
    );
    $link->query($sql);
    $service_id = $link->insert_id;

    // Description
    $unit_no = '';
    if ($r = $link->query("SELECT unit_no FROM units WHERE uid=".(int)$data['uid'])->fetch_assoc()) {
      $unit_no = $r['unit_no'];
    }
    $desc = "Service Fee on unit {$unit_no} for {$duration} ".($period_type === 'Y' ? 'year(s)' : 'month(s)');

    // Tenant service account (credit full bill)
    $link->query(sprintf(
      "INSERT INTO `tenant_service_accounts`
        (`tid`,`rid`,`trans_type`,`description`,`transaction_amt`,`added_by`)
       VALUES (%d,%d,'credit','%s',%.2f,%d)",
      (int)$data['tid'], $service_id, $link->real_escape_string($desc), $rent_total, (int)$_SESSION['user_id']
    ));

    // Route to main vs foreign account (currency id 15 assumed 'main/local')
    $current_year = date('Y');
    $amount_for_account = ($period_type === 'Y') ? ($rent_rate * 12 * $duration) : ($rent_rate * $duration);
    if ($rate_currency_id === 15) {
      $link->query(sprintf(
        "INSERT INTO `service_main_account`
          (`rent_id`,`fiscal_year`,`trans_type`,`amount`,`added_by`)
         VALUES (%d,%d,'debit',%.2f,%d)",
        $service_id, $current_year, $amount_for_account, (int)$_SESSION['user_id']
      ));
    } else {
      $link->query(sprintf(
        "INSERT INTO `foreign_currency_service_main_account`
          (`rent_id`,`fiscal_year`,`trans_type`,`amount`,`added_by`)
         VALUES (%d,%d,'debit',%.2f,%d)",
        $service_id, $current_year, $amount_for_account, (int)$_SESSION['user_id']
      ));
    }

    // Immediate payment?
    $amt_paid_now = (float)($data['amt_paid'] ?: 0);
    if ($amt_paid_now > 0) {
      $link->query(sprintf(
        "INSERT INTO `tenant_service_accounts`
          (`tid`,`rid`,`trans_type`,`description`,`transaction_amt`,`added_by`)
         VALUES (%d,%d,'debit','Service Fee Payment From Tenant',%.2f,%d)",
        (int)$data['tid'], $service_id, $amt_paid_now, (int)$_SESSION['user_id']
      ));
      $link->query(sprintf(
        "INSERT INTO `service_payment_updates` (`rent_id`,`amount`,`added_by`)
         VALUES (%d,%.2f,%d)",
        $service_id, $amt_paid_now, (int)$_SESSION['user_id']
      ));
      if ($amt_paid_now >= (float)$rent_total) {
        // If your table has bill_status
        @$link->query("UPDATE `service_fee` SET `bill_status`=1 WHERE id=".$service_id);
      }
    }

    $_SESSION["message"] = "Service Fee Added Successfully";
    header("Location: " . WEB_URL . 'service_fee/servicelist.php');
    exit();
  }

  // UPDATE (prefill is supported, but UI below is focused on Add UX)
  if (isset($_GET['action']) && $_GET['action'] === 'update' && !empty($_GET['id']) && is_numeric($_GET['id'])) {
    // Implement your update logic here as needed.
    // ...
    $_SESSION["message"] = "Service Fee Updated Successfully";
    header("Location: " . WEB_URL . 'service_fee/servicelist.php');
    exit();
  }
}

/* -------------------------------------------------
   Edit pre-fill (optional)
------------------------------------------------- */
if (!empty($_GET['id'])) {
  $res = $link->query("SELECT * FROM service_fee WHERE id = ".(int)$_GET['id']." LIMIT 1");
  if ($row = $res->fetch_assoc()) {
    $tid         = (int)$row['tid'];
    $uid         = (int)$row['uid'];
    $amt_paid    = $row['amt_paid'];
    $issue_date  = $row['issue_date'];
    $period      = $row['period'];
    $period_type = $row['period_type'];
    $start_date  = $row['start_date'];
    $end_date    = $row['end_date'];

    $title       = $_data['update_service'];
    $button_text = $_data['update_button_text'];
    $success_msg = $_data['update_service_successfully'];
    $form_url    = WEB_URL . "service_fee/addservicefee.php?id=".(int)$_GET['id']."&action=update";
  }
}
?>
<!-- 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>

<!-- Friendly 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 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; }

  .form-grid{ display:grid; grid-template-columns: 1fr 360px; gap:16px; align-items:start; }
  @media (max-width: 1100px){ .form-grid{ grid-template-columns: 1fr; } }

  .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:var(--brand-2); }

  .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:var(--muted); border-radius:12px; }

  .switch{ margin-left:8px; }
  .locked { opacity:.6; }

  .totals-grid{ display:grid; grid-template-columns: 1fr 1fr; gap:10px; }
  @media (max-width: 520px){ .totals-grid{ grid-template-columns: 1fr; } }

  /* Flatpickr polish */
  .flatpickr-calendar {
    border-radius: 12px;
    box-shadow: 0 12px 28px rgba(2,6,23,.15);
    border: 1px solid #e5e7eb;
    font-family: 'Inter', system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial;
  }
  .flatpickr-day.selected, .flatpickr-day.startRange, .flatpickr-day.endRange {
    background: #2563eb;
    border-color: #2563eb;
  }
  .flatpickr-day.today { border-color: #93c5fd; }
</style>

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

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

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

            <div class="row">
              <!-- Tenant -->
              <div class="form-group col-md-6">
                <label><span style="color:var(--danger)">*</span> Tenant</label>
                <div class="input-group">
                  <span class="input-group-addon"><i class="fa fa-user"></i></span>
                  <select required onchange="getTenantUnit('tid','uid','rent_rate','yearly_rate');" 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 = $result_tenant->fetch_assoc()) { ?>
                        <option value="<?= (int)$row_tenant['tid']; ?>" <?= ($tid == (int)$row_tenant['tid']) ? 'selected':''; ?>>
                          <?= e($row_tenant['r_name']); ?>
                        </option>
                    <?php } ?>
                  </select>
                </div>
                <div class="help-note">Choose a tenant to see their linked units.</div>
              </div>

              <!-- Unit -->
              <div class="form-group col-md-6">
                <label><span style="color:var(--danger)">*</span> <?= e($_data['add_new_form_field_text_3']);?></label>
                <input type="hidden" id="uid_edit" value="<?= isset($uid) ? (int)$uid : ""; ?>" />
                <div class="input-group">
                  <span class="input-group-addon"><i class="fa fa-building-o"></i></span>
                  <select required name="uid" id="uid" class="form-control">
                    <option value="">-- <?= e($_data['add_new_form_field_text_4']);?> --</option>
                    <!-- Populated by getTenantUnit(...) -->
                  </select>
                </div>
              </div>
            </div>

            <hr>

            <h4 class="section-title"><i class="fa fa-money"></i> Service Fee & Period</h4>

            <div class="row">
              <!-- Monthly Fee + Currency (AUTO from unit; toggle to override) -->
              <div class="form-group col-md-6">
                <label><span style="color:var(--danger)">*</span> Monthly Service Fee</label>
                <div style="display:flex; align-items:center; gap:10px;">
                  <div class="input-group" style="flex:1;">
                    <span class="input-group-addon" style="padding:0;">
                      <select class="form-control locked" name="rate_currency" id="rate_currency" required style="border:0;border-radius:12px 0 0 12px;height:42px;" disabled>
                        <?php foreach ($currencies as $c): ?>
                          <?php $val = (int)$c['cid'].'-'.e($c['exchange_rate']); ?>
                          <option value="<?= $val; ?>"><?= e($c['symbol']); ?></option>
                        <?php endforeach; ?>
                      </select>
                    </span>
                    <input
                      id="rent_rate"
                      name="rent_rate"
                      type="number"
                      min="0"
                      step="0.01"
                      class="form-control"
                      placeholder="0.00"
                      disabled
                    />
                  </div>
                  <label class="switch" data-toggle="tooltip" data-placement="top" title="Enable to manually edit fee & currency">
                    <input type="checkbox" id="set_rate">
                    <span class="slider"></span>
                  </label>
                </div>
                <div class="help-note">Defaults come from the selected unit. Toggle to override.</div>
              </div>

              <div class="form-group col-md-6">
                <label>Yearly Equivalent</label>
                <div class="input-group">
                  <div class="input-group-addon" id="sym_year"><?= e($default_currency_symbol); ?></div>
                  <input readonly type="text" id="yearly_rate" class="form-control" placeholder="0.00" />
                </div>
              </div>
            </div>

            <!-- Start date + Period -->
            <div class="row">
              <div class="form-group col-md-6">
                <label><span style="color:var(--danger)">*</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" value="<?= e($start_date); ?>" />
                </div>
                <div class="help-note">Pick a start date. End date will be calculated automatically when you enter period.</div>
              </div>

              <div class="form-group col-md-6">
                <label><span style="color:var(--danger)">*</span> Period</label>
                <div class="input-group">
                  <input type="number" min="0" required name="duration" value="<?= e($period ?: ""); ?>" id="duration" class="form-control" placeholder="0" />
                  <div class="input-group-addon" style="padding:0;">
                    <select name="period_type" id="period_type" required style="border:0;height:44px;width:5.2em;border-radius:0 12px 12px 0;">
                      <option value="Y" <?= $period_type==='Y'?'selected':''; ?>>Years</option>
                      <option value="M" <?= $period_type==='M'?'selected':''; ?>>Months</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>

            <!-- End Date (auto) -->
            <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" value="<?= e($end_date); ?>" />
                </div>
                <input type="hidden" name="end_date" id="end_date" value="<?= e($end_date); ?>" />
              </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"><?= e($default_currency_symbol); ?></div>
                  <input type="number" step="0.01" min="0"
                         name="amt_paid" id="amt_paid"
                         value="<?= e($amt_paid ?: '0'); ?>"
                         class="form-control" />
                </div>
              </div>

              <div class="form-group col-md-6">
                <label><span style="color:var(--danger)">*</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>

            <div class="row">
              <!-- Totals -->
              <div class="form-group col-md-6">
                <label>Total Amount</label>
                <div class="input-group">
                  <div class="input-group-addon" id="sym_total"><?= e($default_currency_symbol); ?></div>
                  <input type="text" id="total_amount" class="form-control" readonly placeholder="0.00" />
                </div>
              </div>
              <div class="form-group col-md-6">
                <label>Balance</label>
                <div class="input-group">
                  <div class="input-group-addon" id="sym_bal"><?= e($default_currency_symbol); ?></div>
                  <input type="text" id="balance" class="form-control" readonly placeholder="0.00" />
                </div>
              </div>
            </div>
          </div>

          <!-- Right: 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_unit">Unit: —</span></div>
              <div class="pill"><i class="fa fa-money"></i> <span id="sum_rate">Monthly: —</span></div>
              <div class="pill"><i class="fa fa-arrow-right"></i> <span id="sum_yearly">Yearly: —</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-calculator"></i> <span id="sum_total">Total: —</span></div>
              <div class="pill"><i class="fa fa-credit-card"></i> <span id="sum_paid">Paid: —</span></div>
              <div class="pill"><i class="fa fa-balance-scale"></i> <span id="sum_balance">Balance: —</span></div>
            </div>
            <div class="help-note" style="margin-top:10px;">This panel updates as you fill the form.</div>
          </aside>

        </div>

        <div class="box-footer" style="padding:16px 0 0; display:flex; justify-content:flex-end; gap:10px;">
          <button type="submit" name="btnSavePrint" class="btn btn-default">
            <i class="fa fa-print"></i> <?= e($_data['save_and_invoice']);?>
          </button>
          <button type="submit" name="btnSave" class="btn btn-success">
            <i class="fa fa-floppy-o"></i> <?= e($button_text); ?>
          </button>
          <a class="btn btn-warning" href="<?= WEB_URL; ?>service_fee/servicelist.php">
            <i class="fa fa-reply"></i> <?= e($_data['back_text']);?>
          </a>
        </div>

      </form>
    </div>
  </div>
</section>

<!-- Page JS (your existing util file if any) -->
<script src="<?= WEB_URL; ?>assets/js/addservicefee.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.js"></script>

<script>
  // ---------- Currency map (value "cid-exrate" -> symbol) ----------
  const currencyMap = {
    <?php foreach ($currencies as $c):
      $val = (int)$c['cid'] . '-' . $c['exchange_rate'];
      $sym = $c['symbol'];
    ?>
      "<?= $val ?>": "<?= e($sym) ?>",
    <?php endforeach; ?>
  };

  // Elements
  const selCurrency = document.getElementById('rate_currency');  // visible selector (disabled until override)
  const rentRate    = document.getElementById('rent_rate');
  const toggle      = document.getElementById('set_rate');

  const symYear  = document.getElementById('sym_year');
  const symPaid  = document.getElementById('sym_paid');
  const symTotal = document.getElementById('sym_total');
  const symBal   = document.getElementById('sym_bal');

  const yearly   = document.getElementById('yearly_rate');
  const elTenant = document.getElementById('tid');
  const elUnit   = document.getElementById('uid');

  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 totalEl  = document.getElementById('total_amount');
  const balEl    = document.getElementById('balance');

  // Summary
  const S = {
    tenant:  document.getElementById('sum_tenant'),
    unit:    document.getElementById('sum_unit'),
    rate:    document.getElementById('sum_rate'),
    yearly:  document.getElementById('sum_yearly'),
    start:   document.getElementById('sum_start'),
    period:  document.getElementById('sum_period'),
    end:     document.getElementById('sum_end'),
    total:   document.getElementById('sum_total'),
    paid:    document.getElementById('sum_paid'),
    balance: document.getElementById('sum_balance')
  };

  // Toggle manual edit
  function applyLockState() {
    const manual = toggle.checked;
    rentRate.disabled = !manual;
    selCurrency.disabled = !manual;
    selCurrency.classList.toggle('locked', !manual);
  }
  toggle.addEventListener('change', applyLockState);

  function currentSymbol(){
    const opt = selCurrency.options[selCurrency.selectedIndex];
    return opt ? (opt.textContent || '').trim() : "<?= addslashes($default_currency_symbol) ?>";
  }
  function setSymbols(){
    const sym = currentSymbol();
    symYear.textContent  = sym;
    symPaid.textContent  = sym;
    symTotal.textContent = sym;
    symBal.textContent   = sym;
    updateSummary();
  }

  function calcYearly(){
    const m = parseFloat(rentRate.value) || 0;
    yearly.value = (m * 12).toFixed(2);
  }

  function textOfSelect(sel){
    const opt = sel && sel.options[sel.selectedIndex];
    return opt ? opt.textContent.trim() : '—';
  }

  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}`;
  }

  function parseDateInput(val){
    if (!val) return null;
    const dt = new Date(val);
    return isNaN(dt) ? null : dt;
  }

  // End date calculator (Start + Duration (Y/M))
  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 dt.setMonth(dt.getMonth() + dur);

    const out = fmtDate(dt);
    elEndDisp.value = out;
    elEnd.value     = out;
    recalcTotals(); // refresh totals when end changes
  }

  // Total amount & balance
  function recalcTotals(){
    calcYearly();
    const rate   = parseFloat(rentRate.value) || 0; // monthly
    const dur    = parseInt(elDur.value || '0', 10);
    const type   = elType.value;

    let total = 0;
    if (type === 'Y') total = (rate * 12) * dur;
    else total = rate * dur;

    totalEl.value = total.toFixed(2);
    const paid    = parseFloat(elPaid.value) || 0;
    balEl.value   = (total - paid).toFixed(2);
    updateSummary();
  }

  // Summary
  function updateSummary(){
    const sym   = currentSymbol();
    const rateM = parseFloat(rentRate.value) || 0;
    const yVal  = parseFloat(yearly.value) || 0;
    const paid  = parseFloat(elPaid.value) || 0;
    const total = parseFloat(totalEl.value) || 0;
    const bal   = parseFloat(balEl.value) || 0;

    S.tenant.textContent = 'Tenant: ' + textOfSelect(elTenant);
    S.unit.textContent   = 'Unit: '   + textOfSelect(elUnit);
    S.rate.textContent   = 'Monthly: ' + sym + ' ' + rateM.toFixed(2);
    S.yearly.textContent = 'Yearly: '  + sym + ' ' + yVal.toFixed(2);
    S.start.textContent  = 'Start: '   + (elStart.value || '—');
    S.period.textContent = 'Period: '  + (elDur.value || '0') + ' ' + (elType.value === 'Y' ? 'year(s)' : 'month(s)');
    S.end.textContent    = 'Ends: '    + (elEndDisp.value || '—');
    S.total.textContent  = 'Total: '   + sym + ' ' + total.toFixed(2);
    S.paid.textContent   = 'Paid: '    + sym + ' ' + paid.toFixed(2);
    S.balance.textContent= 'Balance: ' + sym + ' ' + bal.toFixed(2);
  }

  // When user manually changes currency (only works if toggle=ON)
  selCurrency.addEventListener('change', function(){
    setSymbols();
    recalcTotals();
  });

  // When unit changes, fetch defaults for that unit (rate & currency) and apply
  function fetchUnitDefaults(uid){
    if (!uid) return;
    // Try an endpoint you have; sample payload expected: { success, rate, currency_cid, exchange_rate }
    if (window.jQuery) {
      $.ajax({
        url: "<?= WEB_URL; ?>ajax/get_unit_defaults.php",
        type: "POST",
        dataType: "json",
        data: { uid: uid },
        success: function(res){
          if (res && res.success) {
            setUnitDefaults({
              rate: res.rate || 0,
              currencyCid: res.currency_cid,
              exchangeRate: res.exchange_rate
            });
          }
        }
      });
    }
  }

  // Set defaults from unit (keep controls locked unless toggle is ON)
  function setUnitDefaults({ rate, currencyCid, exchangeRate }) {
    // set currency select to unit currency (even if disabled)
    const targetVal = `${currencyCid}-${exchangeRate}`;
    for (const opt of selCurrency.options) {
      if (opt.value == targetVal) { selCurrency.value = opt.value; break; }
    }
    setSymbols();

    // set monthly rate
    rentRate.value = (rate ?? 0);
    recalcTotals();
  }

  // Wire events
  elUnit.addEventListener('change', function(){
    fetchUnitDefaults(this.value);
    updateSummary();
  });
  elTenant.addEventListener('change', updateSummary);

  rentRate.addEventListener('input', recalcTotals);
  elPaid.addEventListener('input', recalcTotals);

  elStart.addEventListener('change', updateEnd);
  elDur.addEventListener('input',  updateEnd);
  elType.addEventListener('change', updateEnd);

  // Initialize flatpickr
  (function initPickers(){
    if (!window.flatpickr) return;
    const 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(); }
    }));
  })();

  // Initial UI sync
  applyLockState();    // keep locked by default
  setSymbols();
  calcYearly();
  updateEnd();
  recalcTotals();
  if (window.$ && $.fn.tooltip) $('[data-toggle="tooltip"]').tooltip();
</script>

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