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

$partnerId = auth_partner_id();

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

if ($partnerId <= 0) {
    http_response_code(403);
    exit('Partner 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.external_partner_id = :partner_id AND pa.status = 'completed'
    ORDER BY pa.stopped_at DESC, pa.id DESC
");
$stmt->execute([':partner_id' => $partnerId]);
$rows = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>✅ Ολοκληρωμένα Έργα</h1>
    <span><?php echo count($rows); ?> εργασίες</span>
  </div>
  <div class="page-header-actions">
    <a class="btn btn-outline-light btn-sm" href="/gopools/public/partners/my_jobs.php">← Ενεργά Έργα</a>
  </div>
</div>

<?php if (!$rows): ?>
  <div class="card" style="padding: 40px; text-align: center; border-radius: 16px;">
    <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;">
    <div style="font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; color: var(--gp-muted); font-weight: 700;">Σύνολο Έργων</div>
    <div style="font-size: 2rem; font-weight: 800; color: #10b981; margin-top: 4px;"><?php echo count($rows); ?></div>
  </div>
  <?php
    $totalDays = 0;
    foreach ($rows as $r) {
        if (!empty($r['start_date']) && !empty($r['end_date_actual'])) {
            $totalDays += (int)(new DateTime($r['start_date']))->diff(new DateTime($r['end_date_actual']))->days;
        }
    }
  ?>
  <div class="card" style="padding: 16px; text-align: center; border-radius: 12px;">
    <div style="font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; color: var(--gp-muted); font-weight: 700;">Συνολικές Ημέρες</div>
    <div style="font-size: 2rem; font-weight: 800; color: #3b82f6; margin-top: 4px;"><?php echo $totalDays > 0 ? $totalDays : '—'; ?></div>
  </div>
  <div class="card" style="padding: 16px; text-align: center; border-radius: 12px;">
    <div style="font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; color: var(--gp-muted); 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 List -->
<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); text-align: right;"></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
        <tr class="completed-row" style="border-bottom: 1px solid var(--gp-card-border); transition: background 0.15s;" 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;">
            <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;">
            <a href="/gopools/public/partners/project_detail.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'; ?>
