<?php use App\Helpers\Helper; ?>

<!-- Page Title -->
<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="admin-page-title mb-1">Dashboard</h1>
    <p class="text-muted small mb-0">Welcome back, <?= htmlspecialchars($_SESSION['user_name'] ?? '') ?>! Here's what's happening today.</p>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= APP_URL ?>/admin/payments/create" class="btn btn-sm btn-primary"><i class="bi bi-plus me-1"></i>Record Payment</a>
    <a href="<?= APP_URL ?>/admin/bookings" class="btn btn-sm btn-outline-primary"><i class="bi bi-calendar-check me-1"></i>Bookings</a>
  </div>
</div>

<!-- Stat Cards Row 1 -->
<div class="row g-3 mb-4">
  <div class="col-xl-3 col-md-6">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap blue"><i class="bi bi-buildings"></i></div>
      <div>
        <div class="stat-val"><?= number_format($stats['total_properties']) ?></div>
        <div class="stat-lbl">Total Properties</div>
        <div class="stat-trend text-success"><i class="bi bi-arrow-up-short"></i> Active</div>
      </div>
    </div>
  </div>
  <div class="col-xl-3 col-md-6">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap green"><i class="bi bi-people"></i></div>
      <div>
        <div class="stat-val"><?= number_format($stats['total_tenants']) ?></div>
        <div class="stat-lbl">Active Tenants</div>
        <div class="stat-trend text-success"><i class="bi bi-arrow-up-short"></i> This month</div>
      </div>
    </div>
  </div>
  <div class="col-xl-3 col-md-6">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap orange"><i class="bi bi-door-open"></i></div>
      <div>
        <div class="stat-val"><?= number_format($stats['available_units']) ?></div>
        <div class="stat-lbl">Available Units</div>
        <div class="stat-trend text-muted"><?= $stats['total_units'] ?> total units</div>
      </div>
    </div>
  </div>
  <div class="col-xl-3 col-md-6">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap purple"><i class="bi bi-cash-stack"></i></div>
      <div>
        <div class="stat-val" style="font-size:1.3rem"><?= Helper::money($stats['monthly_revenue']) ?></div>
        <div class="stat-lbl">This Month Revenue</div>
        <div class="stat-trend text-success"><i class="bi bi-arrow-up-short"></i> Completed</div>
      </div>
    </div>
  </div>
</div>

<!-- Stat Cards Row 2 -->
<div class="row g-3 mb-4">
  <div class="col-xl-3 col-md-6">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap teal"><i class="bi bi-file-earmark-text"></i></div>
      <div>
        <div class="stat-val"><?= number_format($stats['active_leases']) ?></div>
        <div class="stat-lbl">Active Leases</div>
      </div>
    </div>
  </div>
  <div class="col-xl-3 col-md-6">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap yellow"><i class="bi bi-calendar-check"></i></div>
      <div>
        <div class="stat-val"><?= number_format($stats['pending_bookings']) ?></div>
        <div class="stat-lbl">Pending Bookings</div>
        <div class="stat-trend text-warning"><i class="bi bi-clock"></i> Awaiting review</div>
      </div>
    </div>
  </div>
  <div class="col-xl-3 col-md-6">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap red"><i class="bi bi-tools"></i></div>
      <div>
        <div class="stat-val"><?= number_format($stats['open_maintenance']) ?></div>
        <div class="stat-lbl">Open Maintenance</div>
        <div class="stat-trend text-danger"><i class="bi bi-exclamation-triangle"></i> Needs attention</div>
      </div>
    </div>
  </div>
  <div class="col-xl-3 col-md-6">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap indigo"><i class="bi bi-percent"></i></div>
      <div>
        <div class="stat-val"><?= $stats['occupancy_rate'] ?>%</div>
        <div class="stat-lbl">Occupancy Rate</div>
        <div class="mt-1">
          <div class="occupancy-bar" style="width:100%">
            <div class="occupancy-bar-fill bg-primary" style="width:<?= $stats['occupancy_rate'] ?>%"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Charts Row -->
