<?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 = "";

/* 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';
}

/* Flash messages */
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"]);
}
?>
<!-- Page Header -->
<section class="content-header">
  <h1><?= $_data['renterr_list']; ?></h1>
  <ol class="breadcrumb">
    <li><a href="<?= WEB_URL ?>dashboard.php"><i class="fa fa-dashboard"></i><?= $_data['home_breadcam']; ?></a></li>
    <li class="active"><?= $_data['add_new_renter_information_breadcam']; ?></li>
    <li class="active"><?= $_data['renterr_list']; ?></li>
  </ol>
</section>

<!-- Friendly styles & fonts -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
  :root{
    --ink-1:#0f172a; --ink-2:#334155; --muted:#64748b;
    --soft:#f8fafc; --soft-2:#eef2ff; --chip:#e2e8f0;
    --ok:#16a34a; --warn:#d97706; --danger:#dc2626; --brand:#2563eb;
  }
  .content-wrapper, .box, .modal-content, .table { font-family:'Inter',system-ui,Segoe UI,Roboto,Helvetica,Arial; color:var(--ink-2); }
  .content-header > h1 { font-weight:800; color:var(--ink-1); letter-spacing:.2px; }

  /* Card */
  .box.box-success{ border-radius:14px; overflow:hidden; box-shadow:0 8px 28px rgba(0,0,0,.06); }
  .box.box-success .box-header{ background:linear-gradient(135deg,var(--soft),var(--soft-2)); }
  .box.box-success .box-title{ font-weight:700; color:var(--ink-1); }

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

  /* Table */
  table.sakotable{ width:100%; }
  .table thead th{
    background:#f8fafc; color:var(--ink-1); font-weight:700;
    border-bottom:1px solid #e5e7eb !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;
    border:1px solid #e2e8f0 !important; background:#fff !important;
    min-width:160px; font-weight:700 !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; }
</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> <?= $_data['delete_text']; ?>!</h4>
        <?= $_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> <?= $_data['success']; ?>!</h4>
        <?= htmlspecialchars($msg); ?>
      </div>

      <div class="box box-success">
        <div class="box-header">
          <h3 class="box-title"><?= $_data['renterr_list']; ?></h3>
        </div>
        <div class="box-body">
          <table id="sakotable" class="table sakotable display table-bordered table-striped dt-responsive">
            <thead>
              <tr>
                <th><?= $_data['add_new_form_field_text_0']; ?></th>
                <th><?= $_data['add_new_form_field_text_1']; ?></th>
                <th><?= $_data['add_new_form_field_text_4']; ?></th>
                <th>Email</th>
                <th>Tenant Status</th>
              </tr>
            </thead>
            <tbody>
              <?php
              $result = mysqli_query($link, "SELECT * FROM tenants WHERE r_status = 2 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'];
                }
                $isArchived = ($row['r_status'] == '2');
              ?>
              <tr>
                <td><img class="photo_img_round" style="width:50px;height:50px;" src="<?= $image; ?>" alt="Tenant photo"></td>
                <td><strong><?= htmlspecialchars($row['r_name']); ?></strong></td>
                <td><?= htmlspecialchars($row['r_contact']); ?></td>
                <td><?= htmlspecialchars($row['r_email']); ?></td>
                <td>
                  <select name="ddlStatus"
                          onchange="_set_tenant_status(<?= (int)$row['tid']; ?>, this);"
                          class="form-control status-select <?= $isArchived ? 'status-archived' : 'status-active'; ?>">
                    <option value="1" <?= !$isArchived ? 'selected' : ''; ?>><?= $_data['r_status_on_active']; ?></option>
                    <option value="2" <?= $isArchived ? 'selected' : ''; ?>><?= $_data['r_status_on_archive']; ?></option>
                  </select>
                </td>
              </tr>
              <?php endwhile;
                mysqli_close($link); $link = NULL;
              ?>
            </tbody>
          </table>
        </div>
      </div>

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

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

    // Keep pill colors correct on change (or DataTable redraws)
    function paintStatus() {
      $('.status-select').each(function(){
        var v = $(this).val();
        $(this).toggleClass('status-active', v === '1');
        $(this).toggleClass('status-archived', v === '2');
      });
    }
    paintStatus();
    $(document).on('change', '.status-select', paintStatus);
  });

  function deleteTenant(Id) {
    var proceed = function(){ window.location = '<?= WEB_URL; ?>tenant/tenantlist.php?id=' + Id; };
    if (typeof sweetConfirmDelete === 'function') {
      sweetConfirmDelete(proceed);
    } else {
      if (confirm("<?= addslashes($_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';
        }
      }
    });
  }
</script>

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