<?php
session_start();
$page_title = 'Dashboard';
$active_nav = 'dashboard';
require_once __DIR__ . '/includes/header.php';

// Stats
$stats = get_org_stats($conn, $org_id);

// Recent funding batches (last 5)
$recent_batches = [];
$rb = $conn->prepare(
    "SELECT b.*, u.name AS admin_name
     FROM org_funding_batches b
     INNER JOIN users u ON b.funded_by = u.id
     WHERE b.organization_id = ?
     ORDER BY b.created_at DESC LIMIT 5"
);
$rb->bind_param("i", $org_id);
$rb->execute();
$recent_batches = $rb->get_result()->fetch_all(MYSQLI_ASSOC);

// Recent staff (last 5 added)
$recent_staff = [];
$rs = $conn->prepare(
    "SELECT id, name, email, employee_id, department, status, created_at
     FROM users
     WHERE organization_id = ? AND role = 'org_staff'
     ORDER BY created_at DESC LIMIT 5"
);
$rs->bind_param("i", $org_id);
$rs->execute();
$recent_staff = $rs->get_result()->fetch_all(MYSQLI_ASSOC);

// Active schedules count
$sch = $conn->prepare("SELECT COUNT(*) FROM org_funding_schedules WHERE organization_id=? AND is_active=1");
$sch->bind_param("i", $org_id);
$sch->execute();
$active_schedules = (int)$sch->get_result()->fetch_row()[0];

// Next upcoming schedule
$next_sch = $conn->prepare(
    "SELECT label, frequency, next_run_at, amount_per_staff
     FROM org_funding_schedules
     WHERE organization_id=? AND is_active=1
     ORDER BY next_run_at ASC LIMIT 1"
);
$next_sch->bind_param("i", $org_id);
$next_sch->execute();
$upcoming = $next_sch->get_result()->fetch_assoc();
?>

<div class="anim-up">

<!-- Page header -->
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h2 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em">Welcome back, <?php echo h(explode(' ', $__name)[0]); ?> ðŸ‘‹</h2>
    <p style="font-size:.84rem;color:var(--text-muted);margin-top:3px"><?php echo h($__org_name); ?> Â· <?php echo date('l, F j, Y'); ?></p>
  </div>
  <div style="display:flex;gap:10px">
 <a href="fund_staff.php" class="btn btn-secondary btn-md">
    <span style="font-size:18px;font-weight:bold;">₦</span>
    Fund Staff
</a>
    <a href="staff.php?action=add" class="btn btn-org btn-md">
      <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
      Add Staff
    </a>
  </div>
</div>

<!-- Stats row -->
<div class="stat-grid" style="grid-template-columns:repeat(auto-fit,minmax(200px,1fr));margin-bottom:28px">

  <div class="stat-card" style="border-top:3px solid var(--org-accent)">
    <div class="stat-label">Active Staff</div>
    <div class="stat-value" style="color:var(--org-accent)"><?php echo number_format($stats['active_staff']); ?></div>
    <?php if ($stats['suspended_staff'] > 0): ?>
    <div class="stat-sub" style="color:var(--error)"><?php echo $stats['suspended_staff']; ?> suspended</div>
    <?php else: ?>
    <div class="stat-sub">All accounts active</div>
    <?php endif; ?>
  </div>

  <div class="stat-card" style="border-top:3px solid var(--success)">
    <div class="stat-label">Meal Ticket Balance</div>
    <div class="stat-value" style="color:var(--success);font-size:1.4rem"><?php echo fmt_money($stats['total_meal_ticket_balance']); ?></div>
    <div class="stat-sub">In circulation across all staff</div>
  </div>

  <div class="stat-card" style="border-top:3px solid var(--primary)">
    <div class="stat-label">Funded This Month</div>
    <div class="stat-value" style="font-size:1.4rem;color:var(--primary)"><?php echo fmt_money($stats['funded_this_month']); ?></div>
    <div class="stat-sub"><?php echo date('F Y'); ?></div>
  </div>

  <div class="stat-card" style="border-top:3px solid var(--warning)">
    <div class="stat-label">Total Funded (All Time)</div>
    <div class="stat-value" style="font-size:1.4rem;color:var(--warning)"><?php echo fmt_money($stats['total_funded']); ?></div>
    <div class="stat-sub"><?php echo number_format($stats['total_batches']); ?> funding batch<?php echo $stats['total_batches'] !== 1 ? 'es' : ''; ?></div>
  </div>

</div>

