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

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

$delinfo = 'none';
$addinfo = 'none';
$msg = "";

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

/* ---------- Safe delete (if requested) ---------- */
if (isset($_GET['id']) && (int)$_GET['id'] > 0) {
  $tid = (int)$_GET['id'];
  mysqli_query($link, "DELETE FROM tenants WHERE tid = {$tid}");
  $delinfo = 'block';
}

/* ---------- Success flash from actions ---------- */
if (isset($_GET['m']) && $_GET['m'] === 'add') { $addinfo = 'block'; $msg = $_data['added_renter_successfully']; }
if (isset($_GET['m']) && $_GET['m'] === 'up')  { $addinfo = 'block'; $msg = $_data['update_renter_successfully']; }
if (isset($_SESSION["message"])) { $addinfo = 'block'; $msg = $_SESSION["message"]; unset($_SESSION["message"]); }

$assign_unit_url = WEB_URL . "tenant/addtenant.php?action=assign";

/* ---------- Preload blocks for assign modal ---------- */
$blockOptions = '';
$resBlocks = mysqli_query($link, "SELECT bid, b_name FROM blocks ORDER BY b_name ASC");
if ($resBlocks) {
  while ($b = mysqli_fetch_assoc($resBlocks)) {
    $blockOptions .= '<option value="'.(int)$b['bid'].'">'.e($b['b_name']).'</option>';
  }
  mysqli_free_result($resBlocks);
}
?>
<!-- Content Header -->
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;">
    <i class="fa fa-users"></i> <?= e($_data['renter_list']); ?>
  </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_renter_information_breadcam']); ?></li>
    <li class="active"><?= e($_data['renter_list']); ?></li>
  </ol>
</section>

<!-- Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">

