<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>
<?php
$primaryColor = $settings['primary_color'] ?? '#76002b';
$daysLeft     = $daysToExpiry ?? null;
$expWarning   = $daysLeft !== null && $daysLeft <= 30 && $unit['status'] === 'occupied';
$expCritical  = $daysLeft !== null && $daysLeft <= 7  && $unit['status'] === 'occupied';
?>

<div class="page-header">
  <div>
    <h1><i class="bi bi-grid me-2"></i>Unit <?= esc($unit['unit_number']) ?></h1>
    <nav aria-label="breadcrumb"><ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="<?= base_url('facilities') ?>">Facilities</a></li>
      <li class="breadcrumb-item"><a href="<?= base_url('facilities/view/'.$unit['facility_id']) ?>"><?= esc($unit['facility_name']) ?></a></li>
      <li class="breadcrumb-item"><a href="<?= base_url('facilities/'.$unit['facility_id'].'/units') ?>">Units</a></li>
      <li class="breadcrumb-item active">Unit <?= esc($unit['unit_number']) ?></li>
    </ol></nav>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <span class="fm-badge badge-status-<?= esc($unit['status']) ?> align-self-center"><?= ucfirst($unit['status']) ?></span>
    <a href="<?= base_url('units/edit/'.$unit['id']) ?>" class="btn btn-fm-outline btn-sm"><i class="bi bi-pencil me-1"></i>Edit</a>
    <?php if($unit['status']==='vacant'): ?>
    <a href="<?= base_url('units/checklist/'.$unit['id'].'/move_in') ?>" class="btn btn-fm-primary btn-sm"><i class="bi bi-box-arrow-in-right me-1"></i>Move-In</a>
    <?php elseif($unit['status']==='occupied'): ?>
    <a href="<?= base_url('units/checklist/'.$unit['id'].'/move_out') ?>" class="btn btn-sm btn-warning"><i class="bi bi-box-arrow-right me-1"></i>Move-Out</a>
    <?php endif; ?>
    <a href="<?= base_url('workorders/create?facility_id='.$unit['facility_id'].'&unit_id='.$unit['id']) ?>" class="btn btn-sm btn-outline-secondary"><i class="bi bi-tools me-1"></i>New WO</a>
  </div>
</div>

<!-- Contract Expiry Banner -->
<?php if($expCritical): ?>
<div class="alert alert-danger d-flex align-items-center gap-2 mb-3">
  <i class="bi bi-exclamation-triangle-fill fs-5"></i>
  <div><strong>Contract expiring in <?= $daysLeft ?> day<?= $daysLeft===1?'':'s' ?>!</strong> Immediate renewal action required.</div>
  <a href="<?= base_url('finance/contracts/create?unit_id='.$unit['id']) ?>" class="btn btn-sm btn-danger ms-auto">Renew Now</a>
</div>
<?php elseif($expWarning): ?>
<div class="alert alert-warning d-flex align-items-center gap-2 mb-3">
  <i class="bi bi-clock-history fs-5"></i>
  <div>Contract expires on <strong><?= date('d M Y',strtotime($unit['contract_end'])) ?></strong> (<?= $daysLeft ?> days remaining).</div>
  <a href="<?= base_url('finance/contracts/create?unit_id='.$unit['id']) ?>" class="btn btn-sm btn-warning ms-auto">Renew Contract</a>
</div>
<?php endif; ?>

