<?php
include_once('../header.php');
include_once(ROOT_PATH.'language/'.$lang_code_global.'/lang_add_fare.php');

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

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

/* ---------- Defaults ---------- */
$title          = $_data['add_new_security_deposit'];
$button_text    = $_data['save_button_text'];
$form_url       = WEB_URL . "security_deposit/addsecuritydeposit.php?action=add";

$tid = 0;            // tenant id
$uid = 0;            // unit id
$rent_rate = '';     // deposit amount
$amt_paid  = '0.00';
$issue_date = '';

$rate_currency_id = null;
$exchange_rate    = null;

/* First currency symbol (fallback for UI) */
$currency_symbol = '$';
if ($res = $link->query("SELECT symbol FROM currencies ORDER BY cid ASC LIMIT 1")) {
  if ($row = $res->fetch_assoc()) $currency_symbol = $row['symbol'] ?: $currency_symbol;
  $res->free();
}

/* ---------- Handle POST (Add / Update) ---------- */
if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $tid        = isset($_POST['tid']) ? (int)$_POST['tid'] : 0;
  $uid        = isset($_POST['uid']) ? (int)$_POST['uid'] : 0;
  $rent_rate  = isset($_POST['rent_rate']) ? (float)$_POST['rent_rate'] : 0;
  $amt_paid   = (isset($_POST['amt_paid']) && $_POST['amt_paid'] !== '') ? (float)$_POST['amt_paid'] : 0;
  $issue_date = isset($_POST['txtIssueDate']) ? trim($_POST['txtIssueDate']) : '';

  // rate_currency select packs "cid-exchange_rate"
  if (!empty($_POST['rate_currency'])) {
    $tmp = explode('-', $_POST['rate_currency'], 2);
    $rate_currency_id = isset($tmp[0]) ? (int)$tmp[0] : null;
    $exchange_rate    = isset($tmp[1]) ? (float)$tmp[1] : null;
  }

  if ($tid > 0 && $uid > 0 && $rent_rate >= 0 && $issue_date !== '' && $rate_currency_id !== null && $exchange_rate !== null) {
    mysqli_begin_transaction($link);
    $ok = true;

    if (isset($_GET["action"]) && $_GET["action"] === "add") {
      $stmt = $link->prepare("
        INSERT INTO security_deposit
          (uid, tid, rate, rate_currency_id, currency_exchange_rate, amt_paid, issue_date, added_by)
        VALUES (?,?,?,?,?,?,?,?)
      ");
      $added_by = (int)$_SESSION['user_id'];
      $stmt->bind_param('iididdsi', $uid, $tid, $rent_rate, $rate_currency_id, $exchange_rate, $amt_paid, $issue_date, $added_by);
      $ok = $ok && $stmt->execute();
      $new_id = $stmt->insert_id ?? 0;
      $stmt->close();

      if ($ok && $amt_paid > 0) {
        $stmt2 = $link->prepare("
          INSERT INTO security_deposit_payment_updates (security_deposit_id, amount, added_by)
          VALUES (?,?,?)
        ");
        $stmt2->bind_param('idi', $new_id, $amt_paid, $added_by);
        $ok = $ok && $stmt2->execute();
        $stmt2->close();
      }

    } elseif (isset($_GET["action"]) && $_GET["action"] === "update" && isset($_GET["id"]) && is_numeric($_GET["id"])) {
      $id = (int)$_GET['id'];
      $stmt = $link->prepare("
        UPDATE security_deposit
           SET uid=?, tid=?, rate=?, rate_currency_id=?, currency_exchange_rate=?, amt_paid=?, issue_date=?
         WHERE id=?
      ");
      $stmt->bind_param('iididdsi', $uid, $tid, $rent_rate, $rate_currency_id, $exchange_rate, $amt_paid, $issue_date, $id);
      $ok = $ok && $stmt->execute();
      $stmt->close();
    } else {
      $ok = false;
    }

    if ($ok) {
      mysqli_commit($link);
      $_SESSION["message"] = (isset($_GET['action']) && $_GET['action'] === 'update')
        ? $_data['update_security_deposit_successfully']
        : $_data['added_security_deposit_successfully'];
      header("Location: " . WEB_URL . 'security_deposit/security_deposit_list.php');
      exit;
    } else {
      mysqli_rollback($link);
      $_SESSION["message"] = "Operation failed. Please try again.";
      header("Location: " . WEB_URL . 'security_deposit/security_deposit_list.php');
      exit;
    }
  } else {
    $_SESSION["message"] = "Please complete all required fields correctly.";
  }
}

/* ---------- Edit mode (prefill) ---------- */
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
  $id = (int)$_GET['id'];
  if ($res = $link->query("SELECT * FROM security_deposit WHERE id={$id} LIMIT 1")) {
    if ($row = $res->fetch_assoc()) {
      $tid              = (int)$row['tid'];
      $uid              = (int)$row['uid'];
      $rent_rate        = (float)$row['rate'];
      $amt_paid         = (string)(float)$row['amt_paid'];
      $issue_date       = $row['issue_date'];
      $rate_currency_id = (int)$row['rate_currency_id'];
      $exchange_rate    = (float)$row['currency_exchange_rate'];

      $title       = $_data['update_security_deposit'];
      $button_text = $_data['update_button_text'];
      $form_url    = WEB_URL . "security_deposit/addsecuritydeposit.php?action=update&id=".$id;
    }
    $res->free();
  }
}
?>

<!-- Header -->
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;margin-bottom:8px;">
    <span style="display:inline-flex;width:38px;height:38px;border-radius:12px;background:#2563eb1a;align-items:center;justify-content:center;">
      <i class="fa fa-shield" style="color:#1e40af;"></i>
    </span>
    <span><?= e($title); ?></span>
  </h1>
  <ol class="breadcrumb">
    <li><a href="<?= WEB_URL?>dashboard.php"><i class="fa fa-dashboard"></i> <?= e($_data['home_breadcam']);?></a></li>
    <li class="active"><?= e($_data['add_new_security_deposit_information_breadcam']);?></li>
    <li class="active"><?= e($title); ?></li>
  </ol>
</section>

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

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

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

  .section-title{
    margin:0 0 12px; display:flex; align-items:center; gap:8px; font-weight:800; color:var(--ink);
  }
  .section-title i{ color:var(--brand2); }

  .form-control{
    height:42px; border-radius:12px; border:1px solid var(--line); box-shadow:none !important;
  }
  .form-control:focus{ border-color:#93c5fd; box-shadow:0 0 0 3px rgba(59,130,246,.15); }
  select.form-control{ height:42px; }

  .input-group .input-group-addon{
    background:#fff; border:1px solid var(--line); border-right:none; border-radius:12px 0 0 12px;
  }
  .input-group > .form-control{ border-left:none; border-radius:0 12px 12px 0; }

  .help-note{ font-size:12px; color:var(--muted); margin-top:6px; }

  .btn{ border-radius:12px; font-weight:700; }
  .btn-success{ background:var(--ok); border-color:var(--ok); color:#fff; }
  .btn-warning{ background:#f59e0b; border-color:#f59e0b; color:#fff; }
  .btn-default{ background:#eef2ff; border-color:#e5e7eb; color:#111827; }
  .btn:hover{ filter:brightness(.98); }

  .pill{
    display:inline-flex; align-items:center; gap:8px; padding:6px 10px; border-radius:999px;
    background:#f3f4f6; color:#111827; font-size:12px; font-weight:700; border:1px solid var(--line);
  }
  .pill i{ color:#6b7280; }

  .errorStar{ color:var(--danger); font-weight:800; }

  /* small tweaks */
  .switch{ margin-left:8px; }
</style>

<section class="content">
  <div class="box box-success">
    <div class="box-header">
      <h3 class="box-title"><i class="fa fa-list-ul"></i> <?= e($_data['add_new_security_deposit_entry_form']);?></h3>
      <div class="help-note">Complete the fields below. You can change currency & amount as needed.</div>
    </div>

    <div class="box-body">
      <div class="grid">
        <!-- LEFT: Form -->
        <div class="card">
          <h4 class="section-title"><i class="fa fa-user-circle"></i> Tenant & Unit</h4>
          <form id="addSecurityDepositForm" action="<?= e($form_url); ?>" method="post" enctype="multipart/form-data" novalidate>
            <div class="row">
              <!-- Tenant -->
              <div class="form-group col-md-6">
                <label for="tid"><span class="errorStar">*</span> Tenant</label>
                <select required name="tid" id="tid" class="form-control"
                        onchange="getTenantUnit('tid','uid','rent_rate','yearly_rate'); updateSummary();">
                  <option value="">-- Select Tenant --</option>
                  <?php
                    $result_tenant = $link->query("SELECT tid, r_name FROM current_tenants_view ORDER BY r_name ASC");
                    while ($row_tenant = mysqli_fetch_assoc($result_tenant)) {
                      $sel = ($tid == (int)$row_tenant['tid']) ? 'selected' : '';
                      echo '<option value="'.(int)$row_tenant['tid'].'" '.$sel.'>'.e($row_tenant['r_name']).'</option>';
                    }
                    if ($result_tenant) $result_tenant->free();
                  ?>
                </select>
                <div class="help-note">Selecting a tenant will list their unit(s).</div>
              </div>

              <!-- Unit -->
              <div class="form-group col-md-6">
                <label for="uid"><span class="errorStar">*</span> <?= e($_data['add_new_form_field_text_3']);?></label>
                <input type="hidden" id="uid_edit" value="<?= (int)$uid; ?>" />
                <select required name="uid" id="uid" class="form-control" onchange="updateSummary();">
                  <option value="">-- <?= e($_data['add_new_form_field_text_4']);?> --</option>
                  <!-- Populated by JS getTenantUnit(...) -->
                </select>
              </div>
            </div>

            <hr>

            <h4 class="section-title"><i class="fa fa-money"></i> Deposit Details</h4>

            <div class="row">
              <!-- Deposit Amount + Currency -->
              <div class="form-group col-md-6">
                <label for="rent_rate"><span class="errorStar">*</span> Security Deposit Amount</label>
                <div class="input-group">
                  <div class="input-group-addon" style="padding:0;">
                    <select class="form-control" name="rate_currency" id="rate_currency" required
                            style="width:4.4em;border:none;"
                            onchange="updateAmtSymbols(); updateSummary();">
                      <?php
                        $selected_value = ($rate_currency_id !== null && $exchange_rate !== null)
                          ? ($rate_currency_id . '-' . $exchange_rate)
                          : null;

                        $result_currencies = $link->query("SELECT cid, symbol, exchange_rate FROM currencies ORDER BY cid ASC");
                        while ($row_c = mysqli_fetch_assoc($result_currencies)) {
                          $val = $row_c['cid'].'-'.$row_c['exchange_rate'];
                          $sel = ($selected_value !== null && $selected_value == $val) ? 'selected' : '';
                          echo '<option value="'.e($val).'" data-symbol="'.e($row_c['symbol']).'" '.$sel.'>'.e($row_c['symbol']).'</option>';
                        }
                        if ($result_currencies) $result_currencies->free();
                      ?>
                    </select>
                  </div>
                  <input type="number" min="0" step="0.01" name="rent_rate" id="rent_rate" class="form-control"
                         value="<?= e($rent_rate); ?>" required placeholder="0.00" oninput="updateSummary();">
                  <label class="switch" data-toggle="tooltip" data-placement="top" title="Enable to manually edit the amount if locked by defaults">
                    <input type="checkbox" id="set_rate" onchange="return setRateManually('rent_rate','rate_currency');">
                    <span class="slider"></span>
                  </label>
                </div>
                <div class="help-note">Choose currency and enter the deposit amount.</div>
              </div>

              <!-- Amount Paid -->
              <div class="form-group col-md-6">
                <label for="amt_paid">Amount Paid (optional)</label>
                <div class="input-group">
                  <div class="input-group-addon" id="amtPaidSymbol" data-default="<?= e($currency_symbol); ?>"><?= e($currency_symbol); ?></div>
                  <input type="number" step="0.01" min="0" name="amt_paid" id="amt_paid"
                         class="form-control" value="<?= e($amt_paid); ?>" placeholder="0.00" oninput="updateSummary();">
                </div>
                <div class="help-note">Upfront payment received with the deposit (if any).</div>
              </div>

              <!-- Issue Date -->
              <div class="form-group col-md-6">
                <label for="txtIssueDate"><span class="errorStar">*</span> <?= e($_data['add_new_form_field_text_15']);?></label>
                <div class="input-group">
                  <div class="input-group-addon"><i class="fa fa-calendar-o"></i></div>
                  <input type="text" name="txtIssueDate" id="txtIssueDate" class="form-control datepicker"
                         value="<?= e($issue_date); ?>" required placeholder="YYYY-MM-DD" oninput="updateSummary();">
                </div>
              </div>
            </div>

            <div class="text-right" style="margin-top:4px;">
              <button type="submit" name="btnSavePrint" class="btn btn-default">
                <i class="fa fa-file-text-o"></i> <?= e($_data['save_and_invoice']);?>
              </button>
              <button type="submit" name="btnSave" class="btn btn-success">
                <i class="fa fa-floppy-o"></i> <?= e($button_text); ?>
              </button>
              <a class="btn btn-warning" href="<?= WEB_URL; ?>security_deposit/security_deposit_list.php">
                <i class="fa fa-reply"></i> <?= e($_data['back_text']);?>
              </a>
            </div>
          </form>
        </div>

        <!-- RIGHT: Live Summary -->
        <aside class="card sticky">
          <h4 class="section-title"><i class="fa fa-info-circle"></i> Summary</h4>
          <div style="display:grid; gap:10px;">
            <div class="pill"><i class="fa fa-user"></i> <span id="sum_tenant">Tenant: —</span></div>
            <div class="pill"><i class="fa fa-building-o"></i> <span id="sum_unit">Unit: —</span></div>
            <div class="pill"><i class="fa fa-money"></i> <span id="sum_amount">Deposit: —</span></div>
            <div class="pill"><i class="fa fa-credit-card"></i> <span id="sum_paid">Paid: —</span></div>
            <div class="pill"><i class="fa fa-calendar"></i> <span id="sum_date">Issue Date: —</span></div>
          </div>
          <div class="help-note" style="margin-top:10px;">This panel updates as you fill the form.</div>
        </aside>
      </div>
    </div>
  </div>
</section>

<!-- Minor tweaks -->
<style>
  #rate_currency{ border:none; }
</style>

<script>
  // Tooltips
  $(function(){ if ($.fn.tooltip) $('[data-toggle="tooltip"]').tooltip(); });

  // Fallback helpers to avoid JS errors if your global helpers aren’t loaded
  if (typeof setRateManually !== 'function') {
    window.setRateManually = function(inputId){
      var cb  = document.getElementById('set_rate');
      var inp = document.getElementById(inputId);
      if (inp && cb) inp.readOnly = !cb.checked;
      return true;
    };
  }
  if (typeof getTenantUnit !== 'function') {
    // Lightweight placeholder; replace with your actual AJAX implementation
    window.getTenantUnit = function(tidId, uidId){
      var uidEdit = document.getElementById('uid_edit') ? document.getElementById('uid_edit').value : '';
      var sel = document.getElementById(uidId);
      if (!sel) return;
      sel.innerHTML = '<option value="">-- Loading --</option>';
      setTimeout(function(){
        sel.innerHTML = '<option value="">-- Select Unit --</option>';
        if (uidEdit) {
          var opt = document.createElement('option');
          opt.value = uidEdit; opt.textContent = 'Unit #' + uidEdit; opt.selected = true;
          sel.appendChild(opt);
        }
        updateSummary();
      }, 120);
    };
  }

  // Update currency symbols where needed
  function currentSymbol(){
    var sel = document.getElementById('rate_currency');
    var opt = sel ? sel.options[sel.selectedIndex] : null;
    return opt ? (opt.getAttribute('data-symbol') || '<?= addslashes($currency_symbol); ?>') : '<?= addslashes($currency_symbol); ?>';
  }
  function updateAmtSymbols(){
    var box = document.getElementById('amtPaidSymbol');
    if (box) box.textContent = currentSymbol();
  }

  // Summary logic
  const S = {
    tenant: document.getElementById('sum_tenant'),
    unit:   document.getElementById('sum_unit'),
    amount: document.getElementById('sum_amount'),
    paid:   document.getElementById('sum_paid'),
    date:   document.getElementById('sum_date')
  };
  function textOfSelect(sel){
    if (!sel) return '—';
    const opt = sel.options[sel.selectedIndex];
    return opt ? opt.textContent.trim() : '—';
  }
  function updateSummary(){
    const sym = currentSymbol();
    const tenantSel = document.getElementById('tid');
    const unitSel   = document.getElementById('uid');

    const rate = parseFloat(document.getElementById('rent_rate').value) || 0;
    const paid = parseFloat(document.getElementById('amt_paid').value) || 0;
    const date = document.getElementById('txtIssueDate').value || '—';

    S.tenant.textContent = 'Tenant: ' + textOfSelect(tenantSel);
    S.unit.textContent   = 'Unit: '   + textOfSelect(unitSel);
    S.amount.textContent = 'Deposit: ' + sym + ' ' + rate.toFixed(2);
    S.paid.textContent   = 'Paid: '    + sym + ' ' + paid.toFixed(2);
    S.date.textContent   = 'Issue Date: ' + date;
  }

  document.addEventListener('DOMContentLoaded', function(){
    // Reflect initial currency
    updateAmtSymbols();
    updateSummary();

    // Update symbol on currency change
    var rc = document.getElementById('rate_currency');
    if (rc) rc.addEventListener('change', function(){ updateAmtSymbols(); updateSummary(); });

    // If editing & tenant already selected, populate unit list
    var tidSel = document.getElementById('tid');
    if (tidSel && tidSel.value) {
      getTenantUnit('tid','uid','rent_rate','yearly_rate');
    }
  });

  // Keep summary in sync
  ['rent_rate','amt_paid','txtIssueDate'].forEach(function(id){
    var el = document.getElementById(id);
    if (el) el.addEventListener('input', updateSummary);
  });
  ['tid','uid'].forEach(function(id){
    var el = document.getElementById(id);
    if (el) el.addEventListener('change', updateSummary);
  });
</script>

<script src="<?= WEB_URL; ?>assets/js/addsecuritydeposit.js"></script>
<?php include_once('../footer.php'); ?>