<!-- Main grid -->
<div style="display:grid;grid-template-columns:1fr 340px;gap:20px;align-items:start">

  <!-- Recent funding batches -->
  <div class="card">
    <div class="card-header">
      <h3>Recent Funding Activity</h3>
      <a href="transactions.php" class="btn btn-secondary btn-sm">View All</a>
    </div>

    <?php if (empty($recent_batches)): ?>
    <div class="card-body" style="text-align:center;padding:48px 24px">
      <div style="width:52px;height:52px;background:var(--org-accent-bg);border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 14px">
        <svg width="24" height="24" viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="var(--org-accent)" stroke-linecap="round"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 100 7h5a3.5 3.5 0 010 7H6"/></svg>
      </div>
      <p style="font-weight:700;margin-bottom:4px">No funding activity yet</p>
      <p style="font-size:.82rem;color:var(--text-muted)">Start funding your staff's meal tickets</p>
      <a href="fund_staff.php" class="btn btn-org btn-md" style="margin-top:16px">Fund Staff Now</a>
    </div>
    <?php else: ?>
    <div style="overflow-x:auto">
      <table class="data-table">
        <thead>
          <tr>
            <th>Batch</th>
            <th>Type</th>
            <th>Staff</th>
            <th>Amount</th>
            <th>Status</th>
            <th>Date</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($recent_batches as $b): ?>
          <tr>
            <td style="font-size:.78rem;color:var(--text-muted);font-family:monospace"><?php echo h(substr($b['reference'], 0, 20)); ?>â€¦</td>
            <td><span class="badge badge-org"><?php echo h(ucfirst(str_replace('_', ' ', $b['batch_type']))); ?></span></td>
            <td><?php echo $b['staff_count']; ?> staff</td>
            <td style="font-weight:700"><?php echo fmt_money($b['total_amount']); ?></td>
            <td>
              <?php
              $bs = $b['status'];
              $cls = match($bs) { 'completed'=>'badge-success','failed'=>'badge-error',default=>'badge-warning' };
              echo '<span class="badge '.$cls.'">'.ucfirst($bs).'</span>';
              ?>
            </td>
            <td style="color:var(--text-muted);font-size:.8rem"><?php echo time_ago($b['created_at']); ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </div>

  <!-- Right column -->
  <div style="display:flex;flex-direction:column;gap:16px">

    <!-- Quick actions -->
    <div class="card card-body" style="padding:18px 20px">
      <h3 style="font-size:.88rem;font-weight:700;margin-bottom:14px">Quick Actions</h3>
      <div style="display:flex;flex-direction:column;gap:8px">
        <a href="fund_staff.php" class="btn btn-org btn-md btn-block">
          <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 100 7h5a3.5 3.5 0 010 7H6"/></svg>
          Fund Individual Staff
        </a>
        
        <a href="fund_staff.php" class="btn btn-secondary btn-md">
    <span style="font-size:18px;font-weight:bold;">₦</span>
    Fund Individual Staff
</a>
        <a href="fund_bulk.php" class="btn btn-secondary btn-md btn-block">
          <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg>
          Bulk Fund All Staff
        </a>
        <a href="staff.php?action=add" class="btn btn-secondary btn-md btn-block">
          <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
          Add Staff Member
        </a>
        <a href="schedules.php" class="btn btn-secondary btn-md btn-block">
          <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
          Manage Schedules
        </a>
      </div>
    </div>

    <!-- Upcoming schedule -->
    <?php if ($upcoming): ?>
    <div class="card card-body" style="padding:18px 20px;border-left:3px solid var(--org-accent)">
      <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px">
        <svg width="16" height="16" viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="var(--org-accent)" stroke-linecap="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
        <h3 style="font-size:.88rem;font-weight:700;color:var(--org-accent)">Next Scheduled Funding</h3>
      </div>
      <p style="font-weight:700;margin-bottom:4px"><?php echo h($upcoming['label']); ?></p>
      <p style="font-size:.8rem;color:var(--text-muted)"><?php echo fmt_money($upcoming['amount_per_staff']); ?> / staff Â· <?php echo ucfirst(str_replace('_', ' ', $upcoming['frequency'])); ?></p>
      <p style="font-size:.78rem;font-weight:700;color:var(--org-accent);margin-top:8px">ðŸ“… <?php echo fmt_date($upcoming['next_run_at']); ?></p>
      <div style="display:flex;align-items:center;justify-content:space-between;margin-top:10px">
        <span class="badge badge-success"><?php echo $active_schedules; ?> active schedule<?php echo $active_schedules!==1?'s':''; ?></span>
        <a href="schedules.php" style="font-size:.78rem;color:var(--org-accent);font-weight:700">View All â†’</a>
      </div>
    </div>
    <?php else: ?>
    <div class="card card-body" style="padding:18px 20px;text-align:center">
      <p style="font-size:.8rem;color:var(--text-muted);margin-bottom:10px">No active schedules</p>
      <a href="schedules.php" class="btn btn-secondary btn-sm">Set Up Auto-Funding</a>
    </div>
    <?php endif; ?>

  </div>
</div>

<!-- Recent staff -->
<?php if (!empty($recent_staff)): ?>
<div class="card" style="margin-top:20px">
  <div class="card-header">
    <h3>Recently Added Staff</h3>
    <a href="staff.php" class="btn btn-secondary btn-sm">View All Staff</a>
  </div>
  <div style="overflow-x:auto">
    <table class="data-table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Employee ID</th>
          <th>Department</th>
          <th>Status</th>
          <th>Joined</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($recent_staff as $s): ?>
        <tr>
          <td>
            <div style="display:flex;align-items:center;gap:10px">
              <div style="width:32px;height:32px;border-radius:50%;background:var(--org-accent-bg);display:flex;align-items:center;justify-content:center;font-size:.72rem;font-weight:800;color:var(--org-accent);flex-shrink:0"><?php echo h(initials($s['name'])); ?></div>
              <span style="font-weight:600"><?php echo h($s['name']); ?></span>
            </div>
          </td>
          <td style="color:var(--text-muted);font-size:.82rem"><?php echo h($s['email']); ?></td>
          <td style="font-family:monospace;font-size:.8rem"><?php echo h($s['employee_id'] ?? 'â€”'); ?></td>
          <td style="font-size:.82rem"><?php echo h($s['department'] ?? 'â€”'); ?></td>
          <td><?php echo status_badge($s['status']); ?></td>
          <td style="color:var(--text-muted);font-size:.8rem"><?php echo fmt_date($s['created_at']); ?></td>
          <td><a href="staff_view.php?id=<?php echo $s['id']; ?>" class="btn btn-secondary btn-sm">View</a></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>

</div><!-- .anim-up -->

<?php require_once __DIR__ . '/includes/footer.php'; ?>
