<?php
include_once('../header.php');
if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  die();
}

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

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

/* ---------------- Routes ----------------- */
$add_payment_url = WEB_URL . "security_deposit/add_payment.php";
$add_refund_url  = WEB_URL . "security_deposit/add_refund.php";

/* ---------------- Alerts & actions ---------------- */
$delinfo = 'none';
$addinfo = 'none';
$msg     = null;

$data = get_input_serilization();

/* Delete full record (and its payments) */
if (isset($data['action']) && $data["action"] === "delete" && isset($data['id']) && $data['id'] != '' && (int)$data['id'] > 0) {
  $id = (int)$data['id'];
  $link->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
  $link->query("DELETE FROM security_deposit_payment_updates WHERE security_deposit_id = {$id}");
  $link->query("DELETE FROM `security_deposit` WHERE id = {$id}");
  if ($link->commit()) {
    $delinfo = 'block';
    header("Location: " . WEB_URL . 'security_deposit/security_deposit_list.php');
    exit;
  }
}

/* Flash messages from add/update */
if (isset($data['m']) && $data['m'] == 'add') { $addinfo = 'block'; $msg = $_data['added_security_deposit_successfully']; }
if (isset($data['m']) && $data['m'] == 'up')  { $addinfo = 'block'; $msg = $_data['update_security_deposit_successfully']; }

/* Session message passthrough (redirect to clean URL) */
if (isset($_SESSION["message"])) {
  if (!empty($_SESSION["message_type"]) && $_SESSION["message_type"] === "error") {
    $delinfo = 'block';
    $addinfo = 'none';
    unset($_SESSION["message_type"]);
  } else {
    $addinfo = 'block';
    $delinfo = 'none';
  }
  $msg = $_SESSION["message"];
  unset($_SESSION["message"]);
  header("Location: " . WEB_URL . 'security_deposit/security_deposit_list.php');
  exit;
}
?>
<!-- Content Header -->
<section class="content-header" style="margin-bottom:8px;">
  <h1 style="display:flex;align-items:center;gap:10px;margin-bottom:8px;">
    <i class="fa fa-shield" aria-hidden="true"></i>
    <span><?= e($_data['security_deposit_list']); ?></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_security_deposit_information_breadcam']); ?></li>
    <li class="active"><?= e($_data['security_deposit_list']); ?></li>
  </ol>
</section>

