<?php use App\Helpers\Helper; ?>
<section class="page-header">
  <div class="container">
    <h1 class="fw-700 mb-2">Book Unit <?= Helper::e($unit['unit_number']) ?></h1>
    <nav aria-label="breadcrumb"><ol class="breadcrumb mb-0"><li class="breadcrumb-item"><a href="<?= APP_URL ?>/">Home</a></li><li class="breadcrumb-item"><a href="<?= APP_URL ?>/residences/<?= $unit['property_id'] ?>">Property</a></li><li class="breadcrumb-item active">Book</li></ol></nav>
  </div>
</section>
<section class="py-5">
  <div class="container">
    <div class="row g-5 justify-content-center">
      <div class="col-lg-7">
        <div class="card border-0 shadow-sm p-4">
          <h4 class="fw-700 mb-4">Your Information</h4>
          <form method="POST" action="<?= APP_URL ?>/book" enctype="multipart/form-data">
            <?= Helper::csrf() ?>
            <input type="hidden" name="unit_id" value="<?= $unit['id'] ?>">
            <input type="hidden" name="property_id" value="<?= $unit['property_id'] ?>">
            <div class="row g-3">
              <?php $fullName = isset($user) ? trim(($user['first_name']??'').' '.($user['last_name']??'')) : ''; ?>
              <div class="col-md-12"><label class="form-label">Full Name *</label><input type="text" name="visitor_name" class="form-control" required placeholder="John Doe" value="<?= Helper::e($fullName) ?>"></div>
              <div class="col-md-6"><label class="form-label">Phone Number *</label><input type="tel" name="visitor_phone" class="form-control" required placeholder="+255 7XX XXX XXX" value="<?= Helper::e($user['phone'] ?? '') ?>"></div>
              <div class="col-md-6"><label class="form-label">Email Address</label><input type="email" name="visitor_email" class="form-control" placeholder="john@example.com" value="<?= Helper::e($user['email'] ?? '') ?>"></div>
              <div class="col-md-6"><label class="form-label">Desired Move-in Date *</label><input type="date" name="desired_move_in" id="moveInDate" class="form-control" required min="<?= date('Y-m-d') ?>"></div>
              <div class="col-md-6">
                <label class="form-label fw-600">Lease Duration *</label>
                <div class="input-group">
                  <input type="number" name="desired_lease_period" id="leasePeriod" class="form-control" value="1" min="1" max="999" required>
                  <select name="lease_period_unit" id="leasePeriodUnit" class="form-select" style="max-width:110px">
                    <option value="day">Day(s)</option>
                    <option value="week">Week(s)</option>
                    <option value="month" selected>Month(s)</option>
                  </select>
                </div>
                <div class="form-text" id="durationHint">e.g. 1 month, 2 weeks, 5 days</div>
              </div>
              <!-- Move-out estimate -->
              <div class="col-md-6">
                <label class="form-label">Estimated Move-out Date</label>
                <input type="text" id="moveOutEstimate" class="form-control bg-light" readonly placeholder="Auto-calculated">
              </div>
              <div class="col-md-6">
                <label class="form-label">Estimated Total Rent</label>
                <input type="text" id="totalRentEstimate" class="form-control bg-light fw-700 text-primary" readonly placeholder="Auto-calculated">
              </div>
              <div class="col-12"><label class="form-label">ID Document (optional)</label><input type="file" name="visitor_id_document" class="form-control" accept="image/*,.pdf"><div class="form-text">National ID, Passport, or Driver's License</div></div>
              <div class="col-12"><label class="form-label">Additional Notes</label><textarea name="notes" class="form-control" rows="3" placeholder="Any questions or special requirements..."></textarea></div>
            </div>
            <div class="form-check mt-3 mb-4">
              <input class="form-check-input" type="checkbox" id="termsCheck" required>
              <label class="form-check-label small" for="termsCheck">I agree to the <a href="#">terms and conditions</a> and booking policy</label>
            </div>
            <button type="submit" class="btn btn-primary w-100 py-3 fw-600"><i class="bi bi-calendar-check me-2"></i>Submit Booking Request</button>
          </form>
        </div>
      </div>
      <div class="col-lg-4">
        <div class="card border-0 bg-primary text-white shadow-sm sticky-top" style="top:80px">
          <div class="card-body p-4">
            <h6 class="fw-700 mb-3 opacity-75">BOOKING SUMMARY</h6>
            <h4 class="fw-800 mb-1">Unit <?= Helper::e($unit['unit_number']) ?></h4>
            <p class="opacity-75 small mb-3"><?= Helper::e($unit['property_name']) ?>, <?= Helper::e($unit['building_name']??'') ?></p>
            <div class="bg-white bg-opacity-10 rounded-3 p-3 mb-3">
              <div class="d-flex justify-content-between mb-2"><span class="small opacity-75">Type</span><span class="fw-600"><?= ucfirst($unit['unit_type']) ?></span></div>
              <div class="d-flex justify-content-between mb-2"><span class="small opacity-75">Bedrooms</span><span class="fw-600"><?= $unit['bedrooms'] ?></span></div>
              <div class="d-flex justify-content-between mb-2"><span class="small opacity-75">Bathrooms</span><span class="fw-600"><?= $unit['bathrooms'] ?></span></div>
              <?php if ($unit['floor_size']): ?><div class="d-flex justify-content-between mb-2"><span class="small opacity-75">Floor Area</span><span class="fw-600"><?= $unit['floor_size'] ?>m²</span></div><?php endif; ?>
              <div class="d-flex justify-content-between"><span class="small opacity-75">Monthly Rent</span><span class="fw-800 fs-5"><?= Helper::money($unit['monthly_rent']) ?></span></div>
              <div class="d-flex justify-content-between mt-2 pt-2 border-top border-white border-opacity-25">
                <span class="small opacity-75">Duration</span>
                <span class="fw-600" id="summaryDuration">—</span>
              </div>
              <div class="d-flex justify-content-between">
                <span class="small opacity-75">Est. Total</span>
                <span class="fw-800 text-warning" id="summaryTotal">—</span>
              </div>
            </div>
            <div class="d-flex gap-2 flex-wrap small mb-1">
              <?php if ($unit['is_furnished']): ?><span class="badge bg-white text-primary">Furnished</span><?php endif; ?>
              <?php if ($unit['has_parking']): ?><span class="badge bg-white text-primary">Parking</span><?php endif; ?>
              <?php if ($unit['has_wifi']): ?><span class="badge bg-white text-primary">WiFi</span><?php endif; ?>
            </div>
            <p class="small opacity-75 mt-3 mb-0"><i class="bi bi-info-circle me-1"></i>After submitting, you will receive payment instructions to confirm your booking via mobile money, bank transfer, or cash.</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<script>