<!-- Styles -->
<style>
  :root{
    /* Neutral base */
    --bg:#ffffff; --ink:#111827; --ink-2:#334155; --muted:#64748b; --line:#e5e7eb;
    --soft:#f8fafc; --soft-2:#eef2ff; --chip:#f3f4f6;

    /* Action palette (indigo-first) */
    --primary:#4f46e5; --primary-700:#4338ca; --primary-soft:#eef2ff;
    --success:#16a34a; --warning:#f59e0b; --info:#0ea5e9; --danger:#ef4444;
  }

  body, .content-wrapper, .box, .modal-content, .table{
    background:var(--bg);
    color:var(--ink-2);
    font-family:'Inter',system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial;
  }

  .content-header>h1{ font-weight:800; color:var(--ink); letter-spacing:.2px; }

  /* Card */
  .box.box-success{
    border-radius:16px; overflow:hidden;
    border:1px solid var(--line);
    box-shadow:0 12px 32px rgba(2,6,23,.06);
  }
  .box.box-success .box-header{
    background:linear-gradient(135deg,var(--soft),var(--soft-2));
    border-bottom:1px solid var(--line);
  }
  .box.box-success .box-title{ font-weight:800; color:var(--ink); }

  /* Alerts */
  .alert{ border-radius:12px; border:none; box-shadow:0 8px 24px rgba(0,0,0,.08); }
  .alert-success{ background:#ecfdf5; color:#065f46; }
  .alert-danger{ background:#fef2f2; color:#7f1d1d; }

  /* Action bar (top-right CTAs) */
  .action-bar{ display:flex; align-items:center; justify-content:flex-end; gap:8px; margin-bottom:12px; }
  .btn{
    border:none; border-radius:10px; font-weight:700; transition:all .12s ease;
  }
  .btn:hover{ transform:translateY(-1px); box-shadow:0 8px 16px rgba(0,0,0,.06); }

  /* Colored “action keys” */
  .btn-primary{ background:var(--primary); color:#fff; }
  .btn-primary:hover{ background:var(--primary-700); }
  .btn-success{ background:var(--success); color:#fff; }
  .btn-warning{ background:var(--warning); color:#111; }
  .btn-info{ background:var(--info); color:#fff; }
  .btn-danger{ background:var(--danger); color:#fff; }
  .btn-default{ background:#fff; border:1px solid var(--line); color:var(--ink-2); }

  /* Compact action buttons (table row) */
  .btn-compact{ padding:6px 10px !important; font-size:12px !important; line-height:1.2 !important; border-radius:10px !important; }
  .btn-compact i{ font-size:12px; }

  /* Table */
  table.sakotable{ width:100%; }
  .table thead th{
    background:var(--soft);
    color:var(--ink);
    font-weight:800;
    border-bottom:1px solid var(--line) !important;
  }
  .table td, .table th{ vertical-align:middle !important; }
  .table>tbody>tr:hover{ background:#fafafa; }

  .photo_img_round{
    border-radius:50%;
    border:2px solid #fff;
    box-shadow:0 6px 16px rgba(2,6,23,.1);
  }

  /* Status select (pill) */
  .status-select{
    border-radius:999px !important; padding:6px 12px !important; min-width:160px;
    font-weight:700 !important; border:1px solid var(--line) !important; background:#fff !important; color:var(--ink-2) !important;
  }
  .status-active{ background:#ecfdf5 !important; color:#065f46 !important; border-color:#86efac !important; }
  .status-archived{ background:#f1f5f9 !important; color:#334155 !important; border-color:#cbd5e1 !important; }

  /* Chips */
  .chip{
    display:inline-flex; align-items:center; gap:6px; background:var(--chip); color:var(--ink-2);
    padding:4px 10px; border-radius:999px; font-size:12px; font-weight:700; border:1px solid var(--line);
  }
  .chip i{ opacity:.8; }

  /* Tenant modal (view) */
  .tenant-modal .modal-content{ border:0; border-radius:16px; overflow:hidden; box-shadow:0 18px 42px rgba(2,6,23,.18); }
  .tenant-modal .modal-header{ background:linear-gradient(135deg,var(--primary),#818cf8); color:#fff; padding:14px 18px; }
  .tenant-modal .modal-title{ font-weight:800; letter-spacing:.2px; }
  .tenant-hero{ display:flex; flex-direction:column; align-items:center; gap:10px; padding:16px 12px 6px; }
  .tenant-avatar{ width:140px; height:140px; border-radius:16px; object-fit:cover; border:3px solid #fff; box-shadow:0 8px 24px rgba(2,6,23,.15); }
  .tenant-name{ font-size:20px; font-weight:800; color:var(--ink); }
  .tenant-status{ display:inline-flex; align-items:center; gap:6px; font-size:12px; font-weight:800; padding:4px 10px; border-radius:999px; background:#e2fbe8; color:#065f46; }
  .tenant-status.archived{ background:#fee2e2; color:#991b1b; }

  .tenant-section-title{ font-weight:800; font-size:16px; color:var(--ink); margin:6px 0 10px; border-bottom:1px solid var(--line); padding-bottom:6px; }

  /* Info list */
  .info-list .list-group-item{
    display:flex; align-items:center; gap:10px; border:1px solid #eef2f7; border-radius:10px !important; margin-bottom:8px; padding:10px 12px;
  }
  .info-icon{ width:28px; height:28px; display:grid; place-items:center; border-radius:8px; background:var(--primary-soft); color:#374151; flex:0 0 28px; }
  .info-label{ color:#475569; font-weight:600; min-width:140px; }
  .info-value{ color:var(--ink); font-weight:700; }

  .unit-chip{ display:inline-flex; align-items:center; gap:6px; background:#f1f5f9; color:var(--ink); border-radius:999px; padding:6px 10px; margin:0 8px 8px 0; font-size:12px; font-weight:700; border:1px solid var(--line); }
  .unit-chip i{ opacity:.85; }

  .btn-soft{ border-radius:10px; border:1px solid var(--line); background:#fff; color:#111827; padding:8px 12px; font-weight:700; }
  .btn-soft:hover{ background:#f9fafb; }

  /* Assign modal header */
  .green_header{ background:linear-gradient(135deg,#22c55e,#86efac); color:#052e16; }

  /* Helpers */
  .text-muted{ color:#94a3b8; }
</style>

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

      <!-- Alerts -->
      <div id="me" class="alert alert-danger alert-dismissable" style="display:<?= $delinfo; ?>">
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button"><i class="fa fa-close"></i></button>
        <h4><i class="icon fa fa-ban"></i> <?= e($_data['delete_text']); ?>!</h4>
        <?= e($_data['delete_renter_information']); ?>
      </div>

      <div id="you" class="alert alert-success alert-dismissable" style="display:<?= $addinfo; ?>">
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button"><i class="fa fa-close"></i></button>
        <h4><i class="icon fa fa-check"></i> <?= e($_data['success']); ?>!</h4>
        <?= e($msg); ?>
      </div>

      <!-- Action bar -->
      <div class="action-bar">
        <a class="btn btn-success btn-compact" data-toggle="tooltip" href="<?= WEB_URL; ?>tenant/addtenant.php" title="<?= e($_data['add_new_rent_breadcam']); ?>">
          <i class="fa fa-plus"></i> <?= e($_data['add_new_rent_breadcam']); ?>
        </a>
        <a class="btn btn-primary btn-compact" data-toggle="tooltip" href="<?= WEB_URL; ?>dashboard.php" title="<?= e($_data['home_breadcam']); ?>">
          <i class="fa fa-dashboard"></i> <?= e($_data['home_breadcam']); ?>
        </a>
      </div>

      <div class="box box-success">
        <div class="box-header">
          <h3 class="box-title"><i class="fa fa-list"></i> <?= e($_data['renter_list']); ?></h3>
        </div>
        <div class="box-body">
          <table id="sakotable" class="table sakotable table-bordered table-striped dt-responsive nowrap">
            <thead>
              <tr>
                <th><?= e($_data['add_new_form_field_text_0']); ?></th>
                <th><?= e($_data['add_new_form_field_text_1']); ?></th>
                <th><?= e($_data['add_new_form_field_text_4']); ?></th>
                <th>Email</th>
                <th>Tenant Status</th>
                <th>Assigned Unit/Shop</th>
                <th><?= e($_data['action_text']); ?></th>
              </tr>
            </thead>
            <tbody>
            <?php
            $result = mysqli_query($link, "SELECT * FROM tenants WHERE r_status = 1 ORDER BY r_name ASC");
            while ($row = mysqli_fetch_assoc($result)):
              $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'];
              }
              // Units assigned to this tenant
              $units = [];
              $qUnits = mysqli_query($link, "SELECT * FROM occupied_units_view WHERE tenant_id = ".(int)$row['tid']);
              while ($u = mysqli_fetch_assoc($qUnits)) { $units[] = $u; }
              $isActive = ($row['r_status'] == '1');
            ?>
              <tr>
                <!-- Avatar -->
                <td><img class="photo_img_round" style="width:50px;height:50px;" src="<?= e($image); ?>" alt="Tenant photo"></td>

                <!-- Name / Contact / Email -->
                <td><strong><?= e($row['r_name']); ?></strong></td>
                <td><?= e($row['r_contact']); ?></td>
                <td><?= e($row['r_email']); ?></td>

                <!-- Status -->
                <td>
                  <select name="ddlStatus"
                          onchange="_set_tenant_status(<?= (int)$row['tid']; ?>, this);"
                          class="form-control status-select <?= $isActive ? 'status-active' : 'status-archived'; ?>">
                    <option value="1" <?= $isActive ? 'selected' : ''; ?>><?= e($_data['r_status_on_active']); ?></option>
                    <option value="2" <?= !$isActive ? 'selected' : ''; ?>><?= e($_data['r_status_on_archive']); ?></option>
                  </select>
                </td>

                <!-- Assignments -->
                <td>
                  <?php if (count($units) === 0): ?>
                    <span class="chip"><i class="fa fa-info-circle"></i> <?= e($_data['add_new_form_field_text_15'] ?? 'No assignment'); ?></span>
                  <?php else: foreach ($units as $unit): ?>
                    <span class="chip" title="<?= e($unit['b_name'].' / '.$unit['unit_no']); ?>">
                      <i class="fa fa-building"></i> <?= e($unit['b_name']); ?> — <?= e($unit['unit_no']); ?>
                      <a class="btn btn-danger btn-compact" style="margin-left:6px;"
                         data-toggle="tooltip"
                         onclick="ejectTenant(<?= (int)$unit['assignment_id']; ?>)"
                         title="Eject">
                        <i class="fa fa-sign-out"></i>
                      </a>
                    </span>
                  <?php endforeach; endif; ?>
                </td>

                <!-- Actions (compact) -->
                <td>
                  <div class="btn-group" role="group" aria-label="tenant-actions">
                    <a class="btn btn-success btn-compact" data-toggle="tooltip" href="javascript:;" onclick="$('#tenant_view_<?= (int)$row['tid']; ?>').modal('show');" title="<?= e($_data['view_text']); ?>">
                      <i class="fa fa-eye"></i>
                    </a>
                    <a class="btn btn-info btn-compact" data-toggle="tooltip" onclick="accountTenant(<?= (int)$row['tid']; ?>);" href="javascript:;" title="Account Statement">
                      <i class="fa fa-money"></i>
                    </a>
                    <a class="btn btn-primary btn-compact" data-toggle="tooltip" href="javascript:;" onclick="$('#assign_<?= (int)$row['tid']; ?>').modal('show');" title="Assign to Unit">
                      <i class="fa fa-clipboard"></i>
                    </a>
                    <a class="btn btn-warning btn-compact" data-toggle="tooltip" href="<?= WEB_URL; ?>tenant/addtenant.php?id=<?= (int)$row['tid']; ?>" title="<?= e($_data['edit_text']); ?>">
                      <i class="fa fa-pencil"></i>
                    </a>
                    <a class="btn btn-danger btn-compact" data-toggle="tooltip" onclick="deleteTenant(<?= (int)$row['tid']; ?>);" href="javascript:;" title="<?= e($_data['delete_text']); ?> From System">
                      <i class="fa fa-trash-o"></i>
                    </a>
                  </div>

                  <!-- View modal -->
                  <div id="tenant_view_<?= (int)$row['tid']; ?>" class="modal fade tenant-modal" tabindex="-1" role="dialog" aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                      <div class="modal-content">
                        <!-- Header -->
                        <div class="modal-header">
                          <button aria-label="Close" data-dismiss="modal" class="close" type="button">
                            <span aria-hidden="true"><i class="fa fa-close"></i></span>
                          </button>
                          <div style="display:flex;align-items:center;gap:10px;">
                            <span style="display:inline-flex;width:36px;height:36px;border-radius:10px;background:#ffffff1a;align-items:center;justify-content:center;">
                              <i class="fa fa-id-badge"></i>
                            </span>
                            <div>
                              <h3 class="modal-title" style="margin:0;"><?= e($_data['rented_details']); ?></h3>
                              <div style="opacity:.9;font-size:12px;margin-top:2px;">Tenant profile & assignments</div>
                            </div>
                          </div>
                        </div>

                        <!-- Hero -->
                        <div class="tenant-hero" style="padding:16px 16px 8px;background:linear-gradient(180deg,#f8fafc,#fff);">
                          <img class="tenant-avatar" src="<?= e($image); ?>" alt="<?= e($row['r_name']); ?> photo" />
                          <div class="tenant-name"><?= e($row['r_name']); ?></div>
                          <?php $activeLbl = $isActive ? ($_data['add_new_form_field_text_16'] ?? 'Active') : ($_data['add_new_form_field_text_17'] ?? 'Archived'); ?>
                          <span class="tenant-status <?= $isActive ? '' : 'archived' ?>">
                            <i class="fa <?= $isActive ? 'fa-check-circle' : 'fa-archive' ?>"></i> <?= e($activeLbl); ?>
                          </span>
                        </div>

                        <!-- Body -->
                        <div class="modal-body" style="padding: 12px 18px 18px;">
                          <div class="row">
                            <!-- Left: Details -->
                            <div class="col-sm-6">
                              <div class="tenant-section-title">
                                <?= e($_data['details_information']); ?>
                              </div>
                              <ul class="list-group info-list" style="margin-bottom:0;">
                                <li class="list-group-item">
                                  <span class="info-icon"><i class="fa fa-user"></i></span>
                                  <span class="info-label"><?= e($_data['add_new_form_field_text_1']); ?>:</span>
                                  <span class="info-value"><?= e($row['r_name']); ?></span>
                                </li>
                                <li class="list-group-item">
                                  <span class="info-icon"><i class="fa fa-envelope-o"></i></span>
                                  <span class="info-label"><?= e($_data['add_new_form_field_text_2']); ?>:</span>
                                  <span class="info-value">
                                    <?php if (!empty($row['r_email'])): ?>
                                      <a href="mailto:<?= e($row['r_email']); ?>" style="text-decoration:none;"><?= e($row['r_email']); ?></a>
                                      <button type="button" class="btn btn-soft btn-xs" onclick="copyText('<?= e($row['r_email']); ?>')" title="Copy email" style="margin-left:6px;">
                                        <i class="fa fa-copy"></i>
                                      </button>
                                    <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                                  </span>
                                </li>
                                <li class="list-group-item">
                                  <span class="info-icon"><i class="fa fa-phone"></i></span>
                                  <span class="info-label"><?= e($_data['add_new_form_field_text_4']); ?>:</span>
                                  <span class="info-value">
                                    <?php if (!empty($row['r_contact'])): ?>
                                      <a href="tel:<?= e($row['r_contact']); ?>" style="text-decoration:none;"><?= e($row['r_contact']); ?></a>
                                      <button type="button" class="btn btn-soft btn-xs" onclick="copyText('<?= e($row['r_contact']); ?>')" title="Copy phone" style="margin-left:6px;">
                                        <i class="fa fa-copy"></i>
                                      </button>
                                    <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                                  </span>
                                </li>
                                <li class="list-group-item">
                                  <span class="info-icon"><i class="fa fa-map-marker"></i></span>
                                  <span class="info-label"><?= e($_data['add_new_form_field_text_5']); ?>:</span>
                                  <span class="info-value"><?= e($row['r_address'] ?: '—'); ?></span>
                                </li>
                                <li class="list-group-item">
                                  <span class="info-icon"><i class="fa fa-briefcase"></i></span>
                                  <span class="info-label">Business Name:</span>
                                  <span class="info-value"><?= e($row['business_name'] ?: '—'); ?></span>
                                </li>
                                <li class="list-group-item">
                                  <span class="info-icon"><i class="fa fa-phone-square"></i></span>
                                  <span class="info-label">Business Phone:</span>
                                  <span class="info-value"><?= e($row['business_phone'] ?: '—'); ?></span>
                                </li>
                                <li class="list-group-item">
                                  <span class="info-icon"><i class="fa fa-industry"></i></span>
                                  <span class="info-label">Nature of Business:</span>
                                  <span class="info-value"><?= e($row['nature_of_business'] ?: '—'); ?></span>
                                </li>
                                <li class="list-group-item">
                                  <span class="info-icon"><i class="fa fa-id-card-o"></i></span>
                                  <span class="info-label">ID CARD NO:</span>
                                  <span class="info-value"><?= e($row['document_name'] ?: '—'); ?></span>
                                </li>
                                <li class="list-group-item" style="align-items:flex-start;">
                                  <span class="info-icon"><i class="fa fa-paperclip"></i></span>
                                  <div style="flex:1;">
                                    <div class="info-label" style="margin-bottom:6px;">Attachments</div>
                                    <?php if (!empty($row['attachments'])) { ?>
                                      <a href="<?= e($row['attachments']); ?>" target="_blank" class="btn btn-soft">
                                        <i class="fa fa-file-pdf-o"></i> View Document
                                      </a>
                                    <?php } else { ?>
                                      <span class="text-muted">No Document Uploaded</span>
                                    <?php } ?>
                                  </div>
                                </li>
                              </ul>
                            </div>

                            <!-- Right: Assignments + Status -->
                            <div class="col-sm-6">
                              <div class="tenant-section-title"><i class="fa fa-cubes"></i> Assignment Units</div>
                              <?php if (!empty($units)) { ?>
                                <div style="margin-bottom:12px;display:flex;flex-wrap:wrap;gap:8px;">
                                  <?php foreach ($units as $unit): ?>
                                    <span class="unit-chip" title="<?= e($unit['b_name'].' • '.$unit['unit_no']); ?>">
                                      <i class="fa fa-building"></i> <?= e($unit['b_name']); ?> — <?= e($unit['unit_no']); ?>
                                    </span>
                                  <?php endforeach; ?>
                                </div>
                              <?php } else { ?>
                                <div class="text-muted" style="margin-bottom:12px;">No units assigned.</div>
                              <?php } ?>

                              <div class="tenant-section-title" style="margin-top:18px;">
                                <i class="fa fa-info-circle"></i> <?= e($_data['add_new_form_field_text_14']); ?>
                              </div>
                              <div style="display:flex;align-items:center;gap:8px;">
                                <span style="font-weight:800;"><?= e($activeLbl); ?></span>
                                <?php if (!empty($row['r_email'])): ?>
                                  <a class="btn btn-soft btn-xs" href="mailto:<?= e($row['r_email']); ?>">
                                    <i class="fa fa-envelope"></i> Email
                                  </a>
                                <?php endif; ?>
                                <?php if (!empty($row['r_contact'])): ?>
                                  <a class="btn btn-soft btn-xs" href="tel:<?= e($row['r_contact']); ?>">
                                    <i class="fa fa-phone"></i> Call
                                  </a>
                                <?php endif; ?>
                              </div>
                            </div>
                          </div>
                        </div>

                        <!-- Footer -->
                        <div class="modal-footer" style="display:flex;gap:8px;justify-content:flex-end;border-top:1px solid var(--line);">
                          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                          <a href="<?= WEB_URL; ?>tenant/addtenant.php?id=<?= (int)$row['tid']; ?>" class="btn btn-primary">
                            <i class="fa fa-pencil"></i> Edit
                          </a>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- Assign modal -->
                  <div id="assign_<?= (int)$row['tid']; ?>" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
                    <div class="modal-dialog">
                      <div class="modal-content" style="border:0;border-radius:16px;overflow:hidden;box-shadow:0 22px 48px rgba(2,6,23,.22);">
                        <!-- Header -->
                        <div class="modal-header green_header">
                          <button aria-label="Close" data-dismiss="modal" class="close" type="button">
                            <span aria-hidden="true"><i class="fa fa-close"></i></span>
                          </button>
                          <h3 class="modal-title" style="font-weight:800;letter-spacing:.2px;display:flex;align-items:center;gap:8px;">
                            <span style="display:inline-flex;width:34px;height:34px;border-radius:10px;background:#052e1612;align-items:center;justify-content:center;">
                              <i class="fa fa-clipboard"></i>
                            </span>
                            Assign Units / Shops
                          </h3>
                        </div>

                        <!-- Tenant Hero -->
                        <div class="modal-body" style="padding:14px 16px 6px;">
                          <div style="display:flex;flex-direction:column;align-items:center;gap:10px;">
                            <img src="<?= e($image); ?>" alt="Tenant photo"
                                 style="width:100px;height:100px;border-radius:12px;object-fit:cover;border:3px solid #fff;box-shadow:0 10px 28px rgba(2,6,23,.2);" />
                            <div style="font-weight:800;font-size:16px;color:var(--ink);"><?= e($row['r_name']); ?></div>
                            <div style="color:#475569;font-size:12px;text-align:center;">Pick a block, filter units, then assign one or many at once.</div>
                          </div>
                        </div>

                        <!-- Form -->
                        <form
                          id="assign_form_<?= (int)$row['tid']; ?>"
                          onsubmit="return bulkAssignUnits(<?= (int)$row['tid']; ?>);"
                          action="javascript:void(0);"
                          method="post"
                          data-action="<?= $assign_unit_url; ?>"
                          enctype="multipart/form-data"
                        >
                          <div class="modal-body" style="padding:10px 16px 6px;">

                            <!-- Block -->
                            <div class="form-group" style="margin-bottom:12px;">
                              <label for="bid_<?= (int)$row['tid']; ?>" style="font-weight:700;color:#111827;">
                                <span class="text-danger">*</span> Block
                              </label>
                              <select required
                                      onchange="resetUnitSelection(<?= (int)$row['tid']; ?>); if (typeof getUnoccupiedUnitInfo==='function'){ getUnoccupiedUnitInfo('bid_<?= (int)$row['tid']; ?>','uid_<?= (int)$row['tid']; ?>'); }"
                                      name="bid"
                                      id="bid_<?= (int)$row['tid']; ?>"
                                      class="form-control"
                                      style="border-radius:12px;">
                                <option value="">-- Select Block --</option>
                                <?= $blockOptions; ?>
                              </select>
                              <div style="font-size:12px;color:#64748b;margin-top:6px;">
                                Changing the block will refresh the list with <strong>unoccupied</strong> units/shops only.
                              </div>
                            </div>

                            <!-- Units (search + multi-select) -->
                            <div class="form-group" style="margin-bottom:8px;">
                              <label for="uid_<?= (int)$row['tid']; ?>" style="font-weight:700;color:#111827;display:flex;justify-content:space-between;align-items:center;">
                                <span><span class="text-danger">*</span> Units / Shops</span>
                                <span style="font-size:12px;color:#64748b;">Hold <strong>Ctrl/⌘</strong> to select multiple</span>
                              </label>

                              <!-- Quick filter -->
                              <div class="input-group" style="margin-bottom:8px;border-radius:12px;overflow:hidden;border:1px solid var(--line);">
                                <span class="input-group-addon" style="background:#fff;border:0;border-right:1px solid var(--line);"><i class="fa fa-search" aria-hidden="true"></i></span>
                                <input type="text"
                                       id="unitFilter_<?= (int)$row['tid']; ?>"
                                       oninput="filterUnits(<?= (int)$row['tid']; ?>)"
                                       class="form-control"
                                       placeholder="Type to filter unit numbers…"
                                       style="border:0;box-shadow:none;">
                              </div>

                              <!-- Multi select -->
                              <select required multiple size="8"
                                      name="uids[]"
                                      id="uid_<?= (int)$row['tid']; ?>"
                                      class="form-control"
                                      onchange="updateUnitPreview(<?= (int)$row['tid']; ?>)"
                                      style="border-radius:12px;">
                                <option value="">-- Select Block First --</option>
                              </select>

                              <!-- Small actions -->
                              <div class="row" style="margin-top:8px;">
                                <div class="col-xs-12" style="display:flex;gap:8px;flex-wrap:wrap;">
                                  <button class="btn btn-default btn-sm" type="button" onclick="selectAllUnits(<?= (int)$row['tid']; ?>, true)" style="border-radius:999px;">
                                    <i class="fa fa-check-square-o"></i> Select All (visible)
                                  </button>
                                  <button class="btn btn-default btn-sm" type="button" onclick="selectAllUnits(<?= (int)$row['tid']; ?>, false)" style="border-radius:999px;">
                                    <i class="fa fa-square-o"></i> Clear
                                  </button>
                                  <span style="font-size:12px;color:#64748b;align-self:center;">
                                    <span id="selCount_<?= (int)$row['tid']; ?>">0</span> selected
                                  </span>
                                </div>
                              </div>

                              <!-- Live selection chips -->
                              <div id="selPreview_<?= (int)$row['tid']; ?>" style="margin-top:8px;display:flex;flex-wrap:wrap;gap:6px;"></div>
                            </div>

                            <input type="hidden" name="tid" value="<?= (int)$row['tid']; ?>" />
                          </div>

                          <!-- Footer -->
                          <div class="modal-footer" style="display:flex;gap:8px;justify-content:flex-end;padding:12px 16px 14px;border-top:1px solid var(--line);">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                            <button id="assignBtn_<?= (int)$row['tid']; ?>" type="submit" class="btn btn-success" style="display:inline-flex;align-items:center;gap:8px;">
                              <i class="fa fa-floppy-o"></i>
                              <span>Assign</span>
                              <span class="assign-count" data-tid="<?= (int)$row['tid']; ?>" style="background:#16a34a1a;color:#052e16;border:1px solid #86efac;border-radius:999px;padding:2px 8px;font-weight:800;">0</span>
                            </button>
                          </div>
                        </form>

                        <!-- Lightweight loading veil -->
                        <div id="assignLoading_<?= (int)$row['tid']; ?>" style="display:none;position:absolute;inset:0;background:rgba(255,255,255,.6);backdrop-filter:saturate(140%) blur(2px);align-items:center;justify-content:center;">
                          <div style="display:flex;align-items:center;gap:10px;background:#fff;border:1px solid var(--line);border-radius:12px;padding:10px 14px;box-shadow:0 10px 28px rgba(2,6,23,.12);">
                            <i class="fa fa-spinner fa-spin"></i> <strong>Assigning…</strong>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </td>
              </tr>
            <?php endwhile; mysqli_close($link); $link = NULL; ?>
            </tbody>
          </table>
        </div>
      </div>

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

<script type="text/javascript">
  // Auto-hide alerts + paint pill colors
  $(document).ready(function(){
    setTimeout(function(){ $("#me, #you").fadeOut(300); }, 3000);

    function paintStatusSelects(){
      $('.status-select').each(function(){
        var v = $(this).val();
        $(this).toggleClass('status-active', v === '1');
        $(this).toggleClass('status-archived', v === '2');
      });
    }
    paintStatusSelects();
    $(document).on('change', '.status-select', paintStatusSelects);
  });

  function deleteTenant(Id){
    var proceed = function(){ window.location = '<?= WEB_URL; ?>tenant/tenantlist.php?id=' + Id; };
    if (typeof sweetConfirmDelete === 'function') {
      sweetConfirmDelete(proceed);
    } else {
      if (confirm(<?= json_encode($_data['confirm'] ?? 'Are you sure?'); ?>)) proceed();
    }
  }

  function ejectTenant(unit_assignment_id){
    var iAnswer = confirm("This action cannot be undone.\nAre you sure you want to eject tenant?");
    if (iAnswer){
      if (typeof post === 'function') {
        post("<?= WEB_URL; ?>tenant/eject_tenant.php", { assignment_id: unit_assignment_id });
      } else {
        window.location = "<?= WEB_URL; ?>tenant/eject_tenant.php?assignment_id=" + unit_assignment_id;
      }
    }
  }

  function _set_tenant_status(tid, object){
    $.ajax({
      url: "<?= WEB_URL; ?>/ajax/getunit.php",
      type: 'POST',
      data: 'status=' + object.value + '&tid=' + tid + '&token=updateTenantStatus',
      dataType: 'json',
      success: function (data) {
        if (data != '-99') {
          alert(data.msg);
          window.location.reload();
        } else {
          window.location.href = '../index.php';
        }
      }
    });
  }

  function accountTenant(tid){
    if (typeof post === 'function') {
      post("<?= WEB_URL; ?>tenant/account.php", { tenant_id: tid });
    } else {
      window.location = "<?= WEB_URL; ?>tenant/account.php?tenant_id=" + tid;
    }
  }

  /* ============================================================
   Assign Modal Helpers
   ============================================================ */
  (function(){
    function $id(id){ return document.getElementById(id); }
    function getSelect(tid){ return $id('uid_'+tid); }
    function getFilter(tid){ return $id('unitFilter_'+tid); }
    function getPreview(tid){ return $id('selPreview_'+tid); }
    function getCount(tid){ return $id('selCount_'+tid); }
    function getBadge(tid){ return document.querySelector('.assign-count[data-tid="'+tid+'"]'); }
    function getLoading(tid){ return $id('assignLoading_'+tid); }
    function getForm(tid){ return $id('assign_form_'+tid); }
    function optionVisible(opt){ return !opt.dataset.hidden; }

    // Filter units by the quick-search box (hides non-matching options)
    window.filterUnits = function(tid){
      var filter = (getFilter(tid).value || '').toLowerCase().trim();
      var sel = getSelect(tid);
      Array.prototype.forEach.call(sel.options, function(opt){
        if (!opt.value) return; // skip placeholder
        var txt = (opt.text || '').toLowerCase();
        var ok = (filter === '' || txt.indexOf(filter) !== -1);
        opt.style.display = ok ? '' : 'none';
        if (!ok) { opt.selected = false; opt.dataset.hidden = '1'; } else { delete opt.dataset.hidden; }
      });
      updateUnitPreview(tid);
    };

    // Select all (visible) or clear
    window.selectAllUnits = function(tid, selectAll){
      var sel = getSelect(tid);
      Array.prototype.forEach.call(sel.options, function(opt){
        if (!opt.value) return;
        if (selectAll) { if (optionVisible(opt)) opt.selected = true; }
        else { opt.selected = false; }
      });
      updateUnitPreview(tid);
    };

    // Reset on block change
    window.resetUnitSelection = function(tid){
      var sel = getSelect(tid);
      if (!sel) return;
      sel.innerHTML = '<option value="">-- Loading units… --</option>';
      getFilter(tid).value = '';
      getPreview(tid).innerHTML = '';
      var cnt = getCount(tid); if (cnt) cnt.textContent = '0';
      var badge = getBadge(tid); if (badge) badge.textContent = '0';
    };

    // Create chips for selected items and update counters
    window.updateUnitPreview = function(tid){
      var sel = getSelect(tid);
      var chosen = Array.prototype.filter.call(sel.options, function(opt){ return opt.value && opt.selected; });
      var preview = getPreview(tid);
      preview.innerHTML = '';
      chosen.forEach(function(opt){
        var chip = document.createElement('span');
        chip.className = 'chip';
        chip.innerHTML = '<i class="fa fa-building"></i> '+ (opt.text || '');
        preview.appendChild(chip);
      });
      var n = chosen.length;
      var cnt = getCount(tid); if (cnt) cnt.textContent = n;
      var badge = getBadge(tid); if (badge) badge.textContent = n;
    };

    // Bulk-assign handler: loops selected UIDs and posts them one-by-one
    window.bulkAssignUnits = function(tid){
      var sel = getSelect(tid);
      var form = getForm(tid);
      var endpoint = form.getAttribute('data-action'); // /tenant/addtenant.php?action=assign

      var uids = Array.prototype
        .filter.call(sel.options, function(opt){ return opt.value && opt.selected; })
        .map(function(opt){ return opt.value; });

      if (!uids.length) { alert('Please select at least one unit/shop.'); return false; }

      var bid = document.getElementById('bid_'+tid).value || '';
      if (!bid) { alert('Please choose a block first.'); return false; }

      // UI lock
      var btn = document.getElementById('assignBtn_'+tid);
      var veil = getLoading(tid);
      if (btn) { btn.disabled = true; btn.style.opacity = .8; }
      if (veil) { veil.style.display = 'flex'; }

      function postOne(uid){
        return $.ajax({
          url: endpoint,
          type: 'POST',
          data: { uid: uid, tid: tid, bid: bid },
          dataType: 'json'
        });
      }

      (function loop(i){
        if (i >= uids.length) {
          if (veil) veil.style.display = 'none';
          if (btn) { btn.disabled = false; btn.style.opacity = 1; }
          alert('Assignment complete for '+uids.length+' unit(s).');
          location.reload();
          return;
        }
        postOne(uids[i]).always(function(){ loop(i+1); });
      })(0);

      return false;
    };
  })();

  // Minimal copy helper (shared)
  function copyText(t){
    try {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(t);
      } else {
        const ta = document.createElement('textarea');
        ta.value = t; document.body.appendChild(ta);
        ta.select(); document.execCommand('copy'); document.body.removeChild(ta);
      }
      if (window.toastr) { toastr.success('Copied to clipboard'); }
    } catch(e) { console && console.warn && console.warn(e); }
  }
</script>

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