<!-- Fonts & Base Styles -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
  :root{
    color-scheme: light dark;
    --ink:#0f172a; --ink2:#334155; --muted:#64748b; --line:#e5e7eb;
    --soft:#f8fafc; --soft2:#eef2ff; --brand:#2563eb; --ok:#16a34a; --warn:#d97706; --danger:#dc2626;
    --card:#ffffff; --yellow:#fff8d8; --shadow:0 12px 32px rgba(2,6,23,.08);
    --rowHover:#f9fafb; --chipBorder:#e5e7eb;
  }
  @media (prefers-color-scheme: dark){
    :root{
      --ink:#e5e7eb; --ink2:#cbd5e1; --muted:#94a3b8; --line:#243141;
      --soft:#0b1220; --soft2:#0f172a; --brand:#3b82f6; --ok:#22c55e; --warn:#f59e0b; --danger:#ef4444;
      --card:#0b1220; --yellow:#2b2307; --shadow:0 8px 24px rgba(0,0,0,.3);
      --rowHover:#0f172a; --chipBorder:#1f2937;
    }
  }

  .content-wrapper, .box, .table, label, .btn, .alert, input, select, body {
    font-family:'Inter',system-ui,Segoe UI,Roboto,Helvetica,Arial;
    color:var(--ink2);
  }
  .content-header > h1{ font-weight:800; color:var(--ink); letter-spacing:.2px; }

  /* Shell */
  .page-card{
    border-radius:18px; overflow:hidden; border:1px solid var(--line);
    box-shadow:var(--shadow); background:var(--card);
  }
  .page-head{
    background:linear-gradient(135deg,var(--soft),var(--soft2));
    border-bottom:1px solid var(--line);
    display:flex; align-items:center; justify-content:space-between; gap:12px;
    padding:12px 14px;
  }
  .page-title{ font-weight:800; color:var(--ink); margin:0; font-size:16px; display:flex; align-items:center; gap:8px; }
  .toolbar{ display:flex; align-items:center; gap:8px; flex-wrap:wrap; }

  /* Buttons */
  .btn{ border-radius:10px; border:1px solid var(--line); font-weight:700; }
  .btn i{ margin-right:6px; }
  .btn:hover{ filter:brightness(.98); }
  .btn-success{ background:var(--ok); border-color:var(--ok); color:#fff; }
  .btn-primary{ background:var(--brand); border-color:var(--brand); color:#fff; }
  .btn-ghost{ background:transparent; color:var(--ink2); }
  .btn-ghost:hover{ background:rgba(148,163,184,.08); }
  .btn-row{ padding:5px 9px; font-size:12px; line-height:1.2; border-radius:10px; border:1px solid var(--line); }
  .btn-row i{ margin-right:0; font-size:12px; }
  .btn-warning-solid{ background:var(--warn); border-color:var(--warn); color:#fff; }
  .btn-warning-solid:hover{ filter:brightness(0.95); }
  .btn-danger-solid{ background:var(--danger); border-color:var(--danger); color:#fff; }
  .btn-danger-solid:hover{ filter:brightness(0.95); }
  .btn-info-solid{ background:#0ea5e9; border-color:#0ea5e9; color:#fff; }

  /* Inputs */
  .input, .select{
    border:1px solid var(--line); background:transparent; color:var(--ink2);
    border-radius:10px; padding:6px 10px; outline:none; font-weight:600; font-size:12px; height:34px;
  }
  .input:focus, .select:focus{ border-color:#93c5fd; box-shadow:0 0 0 3px rgba(59,130,246,.12); }

  /* Table */
  .table-wrap{ width:100%; overflow:auto; }
  .table-polished{ width:100%; border-collapse:separate; border-spacing:0 8px; }
  .table > thead > tr > th{
    position:sticky; top:0; z-index:1;
    background:var(--card) !important;
    border-bottom:1px solid var(--line) !important;
    color:var(--ink); font-weight:800; text-transform:uppercase; font-size:11px; letter-spacing:.3px;
  }
  .table > tbody > tr { background:transparent; }
  .table > tbody > tr > td{
    vertical-align:middle; padding:10px; font-size:13px;
    background:var(--card); border-top:1px solid var(--line); border-bottom:1px solid var(--line);
  }
  .table > tbody > tr > td:first-child{ border-left:1px solid var(--line); border-radius:12px 0 0 12px; }
  .table > tbody > tr > td:last-child{ border-right:1px solid var(--line); border-radius:0 12px 12px 0; }
  .table > tbody > tr:hover > td { background:var(--rowHover); transition:background .15s ease; }

  /* Chips */
  .chip{
    display:inline-flex; align-items:center; gap:6px; padding:4px 8px; border-radius:999px;
    font-size:11px; font-weight:700; border:1px solid var(--chipBorder);
  }
  .chip.blue{ background:rgba(191,219,254,.25); color:#1e40af; }
  .chip.gray{ background:rgba(229,231,235,.25); color:#374151; }
  .chip.green{ background:rgba(187,247,208,.25); color:#065f46; }
  .chip.yellow{ background:rgba(254,249,195,.25); color:#92400e; }
  .chip.red{ background:rgba(254,202,202,.25); color:#991b1b; }
  .chip.indigo{ background:rgba(199,210,254,.25); color:#3730a3; }

  /* Row accents */
  .accent-green td{ background-color:rgba(187,247,208,.35) !important; }
  .accent-yellow td{ background-color:rgba(254,249,195,.38) !important; }
  .accent-red td{ background-color:rgba(254,202,202,.38) !important; }

  /* Alerts */
  .alert{ border-radius:12px; border:none; box-shadow:var(--shadow); }
  .alert-success{ background:rgba(187,247,208,.35); color:#064e3b; }
  .alert-danger{ background:rgba(254,202,202,.38); color:#7f1d1d; }

  /* Empty state helper (used by DataTables language.emptyTable) */
  .empty{
    display:flex; flex-direction:column; align-items:center; justify-content:center;
    padding:28px; border:1px dashed var(--line); border-radius:14px; color:var(--muted);
  }

  /* Modal polish */
  .pill{ display:inline-flex; align-items:center; gap:6px; padding:4px 10px; border-radius:999px; font-weight:700; border:1px solid var(--line); }
  .pill-strong{ background:rgba(30,64,175,.12); color:#1e40af; }
  .pill-green { background:rgba(16,185,129,.12); color:#065f46; }
  .pill-blue  { background:rgba(59,130,246,.12); color:#1e3a8a; }
  .sd-modal .modal-content{ border-radius:16px; overflow:hidden; box-shadow:0 24px 60px rgba(2,6,23,.20); }
  .sd-modal .modal-header{ border:0; background:linear-gradient(135deg,var(--soft),var(--soft2)); padding:14px 16px; }
  .sd-modal .modal-title{ font-weight:800; letter-spacing:.2px; color:var(--ink); }
  .sd-modal .close{ opacity:.7; font-size:24px; line-height:1; }

  /* Refund grid */
  .refund-grid{ display:grid; grid-template-columns:repeat(4,1fr); gap:10px; }
  .refund-card{ border:1px solid var(--line); border-radius:12px; padding:10px; background:var(--card); }
  .refund-card-span{ grid-column:span 2; }
  .refund-card .label{ font-size:11px; color:var(--muted); font-weight:700; }
  .refund-card .value{ font-size:13px; font-weight:800; color:var(--ink); margin-top:4px; }

  .fade-in{ animation:fadein .25s ease; }
  @keyframes fadein { from{opacity:0; transform:translateY(2px)} to{opacity:1; transform:none} }

  .kbd{ font-family:ui-monospace,Menlo,Consolas,monospace; padding:2px 6px; border:1px solid var(--line); border-radius:6px; background:transparent; font-size:11px; }
</style>

<section class="content">
  <div class="row">
    <div class="col-xs-12">

      <!-- Alerts -->
      <div id="me" class="alert alert-danger alert-dismissable fade-in" style="display:<?= $delinfo; ?>">
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button" aria-label="Close"><i class="fa fa-close"></i></button>
        <h4 style="margin-top:0;"><i class="icon fa fa-ban"></i> <?= $msg !== null ? 'Warning' : e($_data['delete_text']); ?>!</h4>
        <?= e($msg ?? $_data['delete_security_deposit_information']); ?>
      </div>
      <div id="you" class="alert alert-success alert-dismissable fade-in" style="display:<?= $addinfo; ?>">
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button" aria-label="Close"><i class="fa fa-close"></i></button>
        <h4 style="margin-top:0;"><i class="icon fa fa-check"></i> <?= e($_data['success']); ?>!</h4>
        <?= e($msg ?? ""); ?>
      </div>

      <div class="page-card">
        <div class="page-head">
          <h3 class="page-title"><i class="fa fa-shield"></i> <?= e($_data['security_deposit_list']); ?></h3>

          <div class="toolbar" role="group" aria-label="Security deposit toolbar">
            <a class="btn btn-success" href="<?= WEB_URL; ?>security_deposit/addsecuritydeposit.php" title="<?= e($_data['add_new_security_deposit_breadcam']); ?>">
              <i class="fa fa-plus"></i><?= e($_data['add_new_security_deposit_breadcam']); ?>
            </a>
            <a class="btn btn-primary" href="<?= WEB_URL; ?>dashboard.php" title="<?= e($_data['home_breadcam']); ?>">
              <i class="fa fa-dashboard"></i><?= e($_data['home_breadcam']); ?>
            </a>
            <div style="display:flex;gap:6px;align-items:center;">
              <input id="sdSearch" class="input" placeholder="Search tenant, block, unit…" aria-label="Search security deposits" />
              <span class="kbd">Ctrl /</span>
            </div>
          </div>
        </div>

        <div class="box-body" style="padding:12px;">
          <div class="table-wrap">
            <!-- IMPORTANT: No placeholder rows with colspan inside <tbody> -->
            <table id="sdTable" class="table table-polished table-bordered dt-responsive">
              <thead>
                <tr>
                  <th style="width:56px;">#</th>
                  <th>Tenant</th>
                  <th>Block</th>
                  <th>Unit</th>
                  <th>Paid</th>
                  <th>Balance</th>
                  <th>Deposit</th>
                  <th>Amount Refunded</th>
                  <th>Refund Status</th>
                  <th>Payment Status</th>
                  <th style="min-width:160px;"><?= e($_data['action_text']); ?></th>
                </tr>
              </thead>
              <tbody>
                <?php
                $rowScripts = []; // buffer for per-row JS (printed after the table)
                $result = mysqli_query($link, "SELECT * FROM security_deposit_tenant_unit_view ORDER BY id DESC");
                if ($result){
                  while ($row = mysqli_fetch_array($result)):
                    $id              = (int)$row['id'];
                    $tenant          = $row['r_name'];
                    $block           = $row['b_name'];
                    $unit            = $row['unit_no'];
                    $symbol          = $row['rate_currency'];
                    $rate            = (float)$row['rate'];
                    $amt_paid        = (float)$row['amt_paid'];
                    $amount_refunded = isset($row['amount_refunded']) ? (float)$row['amount_refunded'] : 0.00;
                    $balance         = $rate - $amt_paid;

                    $status          = isset($row['s_status']) ? (string)$row['s_status'] : '0';
                    $isCompleted     = $status === '2';
                    $isPartRefunded  = $status === '3';
                    $isWithhold      = $status === '1';

                    $accentClass = $isCompleted ? 'accent-green' : ($isPartRefunded ? 'accent-yellow' : ($isWithhold ? 'accent-red' : ''));

                    $image = WEB_URL . 'img/no_image.jpg';
                    if (!empty($row['image']) && file_exists(ROOT_PATH . '/img/upload/' . $row['image'])) {
                      $image = WEB_URL . 'img/upload/' . $row['image'];
                    }

                    $max_refundable = max(0, $amt_paid - $amount_refunded);
                ?>
                <tr class="<?= $accentClass; ?>">
                  <td><?= $id; ?></td>
                  <td><?= e($tenant); ?></td>
                  <td><?= e($block); ?></td>
                  <td><?= e($unit); ?></td>

                  <td><span class="chip blue"><i class="fa fa-credit-card"></i> <?= e($symbol) . " " . number_format($amt_paid, 2); ?></span></td>
                  <td>
                    <?php if ($balance > 0): ?>
                      <span class="chip red"><i class="fa fa-exclamation-circle"></i> <?= e($symbol) . " " . number_format($balance, 2); ?></span>
                    <?php elseif ((string)$balance === '0' || abs($balance) < 0.005): ?>
                      <span class="chip green"><i class="fa fa-check-circle"></i> <?= e($symbol) . " 0.00"; ?></span>
                    <?php else: ?>
                      <span class="chip red"><i class="fa fa-warning"></i> <?= e($symbol) . " " . number_format($balance, 2); ?></span>
                    <?php endif; ?>
                  </td>

                  <td><?= e($symbol) . " " . number_format($rate, 2); ?></td>
                  <td><?= e($symbol) . " " . number_format($amount_refunded, 2); ?></td>

                  <!-- Refund Status -->
                  <td>
                    <?php if ($isCompleted): ?>
                      <span class="chip green"><i class="fa fa-lock"></i> <?= e($_data['t_status_completed']); ?></span>
                    <?php elseif ($isPartRefunded): ?>
                      <span class="chip yellow"><i class="fa fa-undo"></i> Partially Refunded</span>
                    <?php else: ?>
                      <select
                        name="ddlStatus"
                        class="select"
                        data-prev="<?= e($status); ?>"
                        data-id="<?= $id; ?>"
                        data-amtpaid="<?= e($amt_paid); ?>"
                        data-refunded="<?= e($amount_refunded); ?>"
                        data-symbol="<?= e($symbol); ?>"
                        onchange="_set_security_status(this);">
                        <option value="0" <?= $status == '0' ? 'selected' : ''; ?>><?= e($_data['t_status_pending']); ?></option>
                        <?php if ($amt_paid > 0): ?>
                          <option value="1" <?= $status == '1' ? 'selected' : ''; ?>>Withhold</option>
                          <option value="2" <?= $status == '2' ? 'selected' : ''; ?>><?= e($_data['t_status_completed']); ?></option>
                          <option value="3" <?= $status == '3' ? 'selected' : ''; ?>>Partially Refunded</option>
                        <?php endif; ?>
                      </select>
                    <?php endif; ?>
                  </td>

                  <!-- Payment Status -->
                  <td>
                    <?php if ($amt_paid <= 0): ?>
                      <span class="chip red"><i class="fa fa-times-circle"></i> Unpaid</span>
                    <?php elseif ($amt_paid < $rate): ?>
                      <span class="chip yellow"><i class="fa fa-hourglass-half"></i> Partial</span>
                    <?php else: ?>
                      <span class="chip green"><i class="fa fa-check-circle"></i> Full</span>
                    <?php endif; ?>
                  </td>

                  <!-- Actions + Modals -->
                  <td>
                    <a target="_blank" class="btn btn-info-solid btn-row" data-toggle="tooltip" title="<?= e($_data['invoice_no']); ?>"
                       href="<?= WEB_URL; ?>security_deposit/invoice.php?security_deposit_id=<?= $id; ?>">
                      <i class="fa fa-file-text-o"></i>
                    </a>

                    <a class="btn btn-success btn-row" data-toggle="tooltip" title="<?= e($_data['view_text']); ?>"
                       href="javascript:;" onclick="$('#info_view_<?= $id; ?>').modal('show');">
                      <i class="fa fa-eye"></i>
                    </a>

                    <?php if ($amt_paid < $rate): ?>
                      <a class="btn btn-primary btn-row" data-toggle="tooltip" title="Add Payment"
                         href="javascript:;" onclick="$('#payment_view_<?= $id; ?>').modal('show');">
                        <i class="fa fa-money"></i>
                      </a>
                    <?php endif; ?>

                    <a class="btn btn-danger-solid btn-row" data-toggle="tooltip" title="<?= e($_data['delete_text']); ?>"
                       href="javascript:;" onclick="deleteSecurityDeposit(<?= $id; ?>);">
                      <i class="fa fa-trash-o"></i>
                    </a>

                    <!-- Info Modal -->
                    <div id="info_view_<?= $id; ?>" class="modal fade sd-modal" tabindex="-1" role="dialog" aria-labelledby="infoLabel_<?= $id; ?>" aria-hidden="true">
                      <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                          <div class="modal-header">
                            <div 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>
                              <div>
                                <h3 id="infoLabel_<?= $id; ?>" class="modal-title"><?= e($_data['fare_detailss']); ?></h3>
                                <div style="font-size:12px; color:var(--muted); margin-top:2px;">
                                  <?= e($_data['invoice_no']); ?>: <span style="font-weight:700; color:var(--ink);"><?= $id; ?></span>
                                </div>
                              </div>
                            </div>
                            <button aria-label="Close" data-dismiss="modal" class="close" type="button">
                              <span aria-hidden="true"><i class="fa fa-close"></i></span>
                            </button>
                          </div>

                          <div class="modal-body" style="padding:16px 16px 8px;">
                            <div style="display:flex; align-items:center; gap:14px; flex-wrap:wrap; justify-content:flex-start;">
                              <img src="<?= e($image); ?>" alt="<?= e($tenant); ?> photo" style="width:64px; height:64px; border-radius:50%; object-fit:cover; border:1px solid var(--line);">
                              <div>
                                <div style="font-weight:800; color:var(--ink); font-size:16px;"><?= e($tenant); ?></div>
                                <div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin-top:6px;">
                                  <span class="pill" style="background:rgba(239,246,255,.35); color:#1e40af;"><i class="fa fa-home"></i> <?= e($_data['add_new_form_field_text_1']); ?>: <?= e($block); ?></span>
                                  <span class="pill pill-green"><i class="fa fa-building-o"></i> <?= e($_data['add_new_form_field_text_3']); ?>: <?= e($unit); ?></span>
                                </div>
                              </div>
                            </div>
                          </div>

                          <div class="modal-body" style="padding:8px 16px 16px;">
                            <h4 style="margin:0 0 10px; font-weight:800; color:var(--ink); border-bottom:1px dashed var(--line); padding-bottom:6px;">
                              <i class="fa fa-info-circle"></i> <?= e($_data['details_information']); ?>
                            </h4>

                            <div class="row">
                              <div class="col-sm-6" style="margin-bottom:10px;">
                                <div style="display:flex; align-items:flex-start; gap:10px; margin-bottom:8px;">
                                  <i class="fa fa-user" style="color:var(--muted); width:16px; margin-top:3px;"></i>
                                  <div>
                                    <div style="font-size:12px; color:var(--muted); font-weight:700;"><?= e($_data['add_new_form_field_text_6']); ?></div>
                                    <div style="font-weight:700; color:var(--ink);"><?= e($tenant); ?></div>
                                  </div>
                                </div>

                                <div style="display:flex; align-items:flex-start; gap:10px; margin-bottom:8px;">
                                  <i class="fa fa-map-marker" style="color:var(--muted); width:16px; margin-top:3px;"></i>
                                  <div>
                                    <div style="font-size:12px; color:var(--muted); font-weight:700;"><?= e($_data['add_new_form_field_text_1']); ?></div>
                                    <div style="font-weight:700; color:var(--ink);"><?= e($block); ?></div>
                                  </div>
                                </div>

                                <div style="display:flex; align-items:flex-start; gap:10px; margin-bottom:8px;">
                                  <i class="fa fa-hashtag" style="color:var(--muted); width:16px; margin-top:3px;"></i>
                                  <div>
                                    <div style="font-size:12px; color:var(--muted); font-weight:700;"><?= e($_data['add_new_form_field_text_3']); ?></div>
                                    <div style="font-weight:700; color:var(--ink);"><?= e($unit); ?></div>
                                  </div>
                                </div>

                                <div style="display:flex; align-items:flex-start; gap:10px;">
                                  <i class="fa fa-money" style="color:var(--muted); width:16px; margin-top:3px;"></i>
                                  <div>
                                    <div style="font-size:12px; color:var(--muted); font-weight:700;"><?= e($_data['add_new_form_field_text_44']); ?></div>
                                    <div style="font-weight:800; color:var(--ink);"><?= e($symbol) . " " . number_format($rate, 2); ?></div>
                                  </div>
                                </div>
                              </div>

                              <div class="col-sm-6" style="margin-bottom:10px;">
                                <div style="display:flex; align-items:flex-start; gap:10px; margin-bottom:8px;">
                                  <i class="fa fa-calendar" style="color:var(--muted); width:16px; margin-top:3px;"></i>
                                  <div>
                                    <div style="font-size:12px; color:var(--muted); font-weight:700;"><?= e($_data['add_new_form_field_text_15']); ?></div>
                                    <div style="font-weight:700; color:var(--ink);"><?= e($row['issue_date']); ?></div>
                                  </div>
                                </div>
                              </div>
                            </div>

                            <div style="display:flex; gap:8px; flex-wrap:wrap; margin-top:10px;">
                              <span class="chip green"><i class="fa fa-credit-card"></i> <?= e($symbol) . " " . number_format((float)$amt_paid, 2); ?> Paid</span>
                              <span class="chip yellow"><i class="fa fa-undo"></i> <?= e($symbol) . " " . number_format((float)$amount_refunded, 2); ?> Refunded</span>
                              <span class="chip indigo"><i class="fa fa-balance-scale"></i> <?= e($symbol) . " " . number_format((float)$rate - (float)$amt_paid, 2); ?> Balance</span>
                            </div>
                          </div>

                          <div class="modal-footer" style="border:0; padding:12px 16px;">
                            <button type="button" class="btn btn-default" data-dismiss="modal" style="border-radius:10px; border:1px solid var(--line);">
                              <i class="fa fa-close"></i> Close
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>

                    <!-- Payment Modal -->
                    <div id="payment_view_<?= $id; ?>" class="modal fade sd-modal" tabindex="-1" role="dialog" aria-labelledby="payLabel_<?= $id; ?>" aria-hidden="true">
                      <div class="modal-dialog modal-md">
                        <div class="modal-content">
                          <div class="modal-header">
                            <div 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-credit-card" style="color:#1e40af;"></i>
                              </span>
                              <div>
                                <h3 id="payLabel_<?= $id; ?>" class="modal-title">Add Payment</h3>
                                <div style="font-size:12px; color:var(--muted); margin-top:2px;">
                                  Tenant: <span style="font-weight:700; color:var(--ink);"><?= e($tenant); ?></span>
                                </div>
                              </div>
                            </div>
                            <button aria-label="Close" data-dismiss="modal" class="close" type="button">
                              <span aria-hidden="true"><i class="fa fa-close"></i></span>
                            </button>
                          </div>

                          <div class="modal-body" style="padding:16px 16px 8px;">
                            <div style="display:flex; align-items:center; gap:14px;">
                              <img src="<?= e($image); ?>" alt="<?= e($tenant); ?> photo" style="width:64px; height:64px; border-radius:50%; object-fit:cover; border:1px solid var(--line);">
                              <div style="display:flex; gap:8px; flex-wrap:wrap;">
                                <span class="chip indigo"><i class="fa fa-balance-scale"></i> Balance: <?= e($symbol); ?> <?= number_format($balance, 2); ?></span>
                              </div>
                            </div>
                          </div>

                          <div class="modal-body" style="padding:8px 16px 16px;">
                            <form id="payment_form_<?= $id; ?>" action="<?= $add_payment_url; ?>" method="post" enctype="multipart/form-data" novalidate>
                              <div class="box-body" style="padding:0; margin:0;">
                                <div class="form-group">
                                  <label for="balance_display_<?= $id; ?>" style="font-weight:700; color:var(--ink2);">Balance Remaining</label>
                                  <div class="input-group">
                                    <div class="input-group-addon"><?= e($symbol); ?></div>
                                    <input id="balance_display_<?= $id; ?>" type="text" readonly value="<?= number_format($balance, 2); ?>" class="form-control" />
                                  </div>
                                </div>

                                <div class="form-group">
                                  <label for="amount_paid_<?= $id; ?>" style="font-weight:700; color:var(--ink2);">Amount Paid</label>
                                  <div class="input-group">
                                    <div class="input-group-addon"><?= e($symbol); ?></div>
                                    <input
                                      id="amount_paid_<?= $id; ?>"
                                      type="number"
                                      step="0.01"
                                      min="0.01"
                                      max="<?= $balance; ?>"
                                      name="amount_paid"
                                      class="form-control"
                                      placeholder="0.00"
                                      required
                                      oninvalid="this.setCustomValidity('Enter an amount up to the remaining balance')"
                                      oninput="setCustomValidity('')"
                                    >
                                  </div>
                                  <div style="display:flex; align-items:center; justify-content:space-between; margin-top:8px;">
                                    <span style="color:var(--muted); font-size:12px;">Max: <?= e($symbol); ?> <?= number_format($balance, 2); ?></span>
                                    <div style="display:flex; gap:6px;">
                                      <button class="btn btn-ghost btn-xs" id="fill_max_<?= $id; ?>"><i class="fa fa-arrow-up"></i> Full balance</button>
                                      <button class="btn btn-ghost btn-xs" id="clear_amt_<?= $id; ?>"><i class="fa fa-eraser"></i> Clear</button>
                                    </div>
                                  </div>
                                </div>

                                <div class="form-group" style="margin-top:6px;">
                                  <div style="display:flex; align-items:center; gap:8px; font-weight:700; color:var(--ink);">
                                    <i class="fa fa-calculator" style="color:var(--muted);"></i>
                                    Remaining after this payment:
                                    <span><?= e($symbol); ?></span>
                                    <span id="remaining_after_<?= $id; ?>"><?= number_format($balance, 2); ?></span>
                                  </div>
                                </div>
                              </div>

                              <input type="hidden" name="security_deposit_id" value="<?= $id; ?>" />

                              <div class="box-footer" style="display:flex; justify-content:flex-end; gap:8px; margin-top:4px;">
                                <button type="button" class="btn btn-default" data-dismiss="modal" style="border-radius:10px; border:1px solid var(--line);">
                                  <i class="fa fa-close"></i> Cancel
                                </button>
                                <button type="submit" class="btn btn-success" style="border-radius:10px;">
                                  <i class="fa fa-floppy-o"></i> Save
                                </button>
                              </div>
                            </form>
                          </div>

                        </div>
                      </div>
                    </div>

                    <!-- Partial Refund Modal -->
                    <div id="refund_view_<?= $id; ?>" class="modal fade sd-modal refund-modal" tabindex="-1" role="dialog" aria-labelledby="refundLabel_<?= $id; ?>" aria-hidden="true" data-submitted="0">
                      <div class="modal-dialog">
                        <div class="modal-content">
                          <div class="modal-header">
                            <h3 id="refundLabel_<?= $id; ?>" class="modal-title">
                              <i class="fa fa-undo" aria-hidden="true"></i> Record Partial Refund
                            </h3>
                            <button aria-label="Close" data-dismiss="modal" class="close" type="button">
                              <span aria-hidden="true"><i class="fa fa-close"></i></span>
                            </button>
                          </div>

                          <div class="modal-body" style="padding:16px 16px 6px;">
                            <div class="refund-grid">
                              <div class="refund-card"><div class="label">Tenant</div><div class="value"><?= e($tenant); ?></div></div>
                              <div class="refund-card"><div class="label">Deposit</div><div class="value"><span class="pill pill-strong"><?= e($symbol); ?> <?= number_format($rate, 2); ?></span></div></div>
                              <div class="refund-card"><div class="label">Paid</div><div class="value"><span class="pill pill-green"><?= e($symbol); ?> <?= number_format($amt_paid, 2); ?></span></div></div>
                              <div class="refund-card"><div class="label">Already Refunded</div><div class="value"><span class="pill pill-blue"><?= e($symbol); ?> <?= number_format($amount_refunded, 2); ?></span></div></div>
                              <div class="refund-card refund-card-span"><div class="label">Max Refundable Now</div><div class="value"><span class="pill pill-strong" id="maxNow_<?= $id; ?>"><?= e($symbol); ?> <?= number_format($max_refundable, 2); ?></span></div></div>
                            </div>

                            <?php $disabled = ($max_refundable <= 0); ?>

                            <form id="refund_form_<?= $id; ?>" class="refund-form" action="<?= $add_refund_url; ?>" method="post"
                                  onsubmit="$('#refund_view_<?= $id; ?>').attr('data-submitted','1');" style="margin-top:10px;" novalidate>
                              <div class="form-group" style="margin-bottom:10px;">
                                <label for="refund_amount_<?= $id; ?>" style="font-weight:700;color:var(--ink2);">Refund Amount</label>
                                <div class="input-group" style="display:flex;align-items:stretch;">
                                  <div class="input-group-addon" style="border:1px solid var(--line);border-right:none;border-radius:12px 0 0 12px;background:transparent;min-width:48px;text-align:center;display:flex;align-items:center;justify-content:center;color:var(--ink);">
                                    <?= e($symbol); ?>
                                  </div>
                                  <input
                                    type="number"
                                    step="0.01"
                                    min="0.01"
                                    max="<?= $max_refundable; ?>"
                                    name="refund_amount"
                                    id="refund_amount_<?= $id; ?>"
                                    class="form-control"
                                    style="border:1px solid var(--line);border-left:none;border-radius:0 12px 12px 0;height:38px;background:transparent;color:var(--ink2);"
                                    <?= $disabled ? 'disabled' : 'required'; ?>
                                    placeholder="0.00"
                                    oninvalid="this.setCustomValidity('Enter a valid amount below the max refundable')"
                                    oninput="setCustomValidity('')">
                                </div>

                                <div class="helper-row" style="display:flex; justify-content:space-between; align-items:center; margin-top:6px; gap:8px; flex-wrap:wrap;">
                                  <div class="quick">
                                    <button type="button" class="btn btn-ghost btn-xs" onclick="fillRefund<?= $id; ?>(0.25)" <?= $disabled ? 'disabled' : ''; ?>>25%</button>
                                    <button type="button" class="btn btn-ghost btn-xs" onclick="fillRefund<?= $id; ?>(0.50)" <?= $disabled ? 'disabled' : ''; ?>>50%</button>
                                    <button type="button" class="btn btn-ghost btn-xs" onclick="fillRefund<?= $id; ?>(0.99)"  <?= $disabled ? 'disabled' : ''; ?>>99%</button>
                                  </div>
                                  <div class="hint" id="afterHint_<?= $id; ?>" aria-live="polite" style="color:var(--muted);font-size:12px;"></div>
                                </div>
                                <small style="color:var(--muted);display:block;margin-top:4px;">Note: For a full refund, choose <b>Refunded</b> in the status selector.</small>
                              </div>

                              <input type="hidden" name="security_deposit_id" value="<?= $id; ?>">
                              <input type="hidden" name="new_status" value="3">

                              <div class="modal-footer" style="display:flex;justify-content:flex-end;gap:8px;border-top:1px solid var(--line);">
                                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                                <button id="refund_save_btn_<?= $id; ?>" type="submit" class="btn btn-success" <?= $disabled ? 'disabled' : ''; ?>>
                                  <i class="fa fa-floppy-o" aria-hidden="true"></i> Save
                                </button>
                              </div>
                            </form>

                            <?php if ($disabled): ?>
                              <div class="alert alert-info" style="margin:8px 0 0;border-radius:10px;">
                                Nothing refundable at the moment.
                              </div>
                            <?php endif; ?>
                          </div>
                        </div>
                      </div>
                    </div>

                    <!-- Hidden form for FULL refund auto-submit -->
                    <form id="full_refund_form_<?= $id; ?>" action="<?= $add_refund_url; ?>" method="post" style="display:none;">
                      <input type="hidden" name="security_deposit_id" value="<?= $id; ?>">
                      <input type="hidden" name="refund_amount" value="">
                      <input type="hidden" name="new_status" value="2">
                    </form>

                  </td>
                </tr>
                <?php
                  // --- Buffer per-row JS (no <script> tags inside <tbody>) ---
                  $jsId            = (int)$id;
                  $jsBalance       = json_encode((float)$balance);
                  $jsSymbol        = json_encode((string)$symbol);
                  $jsMaxRefundable = json_encode((float)$max_refundable);

                  $rowScripts[] = "
(function(){
  var max = {$jsBalance};
  var sym = {$jsSymbol};
  var id  = {$jsId};

  var inputEl = document.getElementById('amount_paid_' + id);
  var remEl   = document.getElementById('remaining_after_' + id);
  var maxBtn  = document.getElementById('fill_max_' + id);
  var clrBtn  = document.getElementById('clear_amt_' + id);
  var formEl  = document.getElementById('payment_form_' + id);

  function fmt(n){ return (Number.isFinite(n) ? n : 0).toFixed(2); }
  function validate(){
    if (!inputEl || !remEl) return;
    var val = parseFloat(inputEl.value || '0');
    if (isNaN(val) || val <= 0){
      inputEl && inputEl.setCustomValidity('Enter an amount greater than 0.00');
    } else if (val > max){
      inputEl && inputEl.setCustomValidity('Cannot exceed remaining balance (' + sym + ' ' + fmt(max) + ')');
    } else {
      inputEl && inputEl.setCustomValidity('');
    }
    var remain = max - (isNaN(val) ? 0 : val);
    remEl.textContent = fmt(Math.max(0, remain));
  }

  inputEl && inputEl.addEventListener('input', validate);
  inputEl && inputEl.addEventListener('blur', validate);
  maxBtn && maxBtn.addEventListener('click', function(e){ e.preventDefault(); if (inputEl){ inputEl.value = fmt(max); inputEl.dispatchEvent(new Event('input', {bubbles:true})); } });
  clrBtn && clrBtn.addEventListener('click', function(e){ e.preventDefault(); if (inputEl){ inputEl.value = ''; inputEl.dispatchEvent(new Event('input', {bubbles:true})); } });
  formEl && formEl.addEventListener('submit', function(e){ validate(); if (!formEl.checkValidity()){ e.preventDefault(); e.stopPropagation(); } });
  validate();
})();

(function(){
  var id     = {$jsId};
  var max    = {$jsMaxRefundable};
  var symbol = {$jsSymbol};

  function fmt(n){ return (Math.round(n * 100) / 100).toFixed(2); }

  window.fillRefund{$jsId} = function(frac){
    var input = document.getElementById('refund_amount_' + id);
    if (!input || max <= 0) return;
    var val = Math.max(0.01, Math.min(max * frac, max - 0.01));
    input.value = fmt(val);
    window.updateHint{$jsId}();
  };

  window.updateHint{$jsId} = function(){
    var input = document.getElementById('refund_amount_' + id);
    var hint  = document.getElementById('afterHint_' + id);
    if (!input || !hint) return;
    var v = parseFloat(input.value || '0');
    if (isNaN(v) || v <= 0) {
      hint.textContent = '';
      input.setCustomValidity('');
      return;
    }
    if (v >= max - 0.00001) {
      input.setCustomValidity('Amount must be less than the remaining refundable. Use Completed for full refund.');
      hint.textContent = 'For a full refund, change status to Completed.';
    } else {
      input.setCustomValidity('');
      var remain = max - v;
      hint.textContent = 'Remaining refundable after this: ' + symbol + ' ' + fmt(remain);
    }
  };

  var input = document.getElementById('refund_amount_' + id);
  var form  = document.getElementById('refund_form_' + id);
  if (input){
    input.addEventListener('input', window.updateHint{$jsId});
    input.addEventListener('blur', window.updateHint{$jsId});
    window.updateHint{$jsId}();
  }
  if (form){
    form.addEventListener('submit', function(e){
      window.updateHint{$jsId}();
      if (!form.checkValidity()){
        e.preventDefault();
        e.stopPropagation();
      }
    });
  }
})();
";
                  endwhile;
                  mysqli_close($link); $link = NULL;
                }
                ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

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

<?php if (!empty($rowScripts)): ?>
  <!-- Per-row scripts printed ONCE, outside <tbody> -->
  <script>
    <?php echo implode("\n", $rowScripts); ?>
  </script>
<?php endif; ?>

<script>
  // Delete record
  function deleteSecurityDeposit(Id){
    var go = function(){ window.location = '<?= WEB_URL; ?>security_deposit/security_deposit_list.php?action=delete&id=' + Id; };
    if (typeof sweetConfirmDelete === 'function') sweetConfirmDelete(go);
    else if (confirm('<?= addslashes($_data['delete_text']);?>?')) go();
  }

  // Status change workflow
  function _set_security_status(selectEl){
    var val        = selectEl.value;
    var prev       = selectEl.getAttribute('data-prev') || '0';
    var id         = parseInt(selectEl.getAttribute('data-id') || '0', 10);
    var amtPaid    = parseFloat(selectEl.getAttribute('data-amtpaid') || '0');
    var alreadyRef = parseFloat(selectEl.getAttribute('data-refunded') || '0');
    var remaining  = Math.max(0, amtPaid - alreadyRef);

    // Guard: If no amount paid, disallow 2/3
    if ((val === '2' || val === '3') && !(amtPaid > 0)) {
      alert('Cannot set to Refunded or Partially Refunded when no amount has been paid.');
      selectEl.value = prev;
      return;
    }

    // Partially refunded -> open partial refund modal; revert to prev if closed without submit
    if (val === '3') {
      var $modal = $('#refund_view_' + id);
      $modal.attr('data-submitted','0');
      $modal.off('hidden.bs.modal').on('hidden.bs.modal', function(){
        if ($(this).attr('data-submitted') !== '1') selectEl.value = prev;
      });
      $modal.modal('show');
      return;
    }

    // Fully refunded -> if money remaining, submit hidden form; else update status via AJAX
    if (val === '2') {
      if (remaining > 0) {
        var frm = document.getElementById('full_refund_form_' + id);
        if (frm) {
          frm.querySelector('input[name="refund_amount"]').value = remaining.toFixed(2);
          frm.submit();
          return;
        }
      }
      $.ajax({
        url: "<?= WEB_URL; ?>/ajax/getunit.php",
        type: 'POST',
        data: 'status=2&id=' + encodeURIComponent(id) + '&token=updateSecurityStatus',
        dataType: 'json',
        success: function(data) {
          if (data != '-99') {
            alert(data.msg);
            selectEl.setAttribute('data-prev', '2');
            window.location.reload();
          } else {
            window.location.href = '../index.php';
          }
        }
      });
      return;
    }

    // Pending / Withhold -> simple AJAX update
    $.ajax({
      url: "<?= WEB_URL; ?>/ajax/getunit.php",
      type: 'POST',
      data: 'status=' + encodeURIComponent(val) + '&id=' + encodeURIComponent(id) + '&token=updateSecurityStatus',
      dataType: 'json',
      success: function(data) {
        if (data != '-99') {
          alert(data.msg);
          selectEl.setAttribute('data-prev', val);
          window.location.reload();
        } else {
          window.location.href = '../index.php';
        }
      }
    });
  }

  // Init (SAFE DataTables init — avoids colspan/script issues)
  document.addEventListener('DOMContentLoaded', function(){
    // Alerts auto-hide
    setTimeout(function(){
      var me  = document.getElementById('me');
      var you = document.getElementById('you');
      me  && (me.style.display  = 'none');
      you && (you.style.display = 'none');
    }, 3000);

    if ($.fn.tooltip) $('[data-toggle="tooltip"]').tooltip();

    if ($.fn.DataTable) {
      var $tbl = $('#sdTable');
      var dt;
      if ( $.fn.DataTable.isDataTable('#sdTable') ) {
        dt = $tbl.DataTable();              // retrieve existing instance
        dt.order([0, 'desc']).draw(false);  // newest first
      } else {
        dt = $tbl.DataTable({
          pageLength: 10,
          order: [[0, 'desc']],             // newest first by ID
          responsive: true,
          autoWidth: false,
          language: {
            emptyTable:
              '<div class="empty"><i class="fa fa-inbox" style="font-size:20px;margin-bottom:8px;"></i> No security deposits yet.</div>',
            zeroRecords: 'No matching records found'
          },
          columnDefs: [
            { orderable: false, targets: [10] } // actions column
          ]
        });
      }

      // Hook our external search to DataTables search API
      var $search = $('#sdSearch');
      if ($search.length) {
        $search.on('input', function(){ dt.search(this.value).draw(); });
        // Keyboard shortcut: Ctrl + / focuses search
        document.addEventListener('keydown', function(e){
          if ((e.ctrlKey || e.metaKey) && e.key === '/'){
            e.preventDefault();
            $search.trigger('focus');
          }
        });
      }
    }
  });
</script>

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