<div class="row g-3">

  <!-- LEFT COLUMN -->
  <div class="col-lg-4">

    <!-- Unit Info -->
    <div class="fm-form-section mb-3">
      <h6><i class="bi bi-info-circle"></i>Unit Details</h6>
      <div class="small mb-2"><span class="text-muted">Facility:</span> <strong><?= esc($unit['facility_name']) ?></strong></div>
      <?php if($unit['floor']): ?><div class="small mb-2"><span class="text-muted">Floor:</span> <strong><?= esc($unit['floor']) ?></strong></div><?php endif; ?>
      <?php if($unit['unit_type']): ?><div class="small mb-2"><span class="text-muted">Type:</span> <?= esc(ucfirst($unit['unit_type'])) ?></div><?php endif; ?>
      <?php if($unit['area_sqft']): ?><div class="small mb-2"><span class="text-muted">Area:</span> <?= number_format($unit['area_sqft'],0) ?> sqft</div><?php endif; ?>
    </div>

    <!-- Owner Info -->
    <?php if($unit['owner_name']): ?>
    <div class="fm-form-section mb-3">
      <h6><i class="bi bi-person-badge"></i>Owner</h6>
      <div class="small mb-1 fw-semibold"><?= esc($unit['owner_name']) ?></div>
      <?php if($unit['owner_mobile']): ?><div class="small text-muted"><i class="bi bi-telephone me-1"></i><a href="tel:<?= esc($unit['owner_mobile']) ?>"><?= esc($unit['owner_mobile']) ?></a></div><?php endif; ?>
      <?php if($unit['owner_email']): ?><div class="small text-muted"><i class="bi bi-envelope me-1"></i><a href="mailto:<?= esc($unit['owner_email']) ?>"><?= esc($unit['owner_email']) ?></a></div><?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- Tenant Info -->
    <?php if($unit['status']==='occupied'): ?>
    <div class="fm-form-section mb-3" style="border-left:3px solid <?= $primaryColor ?>">
      <h6><i class="bi bi-person-check"></i>Current Tenant</h6>
      <?php if($unit['tenant_name']): ?>
      <div class="small fw-semibold mb-1"><?= esc($unit['tenant_name']) ?></div>
      <?php if($unit['tenant_mobile']): ?><div class="small text-muted mb-1"><i class="bi bi-telephone me-1"></i><a href="tel:<?= esc($unit['tenant_mobile']) ?>"><?= esc($unit['tenant_mobile']) ?></a></div><?php endif; ?>
      <?php if($unit['tenant_email']): ?><div class="small text-muted"><i class="bi bi-envelope me-1"></i><a href="mailto:<?= esc($unit['tenant_email']) ?>"><?= esc($unit['tenant_email']) ?></a></div><?php endif; ?>
      <?php else: ?><p class="small text-muted mb-0">No tenant details recorded.</p><?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- Contract Details -->
    <?php if($unit['contract_number'] || $unit['contract_start']): ?>
    <div class="fm-form-section mb-3">
      <h6><i class="bi bi-file-earmark-text"></i>Contract</h6>
      <?php if($unit['contract_number']): ?><div class="small mb-1"><span class="text-muted">Ref:</span> <strong><?= esc($unit['contract_number']) ?></strong></div><?php endif; ?>
      <?php if($unit['contract_start']): ?><div class="small mb-1"><span class="text-muted">Start:</span> <?= date('d M Y',strtotime($unit['contract_start'])) ?></div><?php endif; ?>
      <?php if($unit['contract_end']): ?>
      <div class="small mb-1 <?= $expCritical?'text-danger fw-bold':($expWarning?'text-warning':'') ?>">
        <span class="text-muted">End:</span> <?= date('d M Y',strtotime($unit['contract_end'])) ?>
        <?php if($daysLeft!==null && $daysLeft>0): ?><span class="badge bg-<?= $expCritical?'danger':($expWarning?'warning':'secondary') ?> ms-1"><?= $daysLeft ?>d</span><?php endif; ?>
      </div>
      <?php endif; ?>
      <?php if($unit['rent_amount']): ?><div class="small mb-1"><span class="text-muted">Rent:</span> <strong><?= $currency ?> <?= number_format($unit['rent_amount'],0) ?>/mo</strong></div><?php endif; ?>
      <?php if($unit['security_deposit']): ?><div class="small"><span class="text-muted">Deposit:</span> <?= $currency ?> <?= number_format($unit['security_deposit'],0) ?></div><?php endif; ?>
      <?php if(!empty($unit['contract_attachment'])): ?>
      <a href="<?= base_url('file/contracts/'.basename($unit['contract_attachment'])) ?>" target="_blank" class="btn btn-sm btn-outline-secondary mt-2 w-100"><i class="bi bi-paperclip me-1"></i>View Contract</a>
      <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- Quick Actions -->
    <div class="fm-form-section">
      <h6><i class="bi bi-lightning-charge"></i>Quick Actions</h6>
      <div class="d-grid gap-2">
        <a href="<?= base_url('workorders/create?facility_id='.$unit['facility_id'].'&unit_id='.$unit['id']) ?>" class="btn btn-fm-outline btn-sm"><i class="bi bi-tools me-2"></i>Create Work Order</a>
        <a href="<?= base_url('units/checklist/'.$unit['id'].'/routine') ?>" class="btn btn-fm-outline btn-sm"><i class="bi bi-clipboard2-check me-2"></i>Routine Inspection</a>
        <a href="<?= base_url('finance/contracts/create?unit_id='.$unit['id']) ?>" class="btn btn-fm-outline btn-sm"><i class="bi bi-file-earmark-plus me-2"></i>New Contract</a>
        <a href="<?= base_url('finance/invoices/create?unit_id='.$unit['id']) ?>" class="btn btn-fm-outline btn-sm"><i class="bi bi-receipt me-2"></i>Create Invoice</a>
      </div>
    </div>

  </div><!-- /.col-lg-4 -->

  <!-- RIGHT COLUMN -->
  <div class="col-lg-8">

    <!-- Tabs -->
    <ul class="nav nav-tabs mb-3">
      <li class="nav-item"><a class="nav-link active" href="#tab-wo"         data-bs-toggle="tab">Work Orders <span class="badge bg-secondary ms-1"><?= count($workOrders) ?></span></a></li>
      <li class="nav-item"><a class="nav-link"        href="#tab-checklists" data-bs-toggle="tab">Checklists <span class="badge bg-secondary ms-1"><?= count($checklists) ?></span></a></li>
      <li class="nav-item"><a class="nav-link"        href="#tab-finance"    data-bs-toggle="tab">Finance</a></li>
    </ul>

    <div class="tab-content">

      <!-- Work Orders Tab -->
      <div class="tab-pane fade show active" id="tab-wo">
        <div class="fm-card">
          <div class="card-header-fm">
            <h5><i class="bi bi-tools me-2"></i>Work Orders</h5>
            <a href="<?= base_url('workorders/create?facility_id='.$unit['facility_id'].'&unit_id='.$unit['id']) ?>" class="btn btn-fm-primary btn-sm"><i class="bi bi-plus me-1"></i>New</a>
          </div>
          <div class="fm-card-body p-0">
            <?php if(empty($workOrders)): ?>
            <p class="text-muted text-center py-4 small">No work orders for this unit.</p>
            <?php else: ?>
            <table class="fm-table">
              <thead><tr><th>WO #</th><th>Title</th><th>Status</th><th>Priority</th><th>Assigned</th><th>Date</th></tr></thead>
              <tbody>
              <?php foreach($workOrders as $w): ?>
              <tr>
                <td><a href="<?= base_url('workorders/view/'.$w['id']) ?>" class="fw-semibold text-primary"><?= esc($w['wo_number']) ?></a></td>
                <td class="small"><?= esc(substr($w['title'],0,35)) ?><?= strlen($w['title'])>35?'…':'' ?></td>
                <td><span class="fm-badge badge-status-<?= esc($w['status']) ?>"><?= ucfirst(str_replace('_',' ',$w['status'])) ?></span></td>
                <td><span class="fm-badge badge-priority-<?= esc($w['priority']) ?>"><?= ucfirst($w['priority']) ?></span></td>
                <td class="small text-muted"><?= esc($w['assigned_name']??'—') ?></td>
                <td class="small text-muted"><?= date('d M Y',strtotime($w['created_at'])) ?></td>
              </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <!-- Checklists Tab -->
      <div class="tab-pane fade" id="tab-checklists">
        <div class="fm-card mb-3">
          <div class="card-header-fm">
            <h5><i class="bi bi-clipboard2-check me-2"></i>Inspection Checklists</h5>
            <div class="d-flex gap-1">
              <a href="<?= base_url('units/checklist/'.$unit['id'].'/move_in') ?>"  class="btn btn-sm btn-success">Move-In</a>
              <a href="<?= base_url('units/checklist/'.$unit['id'].'/move_out') ?>" class="btn btn-sm btn-warning">Move-Out</a>
              <a href="<?= base_url('units/checklist/'.$unit['id'].'/routine') ?>"  class="btn btn-sm btn-outline-secondary">Routine</a>
            </div>
          </div>
          <div class="fm-card-body p-0">
            <?php if(empty($checklists)): ?>
            <p class="text-muted text-center py-4 small">No checklists yet.</p>
            <?php else: ?>
            <table class="fm-table">
              <thead><tr><th>Type</th><th>Status</th><th>Created By</th><th>Date</th><th></th></tr></thead>
              <tbody>
              <?php foreach($checklists as $cl): ?>
              <tr>
                <td><span class="fw-semibold small"><?= ucfirst(str_replace('_',' ',$cl['type'])) ?></span></td>
                <td><span class="fm-badge badge-status-<?= esc($cl['status']) ?>"><?= ucfirst($cl['status']) ?></span></td>
                <td class="small text-muted"><?= esc($cl['created_by_name']??'—') ?></td>
                <td class="small text-muted"><?= date('d M Y',strtotime($cl['created_at'])) ?></td>
                <td><a href="<?= base_url('units/checklist/print/'.$cl['id']) ?>" class="btn-action bg-secondary text-white" title="Print" target="_blank"><i class="bi bi-printer"></i></a></td>
              </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <!-- Finance Tab -->
      <div class="tab-pane fade" id="tab-finance">
        <div class="fm-card">
          <div class="card-header-fm">
            <h5><i class="bi bi-receipt me-2"></i>Finance Summary</h5>
            <a href="<?= base_url('finance/invoices/create?unit_id='.$unit['id']) ?>" class="btn btn-fm-primary btn-sm"><i class="bi bi-plus me-1"></i>Invoice</a>
          </div>
          <div class="fm-card-body">
            <?php if($contract): ?>
            <div class="row g-3 mb-3">
              <div class="col-4">
                <div class="fm-form-section text-center">
                  <div class="kpi-label">Monthly Rent</div>
                  <div class="fw-bold" style="font-size:1.1rem"><?= $currency ?> <?= number_format($unit['rent_amount']??0,0) ?></div>
                </div>
              </div>
              <div class="col-4">
                <div class="fm-form-section text-center">
                  <div class="kpi-label">Security Deposit</div>
                  <div class="fw-bold"><?= $currency ?> <?= number_format($unit['security_deposit']??0,0) ?></div>
                </div>
              </div>
              <div class="col-4">
                <div class="fm-form-section text-center">
                  <div class="kpi-label">Contract Status</div>
                  <span class="fm-badge badge-status-<?= esc($contract['status']) ?>"><?= ucfirst($contract['status']) ?></span>
                </div>
              </div>
            </div>
            <?php else: ?>
            <p class="text-muted small text-center py-3">No active contract. <a href="<?= base_url('finance/contracts/create?unit_id='.$unit['id']) ?>">Create one</a>.</p>
            <?php endif; ?>
          </div>
        </div>
      </div>

    </div><!-- /.tab-content -->
  </div><!-- /.col-lg-8 -->
</div>

<?= $this->endSection() ?>