<div class="row g-3 mb-4">
  <!-- Revenue Chart -->
  <div class="col-xl-8">
    <div class="chart-card">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="chart-title">Monthly Revenue (Last 12 Months)</div>
        <span class="badge bg-primary bg-opacity-10 text-primary">TZS</span>
      </div>
      <div style="height:280px">
        <?php
        $labels = array_column($revenueChart, 'month');
        $values = array_column($revenueChart, 'total');
        ?>
        <canvas id="revenueChart" data-values='<?= json_encode(['labels'=>$labels,'values'=>$values]) ?>'></canvas>
      </div>
    </div>
  </div>

  <!-- Occupancy Donut -->
  <div class="col-xl-4">
    <div class="chart-card h-100">
      <div class="chart-title mb-3">Unit Occupancy</div>
      <div style="height:220px">
        <?php
        $maintenance_units = 0;
        try { $db2=\Core\Database::getInstance(); $maintenance_units=(int)$db2->fetchColumn("SELECT COUNT(*) FROM units WHERE status='maintenance'"); } catch(Exception $e){}
        ?>
        <canvas id="occupancyChart" data-values='<?= json_encode(['occupied'=>$stats['occupied_units'],'available'=>$stats['available_units'],'maintenance'=>$maintenance_units]) ?>'></canvas>
      </div>
      <div class="d-flex justify-content-around mt-3 small">
        <div class="text-center"><div class="fw-700"><?= $stats['occupied_units'] ?></div><div class="text-muted">Occupied</div></div>
        <div class="text-center"><div class="fw-700 text-success"><?= $stats['available_units'] ?></div><div class="text-muted">Available</div></div>
        <div class="text-center"><div class="fw-700 text-warning"><?= $maintenance_units ?></div><div class="text-muted">Maintenance</div></div>
      </div>
    </div>
  </div>
</div>

<!-- Tables Row -->
<div class="row g-3 mb-4">
  <!-- Recent Payments -->
  <div class="col-xl-7">
    <div class="data-card">
      <div class="data-card-header">
        <h6>Recent Payments</h6>
        <a href="<?= APP_URL ?>/admin/payments" class="btn btn-sm btn-outline-primary">View All</a>
      </div>
      <div class="table-responsive">
        <table class="table mb-0">
          <thead>
            <tr><th>Ref</th><th>Tenant</th><th>Unit</th><th>Amount</th><th>Method</th><th>Date</th><th>Status</th></tr>
          </thead>
          <tbody>
            <?php foreach ($recentPayments as $pay): ?>
            <tr>
              <td class="fw-600 small text-primary"><?= Helper::e($pay['payment_ref']) ?></td>
              <td><?= Helper::e($pay['tenant_name']) ?></td>
              <td><?= Helper::e($pay['unit_number'] ?? '—') ?></td>
              <td class="fw-700"><?= Helper::money($pay['amount']) ?></td>
              <td><span class="badge bg-light text-dark"><?= Helper::e($pay['method_name'] ?? 'Cash') ?></span></td>
              <td class="small text-muted"><?= Helper::date($pay['payment_date']) ?></td>
              <td><?= Helper::statusBadge($pay['status']) ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($recentPayments)): ?>
            <tr><td colspan="7" class="text-center text-muted py-4">No payments yet</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Quick Actions + Upcoming Renewals -->
  <div class="col-xl-5">
    <div class="data-card mb-3">
      <div class="data-card-header"><h6>Quick Actions</h6></div>
      <div class="p-3 d-flex flex-column gap-2">
        <a href="<?= APP_URL ?>/admin/tenants/create" class="quick-action"><i class="bi bi-person-plus"></i>Add New Tenant</a>
        <a href="<?= APP_URL ?>/admin/properties/create" class="quick-action"><i class="bi bi-building-add"></i>Add Property</a>
        <a href="<?= APP_URL ?>/admin/payments/create" class="quick-action"><i class="bi bi-credit-card"></i>Record Payment</a>
        <a href="<?= APP_URL ?>/admin/invoices/generate" class="quick-action"><i class="bi bi-receipt"></i>Generate Invoices</a>
        <a href="<?= APP_URL ?>/admin/reports" class="quick-action"><i class="bi bi-bar-chart"></i>View Reports</a>
        <a href="<?= APP_URL ?>/admin/leases/create" class="quick-action"><i class="bi bi-file-earmark-plus"></i>New Lease</a>
      </div>
    </div>
  </div>
</div>

