<?php
  include_once('../header.php');
  include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_fair_security.php');
  if (!check_login()) {
    header("Location: " . WEB_URL . "logout.php");
    die();
  }
?>
<!-- Content Header -->
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;margin-bottom:6px;">
    <i class="fa fa-shield"></i> Security Deposit Report
  </h1>
  <ol class="breadcrumb" style="margin-top:6px;">
    <li>
      <a href="<?= WEB_URL ?>dashboard.php">
        <i class="fa fa-dashboard"></i> <?= $_data['home_breadcam']; ?>
      </a>
    </li>
    <li class="active"><a href="<?= WEB_URL ?>report/security_report.php"><?= $_data['text_2']; ?></a></li>
    <li class="active"><?= $_data['text_1']; ?></li>
  </ol>
</section>

<!-- Inter font + Flatpickr (sleek date picker) -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

<style>
  :root{
    --ink:#0f172a; --ink2:#334155; --muted:#64748b;
    --line:#e5e7eb; --soft:#f8fafc; --soft2:#eef2ff;
    --brand:#2563eb; --ok:#16a34a; --danger:#dc2626;
    --card:#ffffff;
  }

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

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

  /* Inputs */
  .form-group label{ font-weight:700; color:var(--ink); letter-spacing:.2px; }
  .form-control{
    border:1px solid var(--line);
    border-radius:12px;
    height:40px;
    box-shadow:none;
  }
  .form-control:focus{
    border-color:#93c5fd;
    box-shadow:0 0 0 3px rgba(59,130,246,.15);
  }
  .hint{ color:var(--muted); font-size:12px; margin-top:4px; }

  /* Input with icon */
  .input-icon{ position:relative; }
  .input-icon .fa{
    position:absolute; left:12px; top:50%; transform:translateY(-50%);
    color:#94a3b8;
  }
  .input-icon input{ padding-left:34px; }

  /* Buttons */
  .btn{ border:none; border-radius:12px; font-weight:800; letter-spacing:.2px; }
  .btn-pill{ border-radius:999px; }
  .btn-compact{ padding:8px 12px; font-size:12px; line-height:1.2; }
  .btn-primary{ background:var(--brand); color:#fff; }
  .btn-success{ background:var(--ok); color:#fff; }
  .btn-danger{ background:var(--danger); color:#fff; }
  .btn-soft{ background:#fff; border:1px solid var(--line); color:var(--ink2); }
  .btn:hover{ filter:brightness(.97); }

  /* Quick ranges */
  .range-pills{ display:flex; flex-wrap:wrap; gap:8px; }
  .pill{
    padding:6px 10px; border-radius:999px; border:1px solid var(--line); background:#fff;
    font-weight:700; font-size:12px; color:#0f172a; cursor:pointer;
  }
  .pill:hover{ background:#f8fafc; }
  .pill.active{ background:#eef2ff; border-color:#e0e7ff; color:#3730a3; }

  /* Grid helpers */
  .g-12{ display:grid; grid-template-columns:repeat(12,1fr); gap:14px; }
  @media (max-width: 992px){ .g-12{ grid-template-columns:repeat(6,1fr);} }
  @media (max-width: 600px){ .g-12{ grid-template-columns:repeat(1,1fr);} }
  .col-12{ grid-column:span 12; }
  .col-6{ grid-column:span 6; }
  .col-4{ grid-column:span 4; }
  .col-3{ grid-column:span 3; }

  /* Tiny validation alert */
  .tiny-alert{
    display:none; background:#fff7ed; border:1px solid #fed7aa; color:#9a3412;
    border-radius:10px; padding:8px 10px; font-weight:700; font-size:12px; margin-bottom:10px;
  }
</style>

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

      <div class="box box-success">
        <div class="box-header">
          <h3 class="box-title"><i class="fa fa-filter"></i> Security Deposit Report Form</h3>
          <div class="header-actions" style="display:flex;gap:8px;flex-wrap:wrap;">
            <button type="button" class="btn btn-soft btn-compact btn-pill" id="btnReset">
              <i class="fa fa-refresh"></i> Reset
            </button>
            <button type="button" class="btn btn-primary btn-compact btn-pill" onclick="openAllSecurity()">
              <i class="fa fa-list"></i> All Security Deposits
            </button>
          </div>
        </div>

        <div class="box-body">
          <div id="alertRange" class="tiny-alert">
            <i class="fa fa-exclamation-triangle"></i> End date cannot be before start date.
          </div>

          <div class="g-12">
            <!-- Block -->
            <div class="form-group col-6">
              <label for="bid">Select Block</label>
              <select onchange="getUnitReport(this.value)" name="bid" id="bid" class="form-control">
                <option value="">-- Select Block --</option>
                <?php
                  $result_floor = mysqli_query($link, "SELECT * FROM blocks ORDER BY bid ASC");
                  while ($row_floor = mysqli_fetch_array($result_floor)) { ?>
                    <option value="<?= $row_floor['bid']; ?>"><?= htmlspecialchars($row_floor['b_name']); ?></option>
                <?php } ?>
              </select>
              <div class="hint">Pick a block to load its units.</div>
            </div>

            <!-- Unit -->
            <div class="form-group col-6">
              <label for="ddlUnitNo"><?= $_data['text_5']; ?></label>
              <select name="ddlUnitNo" id="ddlUnitNo" class="form-control">
                <option value="">-- <?= $_data['text_5']; ?> --</option>
              </select>
            </div>

            <!-- Tenant -->
            <div class="form-group col-6">
              <label for="tid">Tenant</label>
              <select name="tid" id="tid" class="form-control">
                <option value="">-- Select Tenant --</option>
                <?php
                  $result_tenant = $link->query("SELECT * FROM tenants ORDER BY r_name ASC");
                  while ($row_tenant = mysqli_fetch_array($result_tenant)) { ?>
                    <option value="<?= $row_tenant['tid']; ?>"><?= htmlspecialchars($row_tenant['r_name']); ?></option>
                <?php } ?>
              </select>
            </div>

            <!-- Refund Status (s_status) -->
            <!-- <div class="form-group col-6">
              <label for="refundStatus">Refund Status</label>
              <select name="refundStatus" id="refundStatus" class="form-control">
                <option value="">-- All Refund Statuses --</option>
                <option value="3">Partially Refunded</option>
                <option value="2">Fully Refunded</option>
                <option value="1">Withheld</option>
              </select>
              <div class="hint">Database mapping: 3 = Partially Refunded, 2 = Fully Refunded, 1 = Withheld.</div>
            </div> -->

            <!-- Issue Date range (filters on issue_date column) -->
            <div class="form-group col-3">
              <label for="startDate">Start Date (Issue Date)</label>
              <div class="input-icon">
                <i class="fa fa-calendar"></i>
                <input type="text" name="startDate" id="startDate" class="form-control datepicker" placeholder="YYYY-MM-DD" />
              </div>
              <div class="hint">Format: YYYY-MM-DD</div>
            </div>

            <div class="form-group col-3">
              <label for="endDate">End Date (Issue Date)</label>
              <div class="input-icon">
                <i class="fa fa-calendar"></i>
                <input type="text" name="endDate" id="endDate" class="form-control datepicker" placeholder="YYYY-MM-DD" />
              </div>
              <div class="hint">Format: YYYY-MM-DD</div>
            </div>

            <!-- Quick ranges -->
            <div class="form-group col-12">
              <label style="display:block;font-weight:800;color:var(--ink);">Quick Ranges</label>
              <div class="range-pills" id="rangePills">
                <button type="button" class="pill" data-range="today">Today</button>
                <button type="button" class="pill" data-range="7">Last 7 days</button>
                <button type="button" class="pill" data-range="30">Last 30 days</button>
                <button type="button" class="pill" data-range="month">This month</button>
                <button type="button" class="pill" data-range="quarter">This quarter</button>
                <button type="button" class="pill" data-range="year">This year</button>
              </div>
            </div>
          </div>
        </div>

        <div class="box-footer">
          <div class="hint" style="margin:0;">
            Tip: leave all filters empty to view the full security deposit report.
          </div>
          <div>
            <button type="button" onclick="return getSecurityDepositReport();" class="btn btn-success btn-pill">
              <i class="fa fa-search"></i> <?= $_data['text_7']; ?>
            </button>
          </div>
        </div>
      </div>

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

<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script type="text/javascript">
  // -------- Helpers ----------
  function pad(n){ return (n<10?'0':'') + n; }
  function fmt(d){ return d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate()); }
  function startOfMonth(d){ return new Date(d.getFullYear(), d.getMonth(), 1); }
  function endOfMonth(d){ return new Date(d.getFullYear(), d.getMonth()+1, 0); }
  function startOfQuarter(d){ var m=d.getMonth(), qs=m-(m%3); return new Date(d.getFullYear(), qs, 1); }
  function endOfQuarter(d){ var m=d.getMonth(), qs=m-(m%3); return new Date(d.getFullYear(), qs+3, 0); }
  function startOfYear(d){ return new Date(d.getFullYear(), 0, 1); }
  function endOfYear(d){ return new Date(d.getFullYear(), 11, 31); }
  function isValidYMD(s){ return /^\d{4}-\d{2}-\d{2}$/.test(s); }

  // -------- Datepicker init (Flatpickr -> jQuery UI fallback) ----------
  (function initDatepickers(){
    if (window.flatpickr) {
      flatpickr(".datepicker", {
        dateFormat: "Y-m-d",
        allowInput: true,
        altInput: true,
        altFormat: "D, j M Y",
        disableMobile: false
      });
    } else if (typeof jQuery !== 'undefined' && $.fn.datepicker) {
      $('.datepicker').datepicker({ dateFormat: 'yy-mm-dd' });
    }
  })();

  // -------- Quick ranges ----------
  (function initQuickRanges(){
    var pills = document.getElementById('rangePills');
    if (!pills) return;
    pills.addEventListener('click', function(e){
      if (!e.target.classList.contains('pill')) return;
      var today = new Date();
      var range = e.target.getAttribute('data-range');
      var s, en;

      // Active state
      Array.prototype.forEach.call(pills.querySelectorAll('.pill'), function(p){ p.classList.remove('active'); });
      e.target.classList.add('active');

      if (range === 'today') {
        s = en = fmt(today);
      } else if (range === '7') {
        var d = new Date(); d.setDate(d.getDate()-6);
        s = fmt(d); en = fmt(today);
      } else if (range === '30') {
        var d2 = new Date(); d2.setDate(d2.getDate()-29);
        s = fmt(d2); en = fmt(today);
      } else if (range === 'month') {
        s = fmt(startOfMonth(today)); en = fmt(endOfMonth(today));
      } else if (range === 'quarter') {
        s = fmt(startOfQuarter(today)); en = fmt(endOfQuarter(today));
      } else if (range === 'year') {
        s = fmt(startOfYear(today)); en = fmt(endOfYear(today));
      }

      document.getElementById('startDate').value = s || '';
      document.getElementById('endDate').value = en || '';
      document.getElementById('alertRange').style.display = 'none';
    });
  })();

  // -------- Reset ----------
  (function initReset(){
    var btn = document.getElementById('btnReset');
    if (!btn) return;
    btn.addEventListener('click', function(){
      document.getElementById('bid').value = '';
      document.getElementById('ddlUnitNo').innerHTML = '<option value="">-- <?= addslashes($_data['text_5']); ?> --</option>';
      document.getElementById('tid').value = '';
      document.getElementById('refundStatus').value = '';
      document.getElementById('startDate').value = '';
      document.getElementById('endDate').value = '';
      var pills = document.getElementById('rangePills');
      if (pills){ Array.prototype.forEach.call(pills.querySelectorAll('.pill'), function(p){ p.classList.remove('active'); }); }
      var alertBox = document.getElementById('alertRange');
      if (alertBox) alertBox.style.display = 'none';
    });
  })();

  // -------- Load units for block ----------
  function getUnitReport(bid){
    if (!bid) {
      $("#ddlUnitNo").html('<option value="">--<?= $_data['text_5']; ?>--</option>');
      return;
    }
    $.ajax({
      url: "<?= WEB_URL; ?>/ajax/getunit.php",
      type: "POST",
      data: { token: "unit_by_block", bid: bid },
      success: function(html){
        if (html && typeof html === 'string'){
          $("#ddlUnitNo").html(html);
        } else {
          $("#ddlUnitNo").html('<option value="">--<?= $_data['text_5']; ?>--</option>');
        }
      },
      error: function(){
        $("#ddlUnitNo").html('<option value="">--<?= $_data['text_5']; ?>--</option>');
      }
    });
  }

  // -------- Open "All" ----------
  function openAllSecurity(){
    // df=issue_date (date field to filter on in backend)
    window.open('<?= WEB_URL; ?>report/security_deposit_info_block.php?type=all&df=issue_date', '_blank');
  }

  // -------- Build and open report ----------
  function getSecurityDepositReport() {
    var bid        = $("#bid").val() || '';
    var uid        = $("#ddlUnitNo").val() || '';
    var tid        = $("#tid").val() || '';
    var startDate  = $("#startDate").val() || '';
    var endDate    = $("#endDate").val() || '';
    var rs         = $("#refundStatus").val() || ''; // s_status filter

    // Validate dates
    if (startDate && !isValidYMD(startDate)) { alert("Start date must be in YYYY-MM-DD format."); return false; }
    if (endDate   && !isValidYMD(endDate))   { alert("End date must be in YYYY-MM-DD format.");   return false; }
    if (startDate && endDate && (new Date(startDate) > new Date(endDate))){
      $("#alertRange").fadeIn(150);
      return false;
    } else {
      $("#alertRange").hide();
    }

    // No filters -> open all
    if (!bid && !uid && !tid && !startDate && !endDate && !rs) {
      openAllSecurity();
      return false;
    }

    // Build query; df=issue_date tells backend which column to use for the date range
    var url = '<?= WEB_URL; ?>report/security_deposit_info_block.php?type=query'
      + '&bid=' + encodeURIComponent(bid)
      + '&uid=' + encodeURIComponent(uid)
      + '&tid=' + encodeURIComponent(tid)
      + '&startDate=' + encodeURIComponent(startDate)
      + '&endDate=' + encodeURIComponent(endDate)
      + '&rs=' + encodeURIComponent(rs)
      + '&df=issue_date';

    window.open(url, '_blank');
    return false;
  }
</script>

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