<?php
error_reporting(-1);
ini_set('display_errors', 1);

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

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

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

/* ------------------ Defaults / State ------------------ */
$m_title        = '';
$m_date         = '';   // stored as typed (UI expects YYYY-MM-DD)
$m_amount       = '';
$m_details      = '';
$bid            = "";
$uid            = "";
$m_month        = "";
$m_year         = "";
$hdnid          = "0";

$title          = $_data['add_title_text'];
$button_text    = $_data['save_button_text'];
$successful_msg = $_data['add_msg'];
$form_url       = WEB_URL . "maintenance/add_maintenance_cost.php";

$data     = post_input_serilization();
$get_data = get_input_serilization();

/* Currency display (UTF-8 safe) */
$currency_display = html_entity_decode((string)CURRENCY, ENT_QUOTES | ENT_HTML5, 'UTF-8');

/* ------------------ Preload Blocks & Units (for UI) ------------------ */
$blocks = [];
$units_by_bid = [];

// Blocks
if ($qb = $link->query("SELECT bid, b_name FROM blocks ORDER BY b_name ASC")) {
  while ($rb = $qb->fetch_assoc()) $blocks[] = $rb;
  $qb->free();
}

// Units (use view for speed + clarity)
if ($qu = $link->query("SELECT uid, unit_no, bid FROM unit_view ORDER BY bid ASC, unit_no ASC")) {
  while ($ru = $qu->fetch_assoc()) {
    $b = (string)$ru['bid'];
    if (!isset($units_by_bid[$b])) $units_by_bid[$b] = [];
    $units_by_bid[$b][] = ['uid' => $ru['uid'], 'unit_no' => $ru['unit_no']];
  }
  $qu->free();
}

/* ------------------ Date -> xmonth/xyear (expects YYYY-MM-DD) ------------------ */
/**
 * Returns [month_string, year_string] or ["",""] if unknown.
 * Primary expectation: YYYY-MM-DD (text), with graceful fallback to strtotime().
 */
function derive_month_year_from_text($date_text) {
  $s = trim((string)$date_text);
  if ($s === '') return ["",""];

  if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $s, $m)) {
    return [ (string)((int)$m[2]), (string)((int)$m[1]) ];
  }

  $ts = strtotime($s);
  if ($ts) return [ (string)date('n', $ts), (string)date('Y', $ts) ];

  return ["",""];
}

