<?php use App\Helpers\Helper; $isEdit = isset($lease) && $lease; ?>
<div class="d-flex justify-content-between align-items-center mb-4">
  <h1 class="admin-page-title"><?= $isEdit ? 'Edit Lease' : 'New Lease Agreement' ?></h1>
  <a href="<?= APP_URL ?>/admin/leases" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>Back</a>
</div>
<form method="POST" action="<?= $isEdit ? APP_URL.'/admin/leases/'.$lease['id'] : APP_URL.'/admin/leases' ?>">
  <?= Helper::csrf() ?>
  <div class="row g-4">
    <div class="col-lg-8">
      <div class="form-card mb-4">
        <div class="form-section-title">Parties</div>
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">Tenant *</label>
            <select name="tenant_id" class="form-select" required <?= $isEdit?'disabled':'' ?>>
              <option value="">Select Tenant</option>
              <?php foreach ($tenants as $t): ?>
              <option value="<?= $t['id'] ?>" <?= ($isEdit && $lease['tenant_id']==$t['id'])?'selected':'' ?>><?= Helper::e($t['name']) ?></option>
              <?php endforeach; ?>
            </select>
            <?php if ($isEdit): ?><input type="hidden" name="tenant_id" value="<?= $lease['tenant_id'] ?>"><?php endif; ?>
          </div>
          <div class="col-md-6">
            <label class="form-label">Unit *</label>
            <select name="unit_id" class="form-select" required id="unitSelect" <?= $isEdit?'disabled':'' ?>>
              <option value="">Select Unit</option>
              <?php foreach ($units as $u): ?>
              <option value="<?= $u['id'] ?>" data-rent="<?= $u['monthly_rent'] ?>" data-deposit="<?= $u['security_deposit'] ?>" <?= ($isEdit && $lease['unit_id']==$u['id'])?'selected':'' ?>><?= Helper::e($u['name']) ?></option>
              <?php endforeach; ?>
            </select>
            <?php if ($isEdit): ?><input type="hidden" name="unit_id" value="<?= $lease['unit_id'] ?>"><?php endif; ?>
          </div>
          <div class="col-md-6">
            <label class="form-label">Property *</label>
            <select name="property_id" class="form-select" required>
              <?php foreach ($properties as $p): ?>
              <option value="<?= $p['id'] ?>" <?= ($isEdit && $lease['property_id']==$p['id'])?'selected':'' ?>><?= Helper::e($p['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
      </div>
      <div class="form-card mb-4">
        <div class="form-section-title">Lease Period</div>
        <div class="row g-3">
          <div class="col-md-4"><label class="form-label">Start Date *</label><input type="date" name="start_date" class="form-control" required value="<?= $lease['start_date']??date('Y-m-d') ?>"></div>
          <div class="col-md-4"><label class="form-label">End Date *</label><input type="date" name="end_date" class="form-control" required value="<?= $lease['end_date']??date('Y-m-d',strtotime('+1 year')) ?>"></div>
          <div class="col-md-4">
            <label class="form-label">Payment Frequency</label>
            <select name="payment_frequency" id="paymentFrequency" class="form-select" onchange="updateRentLabel()">
              <?php foreach (['daily'=>'Daily','weekly'=>'Weekly','monthly'=>'Monthly','quarterly'=>'Quarterly','semi_annual'=>'Semi-Annual','annual'=>'Annual'] as $v=>$l): ?>
              <option value="<?= $v ?>" <?= ($lease['payment_frequency']??'monthly')===$v?'selected':'' ?>><?= $l ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
      </div>
      <div class="form-card mb-4">
        <div class="form-section-title">Financial Terms</div>
        <div class="row g-3">
          <div class="col-md-4"><label class="form-label" id="rentLabel">Monthly Rent (TZS) *</label><input type="number" name="monthly_rent" class="form-control" id="monthlyRentInput" required value="<?= $lease['monthly_rent']??0 ?>" min="0"></div>
          <div class="col-md-4"><label class="form-label">Security Deposit (TZS)</label><input type="number" name="security_deposit" class="form-control" id="depositInput" value="<?= $lease['security_deposit']??0 ?>" min="0"></div>
          <div class="col-md-4"><label class="form-label">Advance Payment (TZS)</label><input type="number" name="advance_payment" class="form-control" value="<?= $lease['advance_payment']??0 ?>" min="0"></div>
          <div class="col-md-3"><label class="form-label">Due Day (of month)</label><input type="number" name="payment_due_day" class="form-control" value="<?= $lease['payment_due_day']??1 ?>" min="1" max="28"></div>
          <div class="col-md-3"><label class="form-label">Grace Period (days)</label><input type="number" name="grace_period_days" class="form-control" value="<?= $lease['grace_period_days']??7 ?>" min="0"></div>
          <div class="col-md-3"><label class="form-label">Late Fee (%)</label><input type="number" name="late_fee_percent" class="form-control" value="<?= $lease['late_fee_percent']??0 ?>" min="0" max="50" step="0.1"></div>
          <div class="col-md-3"><label class="form-label">Discount (TZS)</label><input type="number" name="discount_amount" class="form-control" value="<?= $lease['discount_amount']??0 ?>" min="0"></div>
          <div class="col-md-4">
            <div class="form-check mt-2">
              <input class="form-check-input" type="checkbox" name="vat_applicable" id="vatChk" <?= ($lease['vat_applicable']??0)?'checked':'' ?>>
              <label class="form-check-label" for="vatChk">Apply VAT (18%)</label>
            </div>
          </div>
          <div class="col-md-4">
            <div class="form-check mt-2">
              <input class="form-check-input" type="checkbox" name="utilities_included" <?= ($lease['utilities_included']??0)?'checked':'' ?>>
              <label class="form-check-label">Utilities Included</label>
            </div>
          </div>
          <div class="col-md-4">
            <div class="form-check mt-2">
              <input class="form-check-input" type="checkbox" name="auto_renew" <?= ($lease['auto_renew']??0)?'checked':'' ?>>
              <label class="form-check-label">Auto-Renew</label>
            </div>
          </div>
        </div>
      </div>
      <div class="form-card">
        <div class="form-section-title">Terms & Conditions</div>
        <textarea name="terms_conditions" class="form-control" rows="5" placeholder="Enter lease terms and conditions..."><?= Helper::e($lease['terms_conditions']??'') ?></textarea>
      </div>
    </div>
    <div class="col-lg-4">
      <div class="form-card mb-4">
        <div class="form-section-title">Status</div>
        <select name="status" class="form-select">
          <?php foreach (['pending','active','expired','terminated'] as $s): ?>
          <option value="<?= $s ?>" <?= ($lease['status']??'pending')===$s?'selected':'' ?>><?= ucfirst($s) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-card">
        <div class="form-section-title">Summary</div>
        <div class="small">
          <div class="d-flex justify-content-between mb-2"><span class="text-muted" id="sumRentLabel">Monthly Rent:</span><span class="fw-600" id="sumRent">TZS 0</span></div>
          <div class="d-flex justify-content-between mb-2"><span class="text-muted">Security Deposit:</span><span class="fw-600" id="sumDeposit">TZS 0</span></div>
          <hr>
          <div class="d-flex justify-content-between"><span class="fw-700">Total Due on Move-in:</span><span class="fw-800 text-primary" id="sumTotal">TZS 0</span></div>
        </div>
        <button type="submit" class="btn btn-primary w-100 mt-4"><i class="bi bi-save me-2"></i><?= $isEdit?'Update Lease':'Create Lease' ?></button>
      </div>
    </div>
  </div>
</form>
<script>
function fmt(n){return 'TZS '+Number(n).toLocaleString();}
function updateRentLabel(){
  var freq=document.getElementById('paymentFrequency').value;
  var labels={'daily':'Daily Rent (TZS) *','weekly':'Weekly Rent (TZS) *','monthly':'Monthly Rent (TZS) *','quarterly':'Quarterly Rent (TZS) *','semi_annual':'Semi-Annual Rent (TZS) *','annual':'Annual Rent (TZS) *'};
  var sumLabels={'daily':'Daily Rent:','weekly':'Weekly Rent:','monthly':'Monthly Rent:','quarterly':'Quarterly Rent:','semi_annual':'Semi-Annual Rent:','annual':'Annual Rent:'};
  document.getElementById('rentLabel').textContent=labels[freq]||'Rent (TZS) *';
  document.getElementById('sumRentLabel').textContent=sumLabels[freq]||'Rent:';
}
function updateSummary(){
  var r=(+document.getElementById('monthlyRentInput').value)||0;
  var d=(+document.getElementById('depositInput').value)||0;
  document.getElementById('sumRent').textContent=fmt(r);
  document.getElementById('sumDeposit').textContent=fmt(d);
  document.getElementById('sumTotal').textContent=fmt(r+d);
}
document.getElementById('monthlyRentInput').addEventListener('input',updateSummary);
document.getElementById('depositInput').addEventListener('input',updateSummary);
document.getElementById('unitSelect')&&document.getElementById('unitSelect').addEventListener('change',function(){
  var opt=this.options[this.selectedIndex];
  if(opt){document.getElementById('monthlyRentInput').value=opt.dataset.rent||0;document.getElementById('depositInput').value=opt.dataset.deposit||0;updateSummary();}
});
updateSummary();
updateRentLabel();
</script>
