<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/access_guards.php';
require_once __DIR__ . '/../../app/core/i18n.php';
auth_require_login();
$pdo = crm_pdo();
gp_require_staff_access($pdo);
require_once __DIR__ . '/../../app/core/project_permissions.php';
$canViewCostings = gp_user_perm($pdo, 'perm_costings');
$page_title = 'Συνεργάτες';
$_lang = gp_lang($pdo);

$specialty = trim((string)($_GET['specialty'] ?? ''));
$city      = trim((string)($_GET['city'] ?? ''));
$active    = trim((string)($_GET['active'] ?? ''));
$view      = trim((string)($_GET['view'] ?? 'list')); // 'list' or 'billing'

$where = [];
$params = [];

if ($specialty !== '') { $where[] = 'ep.specialty = :specialty'; $params[':specialty'] = $specialty; }
if ($city !== '')      { $where[] = 'ep.city = :city';           $params[':city'] = $city; }
if ($active !== '')    { $where[] = 'ep.active = :active';       $params[':active'] = (int)$active; }

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

// ── Load partners + billing summary ──
$stmt = $pdo->prepare("
    SELECT
        ep.*,
        COALESCE(stats.job_count, 0) AS job_count,
        COALESCE(stats.total_agreed, 0) AS total_agreed,
        COALESCE(stats.total_paid, 0) AS total_paid,
        COALESCE(stats.pending_amount, 0) AS pending_amount,
        COALESCE(stats.active_jobs, 0) AS active_jobs
    FROM external_partners ep
    LEFT JOIN (
        SELECT
            partner_id,
            COUNT(DISTINCT project_id) AS job_count,
            SUM(cost) AS total_agreed,
            SUM(CASE WHEN status = 'paid' THEN COALESCE(NULLIF(paid_amount, 0), cost) ELSE 0 END) AS total_paid,
            SUM(CASE WHEN status != 'paid' AND status != 'cancelled' THEN cost ELSE 0 END) AS pending_amount,
            SUM(CASE WHEN status != 'paid' AND status != 'cancelled' AND status != 'done' THEN 1 ELSE 0 END) AS active_jobs
        FROM (
            SELECT
                pp.external_partner_id AS partner_id,
                pp.project_id,
                pp.status,
                CASE WHEN pp.agreed_cost IS NOT NULL AND pp.agreed_cost != '' THEN pp.agreed_cost ELSE ppc.quote_amount END AS cost,
                pp.paid_amount
            FROM project_partners pp
            LEFT JOIN partner_project_costings ppc ON ppc.project_id = pp.project_id AND ppc.external_partner_id = pp.external_partner_id
            
            UNION ALL
            
            SELECT
                pa.external_partner_id AS partner_id,
                pa.project_id,
                pa.status,
                ppc.quote_amount AS cost,
                0 AS paid_amount
            FROM project_assignments pa
            LEFT JOIN partner_project_costings ppc ON ppc.project_id = pa.project_id AND ppc.external_partner_id = pa.external_partner_id
            WHERE pa.assignment_type = 'partner'
              AND NOT EXISTS (
                  SELECT 1 FROM project_partners ppx 
                  WHERE ppx.project_id = pa.project_id AND ppx.external_partner_id = pa.external_partner_id
              )
        ) AS all_jobs
        GROUP BY partner_id
    ) AS stats ON stats.partner_id = ep.id
    $whereSql
    ORDER BY pending_amount DESC, ep.company_name ASC
");
$stmt->execute($params);
$rows = $stmt->fetchAll();

// Stats
$totalPartners = count($rows);
$totalPending  = array_sum(array_column($rows, 'pending_amount'));
$totalPaid     = array_sum(array_column($rows, 'total_paid'));
$withBalance   = count(array_filter($rows, fn($r) => (float)$r['pending_amount'] > 0));

$specialties = $pdo->query("SELECT DISTINCT specialty FROM external_partners WHERE specialty IS NOT NULL AND specialty <> '' ORDER BY specialty ASC")->fetchAll(PDO::FETCH_COLUMN);
$cities      = $pdo->query("SELECT DISTINCT city FROM external_partners WHERE city IS NOT NULL AND city <> '' ORDER BY city ASC")->fetchAll(PDO::FETCH_COLUMN);

include __DIR__ . '/../includes/header.php';
?>

<style>
.partner-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 16px; }
.partner-card {
  background: var(--gp-card-bg); border: 1px solid var(--gp-card-border);
  border-radius: 16px; padding: 18px 20px; transition: all 0.2s; cursor: pointer;
  text-decoration: none; color: var(--gp-text); display: flex; flex-direction: column; gap: 12px;
}
.partner-card:hover { transform: translateY(-3px); box-shadow: 0 8px 24px rgba(0,0,0,0.1); border-color: var(--gp-primary); }
.partner-card-header { display: flex; align-items: flex-start; gap: 12px; }
.partner-avatar {
  width: 44px; height: 44px; border-radius: 12px; flex-shrink: 0;
  display: flex; align-items: center; justify-content: center;
  font-weight: 800; font-size: 1.1rem; color: #fff;
  background: linear-gradient(135deg, var(--gp-primary), #6366f1);
}
.partner-name { font-weight: 700; font-size: .95rem; }
.partner-sub  { font-size: .75rem; color: var(--gp-muted); margin-top: 2px; }
.partner-billing { display: flex; gap: 8px; flex-wrap: wrap; }
.bill-chip {
  flex: 1; min-width: 90px; padding: 8px 10px; border-radius: 10px;
  background: var(--gp-nav-bg-2); border: 1px solid var(--gp-card-border);
  display: flex; flex-direction: column; gap: 2px;
}
.bill-chip-label { font-size: .65rem; font-weight: 700; text-transform: uppercase; letter-spacing: .06em; color: var(--gp-muted); }
.bill-chip-value { font-size: .95rem; font-weight: 800; }
.bill-chip.danger  { background: rgba(239,68,68,.06);  border-color: rgba(239,68,68,.15); }
.bill-chip.success { background: rgba(16,185,129,.06); border-color: rgba(16,185,129,.15); }
.bill-chip.warning { background: rgba(245,158,11,.06); border-color: rgba(245,158,11,.15); }
.bill-chip.danger  .bill-chip-value { color: #ef4444; }
.bill-chip.success .bill-chip-value { color: #10b981; }
.bill-chip.warning .bill-chip-value { color: #f59e0b; }
.partner-footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.partner-badge {
  padding: 3px 9px; border-radius: 999px; font-size: .7rem; font-weight: 700;
  background: rgba(37,99,235,.1); color: var(--gp-primary); border: 1px solid rgba(37,99,235,.2);
}
.partner-badge.inactive { background: rgba(100,116,139,.1); color: var(--gp-muted); border-color: rgba(100,116,139,.2); }
.partner-badge.alert { background: rgba(239,68,68,.1); color: #ef4444; border-color: rgba(239,68,68,.2); }

/* Summary bar */
.summary-bar {
  display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 18px;
}
.summary-stat {
  flex: 1; min-width: 130px; background: var(--gp-card-bg); border: 1px solid var(--gp-card-border);
  border-radius: 14px; padding: 14px 18px;
}
.summary-stat-label { font-size: .72rem; font-weight: 700; text-transform: uppercase; letter-spacing: .07em; color: var(--gp-muted); }
.summary-stat-value { font-size: 1.5rem; font-weight: 800; margin-top: 4px; }

.view-toggle-bar { display: flex; gap: 6px; }
.vtb-btn {
  padding: 7px 16px; border-radius: 8px; font-size: .82rem; font-weight: 700;
  border: 1px solid var(--gp-card-border); background: var(--gp-card-bg);
  color: var(--gp-muted); cursor: pointer; text-decoration: none; transition: all .18s;
}
.vtb-btn.active { background: var(--gp-primary); color: #fff; border-color: var(--gp-primary); }

@media(max-width:640px) { .partner-grid { grid-template-columns: 1fr; } }
</style>

<!-- Page header -->
<div class="page-header">
  <div class="page-header-title">
    <h1>🤝 Συνεργάτες</h1>
    <span>Προμηθευτές, υπεργολάβοι, εξωτερικά συνεργεία</span>
  </div>
  <div class="page-header-actions">
    <div class="view-toggle-bar">
      <a class="vtb-btn <?php echo $view !== 'billing' ? 'active' : ''; ?>" href="?view=list&specialty=<?php echo h($specialty); ?>&city=<?php echo h($city); ?>&active=<?php echo h($active); ?>">📋 Λίστα</a>
      <a class="vtb-btn <?php echo $view === 'billing' ? 'active' : ''; ?>" href="?view=billing&specialty=<?php echo h($specialty); ?>&city=<?php echo h($city); ?>&active=<?php echo h($active); ?>">💰 Χρεώσεις</a>
    </div>
    <a class="btn btn-primary btn-sm" href="/gopools/public/partners/edit.php">+ Νέος</a>
  </div>
</div>

<?php if ($canViewCostings): ?>
<!-- Summary bar -->
<div class="summary-bar">
  <div class="summary-stat">
    <div class="summary-stat-label">Συνεργάτες</div>
    <div class="summary-stat-value"><?php echo $totalPartners; ?></div>
  </div>
  <div class="summary-stat">
    <div class="summary-stat-label">Ανεξόφλητα</div>
    <div class="summary-stat-value" style="color:#ef4444;">€ <?php echo number_format($totalPending, 2); ?></div>
  </div>
  <div class="summary-stat">
    <div class="summary-stat-label">Εξοφλήθηκαν</div>
    <div class="summary-stat-value" style="color:#10b981;">€ <?php echo number_format($totalPaid, 2); ?></div>
  </div>
  <div class="summary-stat">
    <div class="summary-stat-label">Με υπόλοιπο</div>
    <div class="summary-stat-value" style="color:#f59e0b;"><?php echo $withBalance; ?></div>
  </div>
</div>
<?php endif; ?>

<!-- Filters -->
<div class="card" style="margin-bottom:16px;">
  <form method="get">
    <input type="hidden" name="view" value="<?php echo h($view); ?>">
    <div class="form-grid">
      <div class="form-group">
        <label>Ειδικότητα</label>
        <select name="specialty">
          <option value="">Όλες</option>
          <?php foreach ($specialties as $s): ?>
            <option value="<?php echo h($s); ?>" <?php echo $specialty === $s ? 'selected' : ''; ?>><?php echo h($s); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label>Πόλη</label>
        <select name="city">
          <option value="">Όλες</option>
          <?php foreach ($cities as $c): ?>
            <option value="<?php echo h($c); ?>" <?php echo $city === $c ? 'selected' : ''; ?>><?php echo h($c); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label>Κατάσταση</label>
        <select name="active">
          <option value="">Όλοι</option>
          <option value="1" <?php echo $active === '1' ? 'selected' : ''; ?>>Ενεργοί</option>
          <option value="0" <?php echo $active === '0' ? 'selected' : ''; ?>>Ανενεργοί</option>
        </select>
      </div>
    </div>
    <div class="form-actions" style="margin-top:12px;">
      <button class="btn btn-primary btn-sm" type="submit">Φίλτρο</button>
      <a class="btn btn-secondary btn-sm" href="/gopools/public/partners/index.php?view=<?php echo h($view); ?>">Καθαρισμός</a>
    </div>
  </form>
</div>

<?php if ($view === 'billing' && $canViewCostings): ?>
<!-- ═══ BILLING VIEW ═══ -->
<div class="card">
  <div class="table-responsive">
    <table class="table">
      <thead>
        <tr>
          <th>Συνεργάτης</th>
          <th>Ειδικότητα</th>
          <th>Εργα</th>
          <th>Συμφωνηθέν</th>
          <th>Εξοφλήθηκε</th>
          <th style="color:#ef4444;">Υπόλοιπο ⚡</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $row):
          $pending = (float)$row['pending_amount'];
          $paid    = (float)$row['total_paid'];
          $agreed  = (float)$row['total_agreed'];
        ?>
        <tr style="<?php echo $pending > 0 ? 'background:rgba(239,68,68,0.02)' : ''; ?>">
          <td>
            <div style="font-weight:700;"><?php echo h($row['company_name']); ?></div>
            <div style="font-size:.75rem;color:var(--gp-muted);"><?php echo h($row['contact_person'] ?? ''); ?></div>
          </td>
          <td style="font-size:.85rem;"><?php echo h($row['specialty'] ?? '—'); ?></td>
          <td>
            <span style="background:rgba(37,99,235,.1);color:var(--gp-primary);border-radius:6px;padding:2px 8px;font-size:.8rem;font-weight:700;">
              <?php echo (int)$row['job_count']; ?> έργα
            </span>
            <?php if ((int)$row['active_jobs'] > 0): ?>
            <span style="background:rgba(245,158,11,.1);color:#f59e0b;border-radius:6px;padding:2px 8px;font-size:.8rem;font-weight:700;margin-left:4px;">
              <?php echo (int)$row['active_jobs']; ?> ενεργά
            </span>
            <?php endif; ?>
          </td>
          <td style="font-weight:700;">€ <?php echo number_format($agreed, 2); ?></td>
          <td style="color:#10b981;font-weight:700;">€ <?php echo number_format($paid, 2); ?></td>
          <td>
            <?php if ($pending > 0): ?>
              <span style="background:rgba(239,68,68,.1);color:#ef4444;border-radius:8px;padding:4px 10px;font-size:.88rem;font-weight:800;">
                € <?php echo number_format($pending, 2); ?>
              </span>
            <?php else: ?>
              <span style="color:#10b981;font-weight:700;">✅ Εξοφλήθηκε</span>
            <?php endif; ?>
          </td>
          <td>
            <a class="btn btn-sm btn-primary" href="/gopools/public/partners/history.php?id=<?php echo (int)$row['id']; ?>">Λεπτομέρειες</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php else: ?>
<!-- ═══ CARD LIST VIEW ═══ -->
<div class="partner-grid">
  <?php foreach ($rows as $row):
    $initials = strtoupper(substr($row['company_name'] ?? $row['contact_person'] ?? 'P', 0, 1));
    $pending  = (float)$row['pending_amount'];
    $paid     = (float)$row['total_paid'];
    $agreed   = (float)$row['total_agreed'];
    $isActive = (int)$row['active'] === 1;
    $colors   = ['#3b82f6','#8b5cf6','#10b981','#f59e0b','#f43f5e','#0ea5e9','#6366f1'];
    $color    = $colors[$row['id'] % count($colors)];
  ?>
  <a class="partner-card" href="/gopools/public/partners/history.php?id=<?php echo (int)$row['id']; ?>">
    <div class="partner-card-header">
      <div class="partner-avatar" style="background:linear-gradient(135deg,<?php echo $color; ?>,<?php echo $color; ?>aa);">
        <?php echo h($initials); ?>
      </div>
      <div style="flex:1;min-width:0;">
        <div class="partner-name"><?php echo h($row['company_name'] ?? $row['contact_person']); ?></div>
        <div class="partner-sub">
          <?php echo h($row['specialty'] ?? ''); ?>
          <?php if ($row['city']): ?> · <?php echo h($row['city']); ?><?php endif; ?>
        </div>
        <?php if ($row['phone']): ?>
        <div class="partner-sub">📞 <?php echo h($row['phone']); ?></div>
        <?php endif; ?>
      </div>
      <span class="partner-badge <?php echo $isActive ? '' : 'inactive'; ?>">
        <?php echo $isActive ? 'Ενεργός' : 'Ανενεργός'; ?>
      </span>
    </div>

    <?php if ($canViewCostings): ?>
    <div class="partner-billing">
      <div class="bill-chip warning">
        <span class="bill-chip-label">Εργα</span>
        <span class="bill-chip-value"><?php echo (int)$row['job_count']; ?></span>
      </div>
      <div class="bill-chip <?php echo $pending > 0 ? 'danger' : 'success'; ?>">
        <span class="bill-chip-label">Υπόλοιπο</span>
        <span class="bill-chip-value">€ <?php echo number_format($pending, 0); ?></span>
      </div>
      <div class="bill-chip success">
        <span class="bill-chip-label">Πληρωμένο</span>
        <span class="bill-chip-value">€ <?php echo number_format($paid, 0); ?></span>
      </div>
    </div>

    <?php if ($pending > 0): ?>
    <div class="partner-footer">
      <span class="partner-badge alert">⚡ Εκκρεμεί € <?php echo number_format($pending, 2); ?></span>
      <span style="font-size:.75rem;color:var(--gp-muted);"><?php echo (int)$row['active_jobs']; ?> ενεργά έργα</span>
    </div>
    <?php endif; ?>
    <?php endif; ?>
  </a>
  <?php endforeach; ?>
</div>
<?php endif; ?>

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