/* ------------------ Save (Add / Update) ------------------ */
if (isset($data['txtMTitle'])) {
  // Extract & sanitize; m_date is VARCHAR and stored as typed (we expect YYYY-MM-DD)
  $m_title   = trim((string)$data['txtMTitle']);
  $m_date_in = trim((string)$data['txtMDate']);       // keep as typed (varchar)
  $m_amount  = trim((string)$data['txtMAmount']);     // keep as string; DB will cast if numeric
  $m_details = trim((string)$data['txtMDetails']);
  $bid       = isset($data['bid']) ? trim((string)$data['bid']) : '';
  $uid       = isset($data['uid']) ? trim((string)$data['uid']) : '';

  // Derive month/year from text
  list($xmonth_s, $xyear_s) = derive_month_year_from_text($m_date_in);

  // Type: general if no Block selected, else specific
  $maintenance_type = (empty($bid) ? "general" : "specific");

  if (isset($data['hdn']) && $data['hdn'] === '0') {
    /* ---------------- INSERT ---------------- */
    $sql = "
      INSERT INTO maintenance
        (m_title, m_date, bid, uid, xmonth, xyear, m_amount, maintenance_type, m_details)
      VALUES
        (?, ?, NULLIF(?, ''), NULLIF(?, ''), NULLIF(?, ''), NULLIF(?, ''), NULLIF(?, ''), ?, ?)
    ";
    $stmt = $link->prepare($sql);
    if (!$stmt) { die('Prepare failed: '.$link->error); }

    $stmt->bind_param(
      'sssssssss',
      $m_title,
      $m_date_in,     // VARCHAR as typed (YYYY-MM-DD in UI)
      $bid,           // NULL if ''
      $uid,           // NULL if ''
      $xmonth_s,      // NULL if ''
      $xyear_s,       // NULL if ''
      $m_amount,      // NULL if ''
      $maintenance_type,
      $m_details
    );

    $stmt->execute();
    if ($stmt->errno) { die('Execute failed: '.$stmt->error); }
    $stmt->close();
    mysqli_close($link);

    header("Location: " . WEB_URL . 'maintenance/maintenance_cost_list.php?m=add');
    exit;

  } else {
    /* ---------------- UPDATE ---------------- */
    $row_id = isset($get_data['id']) ? (int)$get_data['id'] : 0;

    $sql = "
      UPDATE maintenance 
      SET 
        m_title = ?,
        m_date  = ?,             -- stored as typed
        bid     = NULLIF(?, ''),
        uid     = NULLIF(?, ''),
        maintenance_type = ?,
        xmonth  = NULLIF(?, ''),
        xyear   = NULLIF(?, ''),
        m_amount= NULLIF(?, ''),
        m_details = ?
      WHERE mcid = ?
    ";
    $stmt = $link->prepare($sql);
    if (!$stmt) { die('Prepare failed: '.$link->error); }

    $stmt->bind_param(
      'sssssssssi',
      $m_title,
      $m_date_in,
      $bid,              // NULL if ''
      $uid,              // NULL if ''
      $maintenance_type,
      $xmonth_s,         // NULL if ''
      $xyear_s,          // NULL if ''
      $m_amount,         // NULL if ''
      $m_details,
      $row_id
    );

    $stmt->execute();
    if ($stmt->errno) { die('Execute failed: '.$stmt->error); }
    $stmt->close();

    header("Location: " . WEB_URL . 'maintenance/maintenance_cost_list.php?m=up');
    exit;
  }
}

/* ------------------ Editing existing record ------------------ */
if (isset($get_data['id']) && $get_data['id'] != '') {
  $row_id = (int)$get_data['id'];
  $stmt   = $link->prepare("SELECT * FROM maintenance WHERE mcid = ?");
  $stmt->bind_param("i", $row_id);
  $stmt->execute();
  $res = $stmt->get_result();
  if ($row = $res->fetch_assoc()) {
    $m_title        = $row['m_title'];
    $m_date         = $row['m_date'];     // keep as typed (VARCHAR; ideally YYYY-MM-DD)
    $m_amount       = $row['m_amount'];
    $m_details      = $row['m_details'];
    $bid            = (string)$row['bid'];
    $uid            = (string)$row['uid'];
    $m_month        = $row['xmonth'];
    $m_year         = $row['xyear'];
    $hdnid          = (string)$row_id;
    $title          = $_data['update_title_text'];
    $button_text    = $_data['update_button_text'];
    $successful_msg = $_data['update_msg'];
    $form_url       = WEB_URL . "maintenance/add_maintenance_cost.php?id=" . $row_id;
  }
  $stmt->close();
}
?>
<!-- Page Header -->
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;margin-bottom:8px;">
    <span style="display:inline-flex;width:40px;height:40px;border-radius:12px;background:#2563eb1a;align-items:center;justify-content:center;">
      <i class="fa fa-wrench" aria-hidden="true" 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['maintenance_cost']);?></li>
    <li class="active"><?= e($title); ?></li>
  </ol>
</section>