(function() {
  const monthlyRent = <?= (float)$unit['monthly_rent'] ?>;
  const dailyRent   = monthlyRent / 30;
  const weeklyRent  = monthlyRent / 4;

  const currency = '<?= defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'TZS' ?>';

  function formatMoney(amount) {
    return currency + ' ' + Number(amount.toFixed(0)).toLocaleString();
  }

  function calcDays(period, unit) {
    if (unit === 'day')   return period;
    if (unit === 'week')  return period * 7;
    if (unit === 'month') return period * 30;
    return 0;
  }

  function addDays(dateStr, days) {
    if (!dateStr) return null;
    const d = new Date(dateStr);
    d.setDate(d.getDate() + days);
    return d.toLocaleDateString('en-GB', {day:'2-digit', month:'short', year:'numeric'});
  }

  function update() {
    const period   = parseInt(document.getElementById('leasePeriod').value) || 0;
    const unitVal  = document.getElementById('leasePeriodUnit').value;
    const moveIn   = document.getElementById('moveInDate').value;

    // Hint text
    const hints = {day:'e.g. 5 days short stay', week:'e.g. 2 weeks temporary stay', month:'e.g. 12 months annual lease'};
    document.getElementById('durationHint').textContent = hints[unitVal] || '';

    if (!period) return;

    // Total rent
    let total = 0;
    if (unitVal === 'day')   total = dailyRent  * period;
    if (unitVal === 'week')  total = weeklyRent * period;
    if (unitVal === 'month') total = monthlyRent * period;

    // Move-out estimate
    const days = calcDays(period, unitVal);
    const moveOut = moveIn ? addDays(moveIn, days) : null;

    // Update form fields
    document.getElementById('moveOutEstimate').value  = moveOut || '—';
    document.getElementById('totalRentEstimate').value = formatMoney(total);

    // Update sidebar
    const label = period + ' ' + unitVal + (period > 1 ? 's' : '');
    document.getElementById('summaryDuration').textContent = label;
    document.getElementById('summaryTotal').textContent    = formatMoney(total);
  }

  document.getElementById('leasePeriod').addEventListener('input', update);
  document.getElementById('leasePeriodUnit').addEventListener('change', update);
  document.getElementById('moveInDate').addEventListener('change', update);

  update(); // run on load
})();
</script>
