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

// index.php / bootstrap
ini_set('display_errors', '1');
error_reporting(E_ALL);


/* -------------------------------------------------
   Defaults
------------------------------------------------- */
$title        = $_data['add_new_rent'];
$button_text  = $_data['save_button_text'];
$form_url     = WEB_URL . "rent/addrent.php?action=add";

$tid          = 0;
$uid          = null;
$issue_date   = '';
$amt_paid     = '0';
$hdnid        = "0";
$r_description = ''; // NEW: default description

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

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

  /* CREATE */
  if (isset($_GET["action"]) && $_GET["action"] === "add") {
    // Hidden field 'rate_currency' carries "cid-exchangerate" (from UNIT or manual override)
    $tmp                = explode("-", $data['rate_currency']);
    $rent_currency_id   = isset($tmp[0]) ? (int)$tmp[0] : 0;
    $rent_exchange_rate = isset($tmp[1]) ? (float)$tmp[1] : 1.0;

    $rent_rate     = (float)($data['rent_rate'] ?? 0);
    $duration_days = (int)($data['duration'] ?? 0);
    $amt_paid      = (float)($data['amt_paid'] ?? 0);

    // NEW: description (TEXT column r_description)
    $r_description = isset($data['r_description']) ? $link->real_escape_string($data['r_description']) : '';

    $startDate = date("Y-m-d", strtotime($data['startDate']));
    $endDate   = date("Y-m-d", strtotime("+$duration_days days", strtotime($startDate)));
    $raw_total = $rent_rate * $duration_days;

    // Unit name for description
    $unit_name = mysqli_fetch_assoc($link->query("SELECT unit_no FROM units WHERE uid = ".(int)$data['uid']));
    $unitNo    = $unit_name ? $unit_name['unit_no'] : '';

    /* -------------------- CONFLICT CHECK -------------------- */
    $stmt = $link->prepare("
      SELECT start_date, end_date
      FROM rent
      WHERE uid = ?
        AND start_date <= ?
        AND end_date >= ?
    ");
    $stmt->bind_param('iss', $data['uid'], $endDate, $startDate);
    $stmt->execute();
    $confRes = $stmt->get_result();

    $hasConflict = false;
    $totalOverlapDays = 0;
    $onlyBoundaryOverlap = true;

    while ($rowC = $confRes->fetch_assoc()) {
      $s1 = max(strtotime($startDate), strtotime($rowC['start_date']));
      $e1 = min(strtotime($endDate),   strtotime($rowC['end_date']));
      if ($e1 >= $s1) {
        $overlapDays = (int)(($e1 - $s1) / 86400) + 1; // inclusive
        $totalOverlapDays += $overlapDays;

        $isBoundary =
          ($overlapDays === 1) &&
          (
            ($endDate   === $rowC['start_date']) ||
            ($startDate === $rowC['end_date'])
          );

        if (!$isBoundary) {
          $onlyBoundaryOverlap = false;
        }
        $hasConflict = true;
      }
    }
    $stmt->close();

    if ($hasConflict && !($onlyBoundaryOverlap && $totalOverlapDays === 1)) {
      $_SESSION['message']      = "Error: The selected rent period conflicts with an existing rent.";
      $_SESSION['message_type'] = 'error';
      header("Location: " . WEB_URL . 'rent/rentlist.php');
      exit();
    }
    /* ------------------ END CONFLICT CHECK ------------------ */

    // Insert rent (store the UNIT currency exactly as chosen/derived)
    $sqlRent = sprintf(
      "INSERT INTO `rent`
        (`uid`,`tid`,`rate`,`rate_currency_id`,`currency_exchange_rate`,
         `period`,`period_type`,`amt_paid`,`start_date`,`end_date`,
         `issue_date`,`added_by`,`total_rent`,`r_description`)
       VALUES
        (%d, %d, %.2f, %d, %.4f,
         %d, 'D', %.2f, '%s', '%s',
         '%s', %d, %.2f, '%s')",
      (int)$data['uid'], (int)$data['tid'], $rent_rate, $rent_currency_id, $rent_exchange_rate,
      $duration_days, $amt_paid, $startDate, $endDate,
      $link->real_escape_string($_POST['txtIssueDate']), (int)$_SESSION['user_id'], $raw_total, $r_description
    );
    $link->query($sqlRent);
    $rent_id = $link->insert_id;

    // Tenant account (credit full bill)
    $current_year = date('Y');
    $desc         = sprintf("Rent processed on unit %s for %d day(s)", $unitNo, $duration_days);
    $sqlTA = sprintf(
      "INSERT INTO `tenant_accounts` (`tid`,`rid`,`trans_type`,`description`,`transaction_amt`,`added_by`)
       VALUES (%d, %d, 'credit', '%s', %.2f, %d)",
      (int)$data['tid'], $rent_id, $link->real_escape_string($desc), $raw_total, (int)$_SESSION['user_id']
    );
    $link->query($sqlTA);

    // Route to main vs foreign account based on currency ID (example: 15 = GHS; adjust to your schema)
    if ($rent_currency_id === 15) {
      $sql_main = "INSERT INTO main_account (rent_id, fiscal_year, trans_type, amount, added_by)
                   VALUES ($rent_id, $current_year, 'debit', $raw_total, ".$_SESSION['user_id'].")";
      $link->query($sql_main);
    } else {
      $sql_fx   = "INSERT INTO foreign_currency_main_account (rent_id, fiscal_year, trans_type, amount, added_by)
                   VALUES ($rent_id, $current_year, 'debit', $raw_total, ".$_SESSION['user_id'].")";
      $link->query($sql_fx);
    }

    // Optional: capture initial payment
    if ($amt_paid > 0) {
      $link->query("INSERT INTO `tenant_accounts`
                      (`tid`,`rid`,`trans_type`,`description`,`transaction_amt`,`added_by`)
                    VALUES
                      (".(int)$data['tid'].", $rent_id, 'debit', 'Rent Payment From Tenant', $amt_paid, ".(int)$_SESSION['user_id'].")");

      $link->query("INSERT INTO `rent_payment_updates` (`rent_id`,`amount`,`added_by`)
                    VALUES ($rent_id, $amt_paid, ".(int)$_SESSION['user_id'].")");

      if ($amt_paid >= $raw_total) {
        $link->query("UPDATE `rent` SET `bill_status` = 1 WHERE id = $rent_id");
      }
    }

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

  /* UPDATE (legacy path) */
  if (isset($_GET['action']) && $_GET['action'] === 'update' && !empty($_GET['id']) && is_numeric($_GET['id'])) {
    // NEW: description on update as well
    $r_description = isset($_POST['r_description']) ? $link->real_escape_string($_POST['r_description']) : '';

    $sql = "UPDATE `rent` SET 
        `b_name`       ='".$link->real_escape_string($_POST['b_name'])."',
        `unit_no`      ='".$link->real_escape_string($_POST['ddlUnitNo'])."',
        `tid`          ='".$link->real_escape_string($_POST['hdnRentedId'])."',
        `month_id`     ='".$link->real_escape_string($_POST['ddlMonth'])."',
        `xyear`        ='".$link->real_escape_string($_POST['ddlYear'])."',
        `rate`         ='".$link->real_escape_string($_POST['txtRent'])."',
        `water_bill`   ='".$link->real_escape_string($_POST['txtWaterBill'])."',
        `electric_bill`='".$link->real_escape_string($_POST['txtElectricBill'])."',
        `gas_bill`     ='".$link->real_escape_string($_POST['txtGasBill'])."',
        `security_bill`='".$link->real_escape_string($_POST['txtSecurityBill'])."',
        `utility_bill` ='".$link->real_escape_string($_POST['txtUtilityBill'])."',
        `other_bill`   ='".$link->real_escape_string($_POST['txtOtherBill'])."',
        `total_rent`   ='".$link->real_escape_string($_POST['txtTotalRent'])."',
        `issue_date`   ='".$link->real_escape_string($_POST['txtIssueDate'])."',
        `paid_date`    ='".$link->real_escape_string($_POST['txtPaidDate'])."',
        `bill_status`  ='".$link->real_escape_string($_POST['ddlBillStatus'])."',
        `r_description`='".$r_description."'
      WHERE id=".(int)$_GET['id'];
    $_SESSION['message'] = $link->query($sql) ? "Rent Updated Successfully" : "Failed to Update Rent";
    header("Location: " . WEB_URL . 'rent/rentlist.php');
    exit();
  }
}

/* -------------------------------------------------
   Edit pre-fill (if any)
------------------------------------------------- */
if (!empty($_GET['id'])) {
  $res = $link->query("SELECT * FROM rent 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'];
    $r_description = isset($row['r_description']) ? $row['r_description'] : ''; // NEW: prefill
    $title         = $_data['update_rent'];
    $button_text   = $_data['update_button_text'];
    $form_url      = WEB_URL . "rent/addrent.php?id=".(int)$_GET['id']."&action=update";
  }
}
?>
<!-- Page Header -->
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;">
    <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><?= htmlspecialchars($title); ?></span>
  </h1>
  <ol class="breadcrumb">
    <li><a href="<?= WEB_URL?>dashboard.php"><i class="fa fa-dashboard"></i> <?= $_data['home_breadcam'];?></a></li>
    <li class="active"><?= $_data['add_new_rent_information_breadcam'];?></li>
    <li class="active"><?= htmlspecialchars($title); ?></li>
  </ol>
</section>

<!-- 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" />
<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 380px; 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; }
  .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 */
  .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"><?= $_data['add_new_rent_entry_form'];?></h3>
    </div>

    <div class="box-body">
      <form id="addRentForm" name="addRentForm" action="<?= htmlspecialchars($form_url); ?>" method="post" enctype="multipart/form-data">
        <div class="form-grid">
          <!-- Left: Form fields -->
          <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 for="tid"><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':''; ?>>
                        <?= htmlspecialchars($row_tenant['r_name']); ?>
                      </option>
                    <?php } ?>
                  </select>
                </div>
                <div class="help-note">Choose a tenant to see linked units.</div>
              </div>

              <!-- Unit -->
              <div class="form-group col-md-6">
                <label for="uid"><span style="color:var(--danger)">*</span> <?= $_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="">-- <?= $_data['add_new_form_field_text_4'];?> --</option>
                    <!-- Populated by getTenantUnit(...) -->
                  </select>
                </div>
              </div>
            </div>

            <div class="row">
              <!-- End of previous rent -->
              <div class="form-group col-md-12">
                <label>End of Previous Rent</label>
                <div id="previousRentReport" class="alert info-block" style="margin:0;">N/A</div>
              </div>
              <!-- Available dates -->
              <div class="form-group col-md-12">
                <label>Available Dates (Next 6 Months)</label>
                <div id="availableDates" class="alert info-block" style="margin:0;">N/A</div>
              </div>
            </div>

            <hr>

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

            <div class="row">
              <!-- Daily Rate + Currency (AUTO from unit; toggle only if overriding) -->
              <div class="form-group col-md-6">
                <label for="rent_rate"><span style="color:var(--danger)">*</span> Daily Rate</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;">
                      <!-- VISIBLE SELECT for currency (disabled until override) -->
                      <select class="form-control locked" id="rate_currency_ui" required style="border:0;border-radius:12px 0 0 12px;height:42px;" disabled>
                        <?php foreach ($currencies as $c): ?>
                          <option value="<?= (int)$c['cid'].'-'.htmlspecialchars($c['exchange_rate']); ?>">
                            <?= htmlspecialchars($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 rate & currency">
                    <input type="checkbox" id="set_rate">
                    <span class="slider"></span>
                  </label>
                </div>
                <div class="help-note">By default, rate & currency come from the selected unit. Toggle to override.</div>
                <!-- HIDDEN FIELD actually posted -->
                <input type="hidden" name="rate_currency" id="rate_currency" value="">
              </div>

              <!-- Start -->
              <div class="form-group col-md-3">
                <label for="startDate"><span style="color:var(--danger)">*</span> Start Date</label>
                <div class="input-group">
                  <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                  <input type="text" class="form-control date-input" name="startDate" id="startDate" required placeholder="YYYY-MM-DD" inputmode="none" />
                </div>
              </div>
              <!-- End -->
              <div class="form-group col-md-3">
                <label for="endDate"><span style="color:var(--danger)">*</span> End Date</label>
                <div class="input-group">
                  <span class="input-group-addon"><i class="fa fa-calendar-check-o"></i></span>
                  <input type="text" class="form-control date-input" name="endDate" id="endDate" required placeholder="YYYY-MM-DD" inputmode="none" />
                </div>
              </div>

              <input type="hidden" name="duration" id="duration" value="" />
            </div>

            <div class="row">
              <!-- Totals -->
              <div class="form-group col-md-12">
                <div class="totals-grid">
                  <div>
                    <label>Total Amount</label>
                    <div class="input-group">
                      <div class="input-group-addon" id="sym_total">¤</div>
                      <input type="text" id="total_amount" class="form-control" readonly placeholder="0.00" />
                    </div>
                  </div>
                  <div>
                    <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"
                             name="amt_paid" id="amt_paid"
                             value="<?= htmlspecialchars($amt_paid ?: '0'); ?>"
                             class="form-control"
                             onkeyup="calcBalance('amt_paid','total_amount','balance');"
                             onchange="calcBalance('amt_paid','total_amount','balance');" />
                    </div>
                  </div>
                </div>
              </div>

              <div class="form-group col-md-6" style="display:none;">
                <label>Balance</label>
                <div class="input-group">
                  <div class="input-group-addon" id="sym_bal">¤</div>
                  <input type="text" id="balance" class="form-control" readonly placeholder="0.00" />
                </div>
              </div>

              <!-- Issue Date -->
              <div class="form-group col-md-6">
                <label for="txtIssueDate"><span style="color:var(--danger)">*</span> <?= $_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="<?= htmlspecialchars($issue_date); ?>" id="txtIssueDate" class="form-control date-input" placeholder="YYYY-MM-DD" inputmode="none" />
                </div>
              </div>
            </div>

            <!-- NEW: Description / Notes -->
            <div class="row">
              <div class="form-group col-md-12">
                <label for="r_description">Description / Notes</label>
                <textarea class="form-control" name="r_description" id="r_description" rows="4" placeholder="Optional notes about this rent..."><?= htmlspecialchars($r_description); ?></textarea>
                <!-- <div class="help-note">Saved into <code>rent.r_description</code>.</div> -->
              </div>
            </div>

          </div>

          <!-- Right: 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_unit">Unit: —</span></div>
              <div class="pill"><i class="fa fa-money"></i> <span id="sum_rate">Rate: —</span></div>
              <div class="pill"><i class="fa fa-calendar"></i> <span id="sum_dates">Dates: —</span></div>
              <div class="pill"><i class="fa fa-hashtag"></i> <span id="sum_days">Duration: — day(s)</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-sticky-note"></i> <span id="sum_desc">Description: —</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> <?= $_data['save_and_invoice']; ?>
          </button>
          <button type="submit" name="btnSave" class="btn btn-success">
            <i class="fa fa-floppy-o"></i> <?= htmlspecialchars($button_text); ?>
          </button>
          <a class="btn btn-warning" href="<?= WEB_URL; ?>rent/rentlist.php">
            <i class="fa fa-reply"></i> <?= $_data['back_text']; ?>
          </a>
        </div>

        <input type="hidden" value="<?= htmlspecialchars($hdnid); ?>" name="hdn"/>
      </form>
    </div>
  </div>
</section>

<!-- Page JS (your existing helpers, OK to keep) -->
<script src="<?= WEB_URL; ?>assets/js/addrent.js"></script>

<!-- Flatpickr 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
    }));

    var start = document.getElementById('startDate');
    var end   = document.getElementById('endDate');

    var fpStart = flatpickr(start, Object.assign({}, opts, {
      onChange: function(selectedDates){
        if (selectedDates && selectedDates[0]) fpEnd.set('minDate', selectedDates[0]);
        start.dispatchEvent(new Event('change'));
      }
    }));
    var fpEnd = flatpickr(end, Object.assign({}, opts, {
      onChange: function(){ end.dispatchEvent(new Event('change')); }
    }));
    if (start.value) fpEnd.set('minDate', start.value);
  }

  if (window.flatpickr) { initPickers(); return; }

  var link1 = document.createElement('link');
  link1.rel  = 'stylesheet';
  link1.href = 'https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.css';
  document.head.appendChild(link1);

  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 (value "cid-exrate" -> symbol) ----------
  const currencyMap = {
    <?php foreach ($currencies as $c):
      $val = (int)$c['cid'] . '-' . $c['exchange_rate'];
      $sym = $c['symbol'];
    ?>
      "<?= $val ?>": "<?= htmlspecialchars($sym) ?>",
    <?php endforeach; ?>
  };

  // Elements
  const selUI   = document.getElementById('rate_currency_ui'); // visible selector (disabled until override)
  const selPost = document.getElementById('rate_currency');     // hidden, always posted
  const rateInp = document.getElementById('rent_rate');
  const toggle  = document.getElementById('set_rate');

  const elTenant = document.getElementById('tid');
  const elUnit   = document.getElementById('uid');
  const elStart  = document.getElementById('startDate');
  const elEnd    = document.getElementById('endDate');
  const elAmt    = document.getElementById('amt_paid');
  const elDesc   = document.getElementById('r_description'); // NEW

  // Summary
  const S = {
    tenant:  document.getElementById('sum_tenant'),
    unit:    document.getElementById('sum_unit'),
    rate:    document.getElementById('sum_rate'),
    dates:   document.getElementById('sum_dates'),
    days:    document.getElementById('sum_days'),
    paid:    document.getElementById('sum_paid'),
    desc:    document.getElementById('sum_desc')
  };

  // Return the CURRENT symbol for the selected currency (no default fallback)
  function symNow(){
    return currencyMap[selUI.value] || '¤';
  }
  function syncCurrencyToPost(){ selPost.value = selUI.value; }
  function setSymbols(){
    const sym = symNow();
    document.getElementById('sym_total').innerText = sym;
    document.getElementById('sym_paid').innerText  = sym;
    document.getElementById('sym_bal').innerText   = sym;
    updateSummary();
  }

  // Lock behavior: OFF = read-only; ON = manual override
  function applyLockState() {
    const manual = toggle.checked;
    rateInp.disabled = !manual;
    selUI.disabled   = !manual;
    selUI.classList.toggle('locked', !manual);
  }
  toggle.addEventListener('change', applyLockState);

  // If user manually changes currency when override is ON
  selUI.addEventListener('change', function(){
    syncCurrencyToPost();
    setSymbols();
    recalcTotals();
  });

  // Fetch UNIT defaults (rate + currency) and apply immediately (NO toggle required)
  function fetchUnitDefaults(uid){
    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; }

          // res.d_rate, res.rate_currency_id, res.rate_currency (label)
          rateInp.value = res.d_rate || 0;

          // Choose the OPTION in the visible select that matches the UNIT's currency id
          const targetCid = String(res.rate_currency_id || '');
          let matchedValue = null;
          for (const opt of selUI.options) {
            const cid = String(opt.value).split('-')[0];
            if (cid === targetCid) { matchedValue = opt.value; break; }
          }
          if (matchedValue) {
            selUI.value = matchedValue;   // even while disabled, value can be set
            syncCurrencyToPost();         // keep hidden field in sync
            setSymbols();                 // update all currency symbols
          }

          // Recompute totals with the new daily rate
          recalcTotals();
        }
      });
    }
  }

  // React when UNIT changes: always pull defaults from that unit
  elUnit.addEventListener('change', function(){
    updateSummary();
    fetchUnitDefaults(this.value);
    // Optional: previously loaded helpers
    if (typeof getPreviousRentPeriod === 'function') getPreviousRentPeriod('uid', "previousRentReport");
    if (typeof getAvailableDatesForCurrentMonth === 'function') getAvailableDatesForCurrentMonth('uid', "availableDates");
  });

  // If a unit is preset (edit mode), fetch defaults right away after DOM is ready
  document.addEventListener('DOMContentLoaded', function(){
    const preset = document.getElementById('uid_edit').value;
    if (preset) {
      setTimeout(function(){
        const opts = Array.from(elUnit.options);
        const found = opts.find(o => o.value === preset);
        if (found) {
          elUnit.value = preset;
          elUnit.dispatchEvent(new Event('change'));
        }
      }, 300);
    }
  });

  // ------- Totals / Summary -------
  function recalcTotals() {
    const sVal = elStart.value;
    const eVal = elEnd.value;
    if (!sVal || !eVal) { updateSummary(); return; }

    const s = new Date(sVal + 'T00:00:00');
    const e = new Date(eVal + 'T00:00:00');
    if (e < s) {
      alert('End Date must be on or after Start Date');
      elEnd.value = '';
      document.getElementById('duration').value = '';
      document.getElementById('total_amount').value = '';
      document.getElementById('balance').value = '';
      updateSummary();
      return;
    }

    const msPerDay = 1000 * 60 * 60 * 24;
    const days = Math.ceil((e - s) / msPerDay); // exclusive end
    document.getElementById('duration').value = days;

    const rate = parseFloat(rateInp.value) || 0;
    document.getElementById('total_amount').value = (rate * days).toFixed(2);
    if (typeof calcBalance === 'function') calcBalance('amt_paid','total_amount','balance');
    updateSummary();
  }

  if (typeof calcBalance !== 'function') {
    window.calcBalance = function(paidId, totalId, balId){
      const paid  = parseFloat(document.getElementById(paidId).value) || 0;
      const total = parseFloat(document.getElementById(totalId).value) || 0;
      document.getElementById(balId).value = (total - paid).toFixed(2);
    }
  }

  function textOfSelect(sel){
    if (!sel) return '—';
    const opt = sel.options[sel.selectedIndex];
    return opt ? opt.textContent.trim() : '—';
  }
  function truncate(s, n){
    s = (s || '').toString();
    return s.length <= n ? s : s.slice(0, n-1) + '…';
  }
  function updateSummary(){
    const sym   = symNow();
    const rate  = parseFloat(rateInp.value) || 0;
    const total = document.getElementById('total_amount').value || '0.00';
    const paid  = parseFloat(elAmt.value) || 0;
    const bal   = document.getElementById('balance').value || '0.00';

    const s = elStart.value || '—';
    const e = elEnd.value   || '—';
    const d = document.getElementById('duration').value || '0';

    S.tenant.textContent  = 'Tenant: ' + textOfSelect(elTenant);
    S.unit.textContent    = 'Unit: '   + textOfSelect(elUnit);
    S.rate.textContent    = 'Rate: '   + sym + ' ' + (rate ? rate.toFixed(2) : '0.00') + ' / day';
    S.dates.textContent   = 'Dates: '  + s + ' → ' + e;
    S.days.textContent    = 'Duration: ' + d + ' day(s)';
    S.paid.textContent    = 'Paid: '   + sym + ' ' + paid.toFixed(2);
    S.desc.textContent    = 'Description: ' + (elDesc.value ? truncate(elDesc.value, 120) : '—');
  }

  document.getElementById('startDate').addEventListener('change', recalcTotals);
  document.getElementById('endDate').addEventListener('change', recalcTotals);
  document.getElementById('amt_paid').addEventListener('input', function(){
    if (typeof calcBalance === 'function') calcBalance('amt_paid','total_amount','balance');
    updateSummary();
  });
  rateInp.addEventListener('input', recalcTotals);

  document.getElementById('tid').addEventListener('change', updateSummary);
  document.getElementById('uid').addEventListener('change', updateSummary);
  document.getElementById('r_description').addEventListener('input', updateSummary); // NEW

  // Initialize: locked by default (no manual edits); will be updated when Unit is selected
  function initialSync(){
    applyLockState();      // keep fields locked initially
    syncCurrencyToPost();  // hidden field mirrors visible selector
    setSymbols();          // set placeholders (¤) until unit is chosen
    updateSummary();
  }
  initialSync();

  if (window.$ && $.fn.tooltip) $('[data-toggle="tooltip"]').tooltip();
</script>

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