<!-- Overdue + Maintenance Row -->
<div class="row g-3 mb-4">
  <!-- Upcoming Renewals -->
  <div class="col-xl-6">
    <div class="data-card">
      <div class="data-card-header">
        <h6><i class="bi bi-calendar-event text-warning me-2"></i>Upcoming Lease Renewals (30 days)</h6>
        <a href="<?= APP_URL ?>/admin/leases" class="btn btn-sm btn-outline-primary">All Leases</a>
      </div>
      <div class="table-responsive">
        <table class="table mb-0">
          <thead><tr><th>Tenant</th><th>Unit</th><th>Expires</th><th>Action</th></tr></thead>
          <tbody>
            <?php foreach ($upcomingRenewals as $r): ?>
            <tr>
              <td><?= Helper::e($r['tenant_name']) ?></td>
              <td class="small"><?= Helper::e($r['unit_number']) ?> - <?= Helper::e($r['property_name']) ?></td>
              <td><span class="badge bg-warning text-dark"><?= Helper::date($r['end_date']) ?></span></td>
              <td><a href="<?= APP_URL ?>/admin/leases/<?= $r['id'] ?>" class="btn btn-xs btn-outline-primary btn-sm">View</a></td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($upcomingRenewals)): ?>
            <tr><td colspan="4" class="text-center text-muted py-3 small">No upcoming renewals</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Emergency Maintenance -->
  <div class="col-xl-6">
    <div class="data-card">
      <div class="data-card-header">
        <h6><i class="bi bi-tools text-danger me-2"></i>Emergency & Open Maintenance</h6>
        <a href="<?= APP_URL ?>/admin/maintenance" class="btn btn-sm btn-outline-danger">View All</a>
      </div>
      <div class="table-responsive">
        <table class="table mb-0">
          <thead><tr><th>Issue</th><th>Unit</th><th>Priority</th><th>Status</th></tr></thead>
          <tbody>
            <?php foreach ($emergencyMaintenance as $m): ?>
            <tr class="priority-<?= $m['priority'] ?>">
              <td class="fw-600 small"><?= Helper::e($m['title']) ?></td>
              <td class="small text-muted"><?= Helper::e($m['unit_number']) ?></td>
              <td><?= Helper::statusBadge($m['priority']) ?></td>
              <td><?= Helper::statusBadge($m['status']) ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($emergencyMaintenance)): ?>
            <tr><td colspan="4" class="text-center text-muted py-3 small"><i class="bi bi-check-circle text-success me-1"></i>No urgent issues</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- Overdue Invoices Alert -->
<?php if ($stats['overdue_invoices'] > 0): ?>
<div class="alert alert-danger d-flex align-items-center gap-3 rounded-3 mb-4" role="alert">
  <i class="bi bi-exclamation-triangle-fill fs-4 flex-shrink-0"></i>
  <div>
    <strong><?= $stats['overdue_invoices'] ?> overdue invoice(s)</strong> totaling <strong><?= Helper::money($stats['overdue_amount']) ?></strong>.
    <a href="<?= APP_URL ?>/admin/invoices?status=overdue" class="alert-link ms-2">View Overdue Invoices &rarr;</a>
  </div>
</div>
<?php endif; ?>

<!-- Recent Bookings -->
<div class="data-card mb-4">
  <div class="data-card-header">
    <h6>Recent Bookings</h6>
    <a href="<?= APP_URL ?>/admin/bookings" class="btn btn-sm btn-outline-primary">View All</a>
  </div>
  <div class="table-responsive">
    <table class="table mb-0">
      <thead><tr><th>Ref</th><th>Visitor</th><th>Property</th><th>Unit</th><th>Move-in</th><th>Fee</th><th>Status</th><th>Action</th></tr></thead>
      <tbody>
        <?php foreach ($recentBookings as $b): ?>
        <tr>
          <td class="fw-600 text-primary small"><?= Helper::e($b['booking_ref']) ?></td>
          <td><?= Helper::e($b['visitor_name']) ?></td>
          <td class="small text-muted"><?= Helper::e($b['property_name']) ?></td>
          <td><?= Helper::e($b['unit_number']) ?></td>
          <td class="small"><?= Helper::date($b['desired_move_in'] ?? '') ?></td>
          <td><?= Helper::money($b['booking_fee']) ?></td>
          <td><?= Helper::statusBadge($b['status']) ?></td>
          <td><a href="<?= APP_URL ?>/admin/bookings/<?= $b['id'] ?>" class="btn btn-sm btn-outline-secondary btn-action"><i class="bi bi-eye"></i></a></td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($recentBookings)): ?>
        <tr><td colspan="8" class="text-center text-muted py-4">No bookings yet</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