<!-- Styles -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
  :root{
    --ink:#0f172a; --ink2:#334155; --muted:#64748b; --line:#e5e7eb;
    --soft:#f8fafc; --soft2:#eef2ff; --brand:#2563eb; --brand2:#1e40af;
    --ok:#16a34a; --warn:#f59e0b; --danger:#ef4444; --card:#ffffff;
  }
  .content-wrapper, label, .btn, input, select, textarea {
    font-family:'Inter',system-ui,Segoe UI,Roboto,Helvetica,Arial;
    color:var(--ink2);
  }

  /* Shell */
  .card {
    background:#fff; border:1px solid var(--line); border-radius:18px;
    box-shadow:0 16px 40px rgba(2,6,23,.06); overflow:hidden; margin-bottom:18px;
  }
  .card-header {
    display:flex; align-items:center; justify-content:space-between; gap:12px;
    padding:16px 18px; background:linear-gradient(135deg,var(--soft),var(--soft2)); border-bottom:1px solid var(--line);
  }
  .card-title { margin:0; font-weight:800; color:var(--ink); letter-spacing:.2px; }
  .helper { color:var(--muted); font-size:12px; }

  /* Layout */
  .grid { display:grid; grid-template-columns: 1.2fr .8fr; gap:18px; }
  @media(max-width: 1100px){ .grid { grid-template-columns: 1fr; } }
  .pane { background:#fff; border:1px solid var(--line); border-radius:14px; }
  .pane-body { padding:16px 18px; }
  .sticky { position:sticky; top:12px; }

  /* Fields */
  .form-grid { display:grid; grid-template-columns:1fr 1fr; gap:14px 18px; }
  .form-grid .full { grid-column:1 / -1; }
  @media(max-width: 900px){ .form-grid { grid-template-columns:1fr; } }

  .label-strong { font-weight:800; color:#111827; margin-bottom:6px; display:block; }
  .input, .select, .textarea {
    width:100%; border:1px solid var(--line); border-radius:12px; padding:10px 12px; outline:none;
  }
  .input:focus, .select:focus, .textarea:focus { border-color:#93c5fd; box-shadow:0 0 0 3px rgba(59,130,246,.15); }

  .input-group { display:flex; align-items:stretch; border:1px solid var(--line); border-radius:12px; overflow:hidden; }
  .input-group .addon {
    background:#f8fafc; border-right:1px solid var(--line); padding:10px 12px; font-weight:800; color:#111827; min-width:56px; text-align:center;
  }
  .input-group input { border:none; outline:none; padding:10px 12px; flex:1; }

  /* Chips */
  .chip{
    display:inline-flex; align-items:center; gap:8px; padding:6px 10px; border-radius:999px;
    background:#f3f4f6; color:#111827; font-size:12px; font-weight:700; border:1px solid var(--line);
  }
  .chip i{ color:#6b7280; }
  .chip.ok{ background:#ecfdf5; border-color:#bbf7d0; }
  .chip.warn{ background:#fff7ed; border-color:#fed7aa; }

  /* Buttons */
  .actions { display:flex; gap:12px; justify-content:flex-end; padding-top:12px; }
  .btn { border-radius:12px; font-weight:800; letter-spacing:.2px; }
  .btn-success { background:#16a34a; border-color:#16a34a; color:#fff; }
  .btn-success:hover { background:#15803d; border-color:#15803d; }
  .btn-warning { background:#f59e0b; border-color:#f59e0b; color:#111827; }
  .btn-warning:hover { background:#d97706; border-color:#d97706; }
  .btn-default { background:#eef2ff; border-color:#e5e7eb; color:#111827; }
  .btn-default:hover { background:#e0e7ff; }

  .hint { font-size:12px; color:var(--muted); margin-top:6px; }
  .errorStar { color:var(--danger); }
  hr.soft { border:0; border-top:1px dashed var(--line); margin:14px 0; }

  /* Flatpickr (same styling tweaks as addrent.php) */
  .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="card">
    <div class="card-header">
      <h3 class="card-title"><i class="fa fa-edit"></i> <?= e($_data['m_cost_entry_form']); ?></h3>
      <div class="helper"><?= e($_data['maintenance_cost']); ?> • <?= e($successful_msg); ?></div>
    </div>

    <div class="pane-body">
      <div class="grid">
        <!-- LEFT: Form -->
        <div class="pane">
          <div class="pane-body">
            <form onsubmit="return validateMe();" action="<?= $form_url ?>" method="post" enctype="multipart/form-data" novalidate>
              <div class="form-grid">
                <!-- Date -->
                <div class="full">
                  <label for="txtMDate" class="label-strong">
                    <span class="errorStar">*</span> <?= e($_data['date']); ?>:
                  </label>
                  <div class="input-group">
                    <div class="addon"><i class="fa fa-calendar-o"></i></div>
                    <input
                      type="text"
                      name="txtMDate"
                      value="<?= e($m_date) ?>"
                      required
                      id="txtMDate"
                      class="input date-input"
                      placeholder="YYYY-MM-DD"
                      inputmode="none"
                      pattern="^\d{4}-\d{2}-\d{2}$"
                      title="Use format YYYY-MM-DD (e.g., 2025-08-13)"
                      oninput="updateDerived();"
                    />
                  </div>
                  <div class="hint">Saved exactly as typed. Expected format: <b>YYYY-MM-DD</b>.</div>
                </div>

                <!-- Block -->
                <div>
                  <label for="bid" class="label-strong"><?= e($_data['select_block'] ?? 'Select Block'); ?>:</label>
                  <select onchange="populateUnitsForBlock(this.value); updateTypeChip();" name="bid" id="bid" class="select">
                    <option value=""><?= e($_data['select_block_placeholder'] ?? '-- Select Block --'); ?></option>
                    <?php foreach ($blocks as $b): ?>
                      <option value="<?= e($b['bid']) ?>" <?= ($bid !== "" && (string)$bid === (string)$b['bid'] ? 'selected' : '') ?>>
                        <?= e($b['b_name']) ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                  <div class="hint"><?= e($_data['block_hint'] ?? 'Choose a block to optionally narrow to a unit.'); ?></div>
                </div>

                <!-- Unit -->
                <div>
                  <label for="ddlUnitNo" class="label-strong"><?= e($_data['select_unit'] ?? 'Select Unit'); ?>:</label>
                  <select name="uid" id="ddlUnitNo" class="select" onchange="updateTypeChip();">
                    <option value=""><?= e($_data['select_unit_placeholder'] ?? '-- Select Unit --'); ?></option>
                  </select>
                  <div class="hint"><?= e($_data['unit_hint'] ?? 'Optional: pick a specific unit.'); ?></div>
                </div>

                <!-- Amount -->
                <div class="full">
                  <label for="txtMAmount" class="label-strong">
                    <span class="errorStar">*</span> <?= e($_data['text_2']); ?>:
                  </label>
                  <div class="input-group">
                    <div class="addon"><?= e($currency_display) ?></div>
                    <input type="number" step="0.01" min="0" required name="txtMAmount" placeholder="0.00" value="<?= e($m_amount) ?>" id="txtMAmount" class="input" oninput="updateSummary();" />
                  </div>
                  <div class="hint"><?= e($_data['amount_hint'] ?? 'Enter the total maintenance amount.'); ?></div>
                </div>

                <!-- Title -->
                <div class="full">
                  <label for="txtMTitle" class="label-strong">
                    <span class="errorStar">*</span> <?= e($_data['text_1']); ?>:
                  </label>
                  <input type="text" required name="txtMTitle" value="<?= e($m_title);?>" id="txtMTitle" class="input" placeholder="<?= e($_data['text_1_placeholder'] ?? 'e.g., Plumbing repair for Block A'); ?>" oninput="updateSummary();" />
                </div>

                <!-- Details -->
                <div class="full">
                  <label for="txtMDetails" class="label-strong">
                    <span class="errorStar">*</span> <?= e($_data['text_3']); ?>:
                  </label>
                  <textarea required name="txtMDetails" rows="6" id="txtMDetails" class="textarea" placeholder="<?= e($_data['text_3_placeholder'] ?? 'Describe the maintenance work performed, materials used, vendor, etc.'); ?>" oninput="updateSummary();"><?= e($m_details) ?></textarea>
                </div>
              </div>

              <hr class="soft">

              <div class="actions">
                <button type="submit" name="button" class="btn btn-success">
                  <i class="fa fa-floppy-o"></i> <?= e($button_text) ?>
                </button>
                <a class="btn btn-warning" href="<?= WEB_URL; ?>maintenance/maintenance_cost_list.php">
                  <i class="fa fa-reply"></i> <?= e($_data['back_text']); ?>
                </a>
                <button type="button" class="btn btn-default" onclick="resetFormNice();">
                  <i class="fa fa-eraser"></i> <?= e($_data['reset'] ?? 'Reset'); ?>
                </button>
              </div>

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

        <!-- RIGHT: Live Summary -->
        <aside class="pane sticky" aria-live="polite">
          <div class="pane-body">
            <h4 style="margin:0 0 10px; font-weight:800; color:var(--ink); display:flex; align-items:center; gap:8px;">
              <i class="fa fa-info-circle" style="color:var(--brand2);"></i> <?= e($_data['summary'] ?? 'Summary'); ?>
            </h4>

            <div style="display:grid; gap:10px;">
              <div class="chip"><i class="fa fa-tag"></i> <span id="sum_title"><?= e($m_title) ? e($m_title) : '— Title —'; ?></span></div>
              <div class="chip"><i class="fa fa-calendar"></i> <span id="sum_date"><?= e($m_date) ? e($m_date) : '— YYYY-MM-DD —'; ?></span></div>
              <div class="chip"><i class="fa fa-layer-group"></i> <span id="sum_block"><?= $bid !== "" ? 'Block: ' . e($bid) : '— No Block (General) —'; ?></span></div>
              <div class="chip"><i class="fa fa-home"></i> <span id="sum_unit"><?= $uid !== "" ? 'Unit: ' . e($uid) : '— No Unit —'; ?></span></div>
              <div class="chip"><i class="fa fa-money"></i> <span id="sum_amount"><?= e($currency_display); ?> <?= $m_amount !== '' ? e(number_format((float)$m_amount, 2)) : '0.00'; ?></span></div>
              <div class="chip ok" id="chip_type"><i class="fa fa-check-circle"></i> <span>Type: <?= $bid === "" ? 'General' : 'Specific'; ?></span></div>
              <div class="chip warn" id="chip_period"><i class="fa fa-clock-o"></i> <span>Period: <?= ($m_month && $m_year) ? e($m_month).'/'.e($m_year) : '— auto from date —'; ?></span></div>
            </div>

            <div class="hint" style="margin-top:10px;">
              <?= e($_data['summary_hint'] ?? 'This panel updates as you fill the form. The period (month/year) is derived from the date.'); ?>
            </div>
          </div>
        </aside>
      </div>
    </div>
  </div>
</section>

<!-- ===== Same Flatpickr loader/initializer pattern as in addrent.php ===== -->
<script>
(function ensureFlatpickrAndInit(){
  function initPickers(){
    if (!window.flatpickr) return;

    var opts = {
      dateFormat: 'Y-m-d',
      allowInput: true,
      clickOpens: true
    };

    // Maintenance Date (default to existing value, else today)
    var el = document.getElementById('txtMDate');
    flatpickr('#txtMDate', Object.assign({}, opts, {
      defaultDate: el && el.value ? el.value : new Date()
    }));
  }

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

  // Load CSS
  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);

  // Load JS then init
  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 type="text/javascript">
/* -------- Preloaded Units Map (from PHP) -------- */
var UNITS_BY_BID = <?php echo json_encode($units_by_bid, JSON_UNESCAPED_UNICODE); ?>;

/* Populate units for a given block id */
function populateUnitsForBlock(bid) {
  var select = document.getElementById('ddlUnitNo');
  while (select.firstChild) select.removeChild(select.firstChild);

  var ph = document.createElement('option');
  ph.value = '';
  ph.textContent = '<?= addslashes($_data['select_unit_placeholder'] ?? '-- Select Unit --'); ?>';
  select.appendChild(ph);

  if (!bid || !UNITS_BY_BID[bid]) { updateSummary(); return; }

  var units = UNITS_BY_BID[bid];
  for (var i = 0; i < units.length; i++) {
    var opt = document.createElement('option');
    opt.value = units[i]['uid'];
    opt.textContent = units[i]['unit_no'];
    select.appendChild(opt);
  }
  updateSummary();
}

/* Preselect units when editing */
(function preselect() {
  var currentBid = "<?= addslashes((string)$bid) ?>";
  var currentUid = "<?= addslashes((string)$uid) ?>";
  if (currentBid) {
    populateUnitsForBlock(currentBid);
    if (currentUid) {
      var sel = document.getElementById('ddlUnitNo');
      for (var i=0;i<sel.options.length;i++) {
        if (String(sel.options[i].value) === String(currentUid)) {
          sel.selectedIndex = i;
          break;
        }
      }
    }
  }
})();

/* Validation */
function validateMe() {
  var dateEl = document.getElementById('txtMDate');
  var dateVal = (dateEl.value || '').trim();
  var iso = /^\d{4}-\d{2}-\d{2}$/;
  if(!iso.test(dateVal)){
    alert("Please enter a valid date in YYYY-MM-DD format (e.g., 2025-08-13).");
    dateEl.focus();
    return false;
  }
  if($("#txtMTitle").val().trim() === ''){
    alert("<?= addslashes($_data['v4']); ?>");
    $("#txtMTitle").focus();
    return false;
  }
  if($("#txtMAmount").val().trim() === ''){
    alert("<?= addslashes($_data['v5']); ?>");
    $("#txtMAmount").focus();
    return false;
  }
  if($("#txtMDetails").val().trim() === ''){
    alert("<?= addslashes($_data['v6']); ?>");
    $("#txtMDetails").focus();
    return false;
  }
  return true;
}

/* Live Summary & Chips */
function textOfSelect(sel){
  if (!sel) return '—';
  var opt = sel.options[sel.selectedIndex];
  return opt ? opt.textContent.trim() : '—';
}
function updateTypeChip(){
  var bid = document.getElementById('bid').value;
  var chip = document.getElementById('chip_type');
  var s = chip.querySelector('span');
  if (bid === '') {
    chip.classList.add('ok'); chip.classList.remove('warn');
    s.textContent = 'Type: General';
  } else {
    chip.classList.add('ok'); chip.classList.remove('warn');
    s.textContent = 'Type: Specific';
  }
  updateSummary();
}
function updateDerived(){
  var dateVal = (document.getElementById('txtMDate').value || '').trim();
  var chip = document.getElementById('chip_period');
  var s = chip.querySelector('span');

  // Fast client-side derivation
  var m = dateVal.match(/^(\d{4})-(\d{2})-(\d{2})$/);
  if (m) {
    var month = parseInt(m[2],10);
    var year  = parseInt(m[1],10);
    s.textContent = 'Period: ' + month + '/' + year;
  } else {
    s.textContent = 'Period: — auto from date —';
  }
  updateSummary();
}
function updateSummary(){
  var title = (document.getElementById('txtMTitle').value || '').trim() || '— Title —';
  var date  = (document.getElementById('txtMDate').value  || '').trim() || '— YYYY-MM-DD —';
  var bidSel= document.getElementById('bid');
  var uidSel= document.getElementById('ddlUnitNo');
  var amt   = parseFloat(document.getElementById('txtMAmount').value || '0') || 0;

  document.getElementById('sum_title').textContent = title;
  document.getElementById('sum_date').textContent  = date;

  var blkTxt = bidSel && bidSel.value ? textOfSelect(bidSel) : '— No Block (General) —';
  document.getElementById('sum_block').textContent = 'Block: ' + blkTxt;

  var unitTxt = uidSel && uidSel.value ? textOfSelect(uidSel) : '— No Unit —';
  document.getElementById('sum_unit').textContent = 'Unit: ' + unitTxt;

  document.getElementById('sum_amount').textContent = '<?= addslashes($currency_display); ?> ' + amt.toFixed(2);
}

function resetFormNice(){
  if(!confirm('Clear all fields?')) return;
  document.getElementById('txtMTitle').value = '';
  document.getElementById('txtMDate').value = '';
  document.getElementById('bid').value = '';
  populateUnitsForBlock('');
  document.getElementById('txtMAmount').value = '';
  document.getElementById('txtMDetails').value = '';
  updateDerived();
}

/* Initialize summary/chips on load */
document.addEventListener('DOMContentLoaded', function(){
  updateTypeChip();
  updateDerived();
  updateSummary();
});
</script>

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