<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/portal_auth.php';
auth_require_employee_portal();
$pdo = crm_pdo();
$page_title = 'Completed Projects';

$employeeId = auth_employee_id();

if (auth_is_admin_like() && $employeeId <= 0) {
    $employees = $pdo->query("SELECT id, full_name FROM employees WHERE active = 1 ORDER BY full_name ASC")->fetchAll();
    include __DIR__ . '/../includes/header.php';
    ?>
    <div class="page-header">
      <div class="page-header-title">
        <h1>Employee Portal</h1>
        <span>Admin access — choose employee</span>
      </div>
    </div>
    <div class="card">
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>Name</th><th></th></tr></thead>
          <tbody>
            <?php foreach ($employees as $e): ?>
              <tr>
                <td><?php echo h($e['full_name']); ?></td>
                <td><a class="btn btn-sm btn-outline-light" href="/gopools/public/employees/completed.php?employee_id=<?php echo (int)$e['id']; ?>">View completed</a></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php include __DIR__ . '/../includes/footer.php'; exit;
}

if ($employeeId <= 0) { http_response_code(403); exit('Employee record not linked.'); }

$stmt = $pdo->prepare("
    SELECT pa.id AS assignment_id, pa.project_id, pa.status, pa.assigned_date, pa.role_label,
           pa.stopped_at, pa.started_at,
           p.title, p.code, p.address, p.city, p.start_date, p.end_date_actual,
           c.name AS customer_name
    FROM project_assignments pa
    JOIN projects p ON p.id = pa.project_id
    LEFT JOIN customers c ON c.id = p.customer_id
    WHERE pa.employee_id = :employee_id AND pa.status = 'completed'
    ORDER BY pa.stopped_at DESC, pa.id DESC
");
$stmt->execute([':employee_id' => $employeeId]);
$rows = $stmt->fetchAll();

// Hours calculation
$totalHours = 0;
foreach ($rows as $r) {
    if (!empty($r['started_at']) && !empty($r['stopped_at'])) {
        $totalHours += round((strtotime($r['stopped_at']) - strtotime($r['started_at'])) / 3600, 1);
    }
}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header" style="background: rgba(255,255,255,0.05); backdrop-filter: blur(10px); border-bottom: 1px solid rgba(255,255,255,0.1); border-radius: 16px; padding: 20px; margin-bottom: 24px; display: flex; justify-content: space-between; align-items: center;">
  <div class="page-header-title">
    <h1 style="font-size: 1.8rem; font-weight: 800; background: linear-gradient(90deg, #10b981, #3b82f6); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">✅ Ολοκληρωμένα Έργα</h1>
    <span style="color: var(--gp-muted); font-size: 0.9rem;"><?php echo count($rows); ?> εργασίες</span>
  </div>
  <a class="btn btn-outline-light btn-sm" href="/gopools/public/employees/my_jobs.php">← Ενεργά Έργα</a>
</div>

<?php if (!$rows): ?>
  <div class="card" style="padding: 40px; text-align: center; border-radius: 16px; background: rgba(16,185,129,0.05); border: 1px dashed rgba(16,185,129,0.3);">
    <div style="font-size: 3rem; margin-bottom: 10px;">📭</div>
    <h3 style="color: var(--gp-muted); font-weight: 600; margin: 0;">Δεν υπάρχουν ολοκληρωμένα έργα ακόμα</h3>
  </div>
<?php else: ?>

<!-- Summary Stats -->
<div class="grid-3" style="margin-bottom: 24px; gap: 16px;">
  <div class="card" style="padding: 16px; text-align: center; border-radius: 12px; background: rgba(16,185,129,0.05); border: 1px solid rgba(16,185,129,0.15);">
    <div style="font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; color: #10b981; font-weight: 700;">Ολοκληρωμένα</div>
    <div style="font-size: 2.2rem; font-weight: 800; color: #10b981; margin-top: 4px;"><?php echo count($rows); ?></div>
  </div>
  <div class="card" style="padding: 16px; text-align: center; border-radius: 12px; background: rgba(59,130,246,0.05); border: 1px solid rgba(59,130,246,0.15);">
    <div style="font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; color: #3b82f6; font-weight: 700;">Συνολικές Ώρες</div>
    <div style="font-size: 2.2rem; font-weight: 800; color: #3b82f6; margin-top: 4px;"><?php echo $totalHours > 0 ? $totalHours : '—'; ?><span style="font-size: 1rem; color: var(--gp-muted);"> h</span></div>
  </div>
  <div class="card" style="padding: 16px; text-align: center; border-radius: 12px; background: rgba(245,158,11,0.05); border: 1px solid rgba(245,158,11,0.15);">
    <div style="font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; color: #f59e0b; font-weight: 700;">Τελευταίο</div>
    <div style="font-size: 1rem; font-weight: 700; color: var(--gp-text); margin-top: 4px;"><?php echo !empty($rows[0]['stopped_at']) ? gp_date($rows[0]['stopped_at']) : '—'; ?></div>
  </div>
</div>

<!-- Search -->
<div class="card" style="padding: 12px 16px; margin-bottom: 16px; border-radius: 12px;">
  <input type="text" id="completed-search" placeholder="🔍 Αναζήτηση έργου..." style="width: 100%; background: transparent; border: none; outline: none; font-size: 0.95rem; color: var(--gp-text);">
</div>

<!-- Compact Table -->
<div class="card" style="border-radius: 16px; overflow: hidden; padding: 0;">
  <div style="overflow-x: auto;">
    <table class="table" style="margin: 0;" id="completed-table">
      <thead>
        <tr style="background: var(--gp-nav-bg-2);">
          <th style="padding: 12px 16px; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--gp-muted); font-weight: 700; border-bottom: 1px solid var(--gp-card-border);">Έργο</th>
          <th style="padding: 12px 16px; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--gp-muted); font-weight: 700; border-bottom: 1px solid var(--gp-card-border);">Πελάτης</th>
          <th style="padding: 12px 16px; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--gp-muted); font-weight: 700; border-bottom: 1px solid var(--gp-card-border);">Τοποθεσία</th>
          <th style="padding: 12px 16px; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--gp-muted); font-weight: 700; border-bottom: 1px solid var(--gp-card-border);">Ώρες</th>
          <th style="padding: 12px 16px; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--gp-muted); font-weight: 700; border-bottom: 1px solid var(--gp-card-border);">Ολοκλήρωση</th>
          <th style="padding: 12px 16px; border-bottom: 1px solid var(--gp-card-border); text-align: right;"></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $r):
          $hrs = '';
          if (!empty($r['started_at']) && !empty($r['stopped_at'])) {
              $h = round((strtotime($r['stopped_at']) - strtotime($r['started_at'])) / 3600, 1);
              if ($h > 0) $hrs = $h . ' h';
          }
        ?>
        <tr class="completed-row" style="border-bottom: 1px solid var(--gp-card-border); transition: background 0.15s; cursor: pointer;" onclick="window.location='/gopools/public/employees/job_action.php?assignment_id=<?php echo (int)$r['assignment_id']; ?>'" onmouseover="this.style.background='var(--gp-nav-bg-2)'" onmouseout="this.style.background=''">
          <td style="padding: 12px 16px; vertical-align: middle;">
            <div style="font-weight: 700; font-size: 0.9rem; color: var(--gp-text);"><?php echo h($r['title']); ?></div>
            <div style="font-size: 0.72rem; color: var(--gp-muted); margin-top: 2px;"><?php echo h($r['code']); ?><?php if ($r['role_label']): ?> · <?php echo h($r['role_label']); ?><?php endif; ?></div>
          </td>
          <td style="padding: 12px 16px; vertical-align: middle; font-size: 0.88rem; color: var(--gp-text);">
            <?php echo h($r['customer_name'] ?? '—'); ?>
          </td>
          <td style="padding: 12px 16px; vertical-align: middle; font-size: 0.82rem; color: var(--gp-muted);">
            <?php echo h(trim(($r['address'] ?? '') . ' ' . ($r['city'] ?? ''))); ?>
          </td>
          <td style="padding: 12px 16px; vertical-align: middle; font-size: 0.82rem;">
            <?php if ($hrs): ?>
              <span style="background: rgba(59,130,246,0.1); color: #3b82f6; border-radius: 8px; padding: 2px 8px; font-size: 0.78rem; font-weight: 700;"><?php echo $hrs; ?></span>
            <?php else: ?>
              <span style="color: var(--gp-muted);">—</span>
            <?php endif; ?>
          </td>
          <td style="padding: 12px 16px; vertical-align: middle;">
            <span style="background: rgba(16,185,129,0.12); color: #10b981; border: 1px solid rgba(16,185,129,0.25); border-radius: 20px; padding: 3px 10px; font-size: 0.75rem; font-weight: 700; white-space: nowrap;">
              ✅ <?php echo !empty($r['stopped_at']) ? gp_date($r['stopped_at']) : gp_date($r['assigned_date']); ?>
            </span>
          </td>
          <td style="padding: 12px 16px; vertical-align: middle; text-align: right;" onclick="event.stopPropagation()">
            <a href="/gopools/public/employees/job_action.php?assignment_id=<?php echo (int)$r['assignment_id']; ?>" class="btn btn-sm btn-outline-light" style="font-size: 0.78rem; padding: 4px 12px; border-radius: 8px;">
              Λεπτομέρειες →
            </a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php endif; ?>

<script>
document.getElementById('completed-search')?.addEventListener('input', function() {
  const q = this.value.toLowerCase();
  document.querySelectorAll('#completed-table .completed-row').forEach(function(row) {
    row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
  });
});
</script>

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