<?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);
$canViewCostings = gp_user_perm($pdo, 'perm_costings');

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { header('Location: /gopools/public/partners/index.php'); exit; }

$stmt = $pdo->prepare("SELECT * FROM external_partners WHERE id = :id LIMIT 1");
$stmt->execute([':id' => $id]);
$partner = $stmt->fetch();
if (!$partner) { header('Location: /gopools/public/partners/index.php'); exit; }

$page_title = $partner['company_name'] ?: $partner['contact_person'];

// ── 1. Jobs from project_partners (manual/billing records) ──
$stmt = $pdo->prepare("
    SELECT
        pp.id,
        pp.project_id,
        pp.work_date,
        pp.description,
        pp.agreed_cost,
        pp.paid_amount,
        pp.paid_date,
        pp.status,
        pp.notes,
        p.code,
        p.title  AS project_title,
        p.status AS project_status,
        p.city   AS project_city,
        'manual' AS source,
        ppc.quote_amount
    FROM project_partners pp
    LEFT JOIN projects p ON p.id = pp.project_id
    LEFT JOIN partner_project_costings ppc ON ppc.project_id = p.id AND ppc.external_partner_id = pp.external_partner_id
    WHERE pp.external_partner_id = :id
    ORDER BY pp.work_date DESC, pp.id DESC
");
$stmt->execute([':id' => $id]);
$manualRows = $stmt->fetchAll();

$manualProjectIds = array_column($manualRows, 'project_id');

// ── 2. Jobs from project_assignments (dispatches) ──
$stmtA = $pdo->prepare("
    SELECT
        pa.id,
        pa.project_id,
        pa.assigned_date AS work_date,
        pa.role_label    AS description,
        NULL             AS agreed_cost,
        NULL             AS paid_amount,
        NULL             AS paid_date,
        pa.status,
        pa.notes,
        p.code,
        p.title  AS project_title,
        p.status AS project_status,
        p.city   AS project_city,
        'dispatch' AS source,
        ppc.quote_amount
    FROM project_assignments pa
    LEFT JOIN projects p ON p.id = pa.project_id
    LEFT JOIN partner_project_costings ppc ON ppc.project_id = p.id AND ppc.external_partner_id = pa.external_partner_id
    WHERE pa.external_partner_id = :id
      AND pa.assignment_type = 'partner'
    ORDER BY pa.assigned_date DESC, pa.id DESC
");
$stmtA->execute([':id' => $id]);
$assignedRows = $stmtA->fetchAll();

// Filter out assignments if we already have a manual billing record for that project
$filteredAssignedRows = array_filter($assignedRows, function($r) use ($manualProjectIds) {
    return !in_array($r['project_id'], $manualProjectIds);
});

// Merge both sources
$allRows = array_merge($manualRows, $filteredAssignedRows);

// Sort merged rows by work_date descending
usort($allRows, function($a, $b) {
    return strcmp($b['work_date'] ?? '', $a['work_date'] ?? '');
});

// Split into pending/paid
$pendingRows = array_filter($allRows, fn($r) => $r['status'] !== 'paid' && $r['status'] !== 'cancelled');
$paidRows    = array_filter($allRows, fn($r) => $r['status'] === 'paid');
$cancelledRows = array_filter($allRows, fn($r) => $r['status'] === 'cancelled');

// Totals (use agreed_cost if set and numeric, otherwise fallback to quote_amount)
$getCost = fn($r) => (float)(is_numeric($r['agreed_cost'] ?? null) ? $r['agreed_cost'] : ($r['quote_amount'] ?? 0));
// Για πληρωμένες: αν έχει paid_amount χρησιμοποιούμε αυτό, αλλιώς agreed_cost/quote_amount
$getPaid = fn($r) => (float)(is_numeric($r['paid_amount'] ?? null) && (float)$r['paid_amount'] > 0 
    ? $r['paid_amount'] 
    : (is_numeric($r['agreed_cost'] ?? null) ? $r['agreed_cost'] : ($r['quote_amount'] ?? 0)));
$totalAgreed  = array_sum(array_map($getCost, $allRows));
$totalPaid    = array_sum(array_map($getPaid, iterator_to_array(new ArrayIterator($paidRows))));
$totalPending = array_sum(array_map($getCost, iterator_to_array(new ArrayIterator($pendingRows))));

$activeTab = $_GET['tab'] ?? 'pending';

$statusColors = [
    'planned'  => '#8b5cf6',
    'working'  => '#f59e0b',
    'done'     => '#10b981',
    'paid'     => '#10b981',
    'cancelled'=> '#ef4444',
];
$statusLabels = [
    'planned'  => 'Προγραμματισμένο',
    'working'  => 'Σε εξέλιξη',
    'done'     => 'Ολοκληρώθηκε',
    'paid'     => 'Εξοφλήθηκε',
    'cancelled'=> 'Ακυρώθηκε',
];

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

<style>
.partner-hero {
  background: linear-gradient(135deg, var(--gp-primary) 0%, #6366f1 100%);
  border-radius: 20px; padding: 28px 32px; margin-bottom: 20px;
  color: #fff; display: flex; align-items: center; gap: 20px;
  position: relative; overflow: hidden;
}
.partner-hero::before {
  content: ''; position: absolute; top: -40px; right: -40px;
  width: 180px; height: 180px; border-radius: 50%;
  background: rgba(255,255,255,0.06);
}
.partner-hero-avatar {
  width: 64px; height: 64px; border-radius: 18px; flex-shrink: 0;
  background: rgba(255,255,255,0.15); display: flex; align-items: center;
  justify-content: center; font-size: 1.8rem; font-weight: 800;
  border: 2px solid rgba(255,255,255,0.3);
}
.partner-hero-name { font-size: 1.5rem; font-weight: 800; }
.partner-hero-sub  { font-size: .9rem; opacity: .8; margin-top: 4px; }

.billing-cards { display: grid; grid-template-columns: repeat(4,1fr); gap: 12px; margin-bottom: 20px; }
.billing-card {
  background: var(--gp-card-bg); border: 1px solid var(--gp-card-border);
  border-radius: 14px; padding: 16px 18px;
}
.billing-card-label { font-size: .72rem; font-weight: 700; text-transform: uppercase; letter-spacing: .07em; color: var(--gp-muted); }
.billing-card-value { font-size: 1.45rem; font-weight: 800; margin-top: 6px; }

.tab-bar { display: flex; gap: 4px; border-bottom: 2px solid var(--gp-card-border); margin-bottom: 16px; }
.tab-btn {
  padding: 10px 18px; font-size: .85rem; font-weight: 700; border: none;
  background: transparent; color: var(--gp-muted); cursor: pointer;
  border-bottom: 2px solid transparent; margin-bottom: -2px; transition: all .18s;
  text-decoration: none; display: inline-block;
}
.tab-btn.active { color: var(--gp-primary); border-bottom-color: var(--gp-primary); }
.tab-btn .tab-count {
  display: inline-flex; align-items: center; justify-content: center;
  width: 20px; height: 20px; border-radius: 999px; font-size: .68rem;
  background: rgba(0,0,0,.06); margin-left: 6px;
}
[data-theme='dark'] .tab-btn .tab-count { background: rgba(255,255,255,.08); }
.tab-btn.active .tab-count { background: rgba(37,99,235,.15); color: var(--gp-primary); }

.job-row { transition: background .15s; }
.job-row:hover { background: rgba(0,0,0,.015); }
[data-theme='dark'] .job-row:hover { background: rgba(255,255,255,.015); }

.status-pill {
  display: inline-flex; align-items: center; gap: 4px;
  padding: 3px 9px; border-radius: 999px; font-size: .72rem; font-weight: 700;
}

@media(max-width:768px) { .billing-cards { grid-template-columns: repeat(2,1fr); } }
@media(max-width:480px) { .billing-cards { grid-template-columns: 1fr 1fr; } }
</style>

<!-- Hero -->
<div class="partner-hero">
  <div class="partner-hero-avatar">
    <?php echo strtoupper(substr($partner['company_name'] ?: $partner['contact_person'] ?: 'P', 0, 1)); ?>
  </div>
  <div style="flex:1;min-width:0;">
    <div class="partner-hero-name"><?php echo h($partner['company_name'] ?: $partner['contact_person']); ?></div>
    <div class="partner-hero-sub">
      <?php echo h($partner['contact_person'] ?? ''); ?>
      <?php if ($partner['specialty']): ?> · <?php echo h($partner['specialty']); ?><?php endif; ?>
      <?php if ($partner['phone']): ?> · 📞 <?php echo h($partner['phone']); ?><?php endif; ?>
      <?php if ($partner['city']): ?> · 📍 <?php echo h($partner['city']); ?><?php endif; ?>
    </div>
  </div>
  <div style="display:flex;gap:8px;flex-shrink:0;">
    <a class="btn btn-sm" href="/gopools/public/partners/edit.php?id=<?php echo $id; ?>"
      style="background:rgba(255,255,255,.15);color:#fff;border-color:rgba(255,255,255,.3);">✏️ Επεξεργασία</a>
    <a class="btn btn-sm" href="/gopools/public/partners/index.php"
      style="background:rgba(255,255,255,.1);color:#fff;border-color:rgba(255,255,255,.2);">← Πίσω</a>
  </div>
</div>

<?php if ($canViewCostings): ?>
<!-- Billing Summary -->
<div class="billing-cards">
  <div class="billing-card">
    <div class="billing-card-label">Σύνολο Εργων</div>
    <div class="billing-card-value"><?php echo count($allRows); ?></div>
  </div>
  <div class="billing-card" style="border-color:rgba(239,68,68,.2);">
    <div class="billing-card-label">Εκκρεμεί</div>
    <div class="billing-card-value" style="color:#ef4444;">€ <?php echo number_format($totalPending, 2); ?></div>
  </div>
  <div class="billing-card" style="border-color:rgba(16,185,129,.2);">
    <div class="billing-card-label">Εξοφλήθηκε</div>
    <div class="billing-card-value" style="color:#10b981;">€ <?php echo number_format($totalPaid, 2); ?></div>
  </div>
  <div class="billing-card" style="border-color:rgba(37,99,235,.2);">
    <div class="billing-card-label">Συνολικό Ποσό</div>
    <div class="billing-card-value" style="color:var(--gp-primary);">€ <?php echo number_format($totalAgreed, 2); ?></div>
  </div>
</div>
<?php endif; ?>

<!-- Tabs -->
<div class="card">
  <div class="tab-bar">
    <a class="tab-btn <?php echo $activeTab === 'pending' ? 'active' : ''; ?>"
       href="?id=<?php echo $id; ?>&tab=pending">
      ⚡ Εκκρεμείς<span class="tab-count"><?php echo count($pendingRows); ?></span>
    </a>
    <a class="tab-btn <?php echo $activeTab === 'paid' ? 'active' : ''; ?>"
       href="?id=<?php echo $id; ?>&tab=paid">
      ✅ Εξοφλήθηκαν<span class="tab-count"><?php echo count($paidRows); ?></span>
    </a>
    <a class="tab-btn <?php echo $activeTab === 'all' ? 'active' : ''; ?>"
       href="?id=<?php echo $id; ?>&tab=all">
      📋 Όλα<span class="tab-count"><?php echo count($allRows); ?></span>
    </a>
  </div>

  <?php
  $displayRows = match($activeTab) {
      'paid'    => $paidRows,
      'all'     => $allRows,
      default   => $pendingRows,
  };
  ?>

  <?php if (empty($displayRows)): ?>
  <div style="text-align:center;padding:40px;color:var(--gp-muted);">
    <?php echo $activeTab === 'pending' ? '✅ Δεν υπάρχουν εκκρεμείς χρεώσεις!' : '— Δεν υπάρχουν εγγραφές —'; ?>
  </div>
  <?php else: ?>
  <div class="table-responsive">
    <table class="table">
      <thead>
        <tr>
          <th>Έργο</th>
          <th>Ημ. Εργασίας</th>
          <th>Περιγραφή</th>
          <?php if ($canViewCostings): ?>
          <th>Συμφωνηθέν</th>
          <?php if ($activeTab === 'paid' || $activeTab === 'all'): ?>
          <th>Πληρώθηκε</th>
          <th>Ημ. Εξόφλησης</th>
          <?php endif; ?>
          <?php endif; ?>
          <th>Status</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($displayRows as $r):
          $statusColor = $statusColors[$r['status']] ?? '#6b7280';
          $statusLabel = $statusLabels[$r['status']] ?? $r['status'];
        ?>
        <tr class="job-row">
          <td>
            <a href="/gopools/public/projects/view.php?id=<?php echo (int)$r['project_id']; ?>"
               style="font-weight:700;color:var(--gp-primary);text-decoration:none;font-size:.88rem;"
               title="Άνοιγμα έργου">
              <?php echo h($r['code'] ?? ''); ?>
            </a>
            <div style="font-size:.78rem;color:var(--gp-muted);"><?php echo h($r['project_title'] ?? ''); ?></div>
            <?php if ($r['project_city']): ?>
            <div style="font-size:.72rem;color:var(--gp-muted);">📍 <?php echo h($r['project_city']); ?></div>
            <?php endif; ?>
          </td>
          <td style="font-size:.85rem;white-space:nowrap;"><?php echo $r['work_date'] ? gp_date($r['work_date']) : '—'; ?></td>
          <td style="font-size:.83rem;max-width:200px;"><?php echo h($r['description'] ?? ''); ?></td>
          <?php if ($canViewCostings): ?>
          <td style="font-weight:700;">
            <?php if ($r['agreed_cost'] !== null && $r['agreed_cost'] !== ''): ?>
              € <?php echo number_format((float)$r['agreed_cost'], 2); ?>
              <?php if (!empty($r['quote_amount'])): ?>
                <div style="font-size:0.68rem; color:var(--gp-muted); margin-top:2px;">Quote: € <?php echo number_format((float)$r['quote_amount'], 2); ?></div>
              <?php endif; ?>
            <?php else: ?>
              <a href="/gopools/public/projects/partners.php?project_id=<?php echo (int)$r['project_id']; ?>" style="font-size:0.75rem; color:#f59e0b; text-decoration:none; border:1px solid rgba(245,158,11,0.5); padding:2px 6px; border-radius:6px; background:rgba(245,158,11,0.1);">✏️ Προσθήκη</a>
              <?php if (!empty($r['quote_amount'])): ?>
                <div style="font-size:0.7rem; color:var(--gp-primary); margin-top:4px; font-weight:800;">Quote: € <?php echo number_format((float)$r['quote_amount'], 2); ?></div>
              <?php endif; ?>
            <?php endif; ?>
          </td>
          <?php if ($activeTab === 'paid' || $activeTab === 'all'): ?>
          <td style="color:#10b981;font-weight:700;">
            <?php echo $r['paid_amount'] ? '€ ' . number_format((float)$r['paid_amount'], 2) : '—'; ?>
          </td>
          <td style="font-size:.83rem;white-space:nowrap;">
            <?php echo (!empty($r['paid_date']) && $r['paid_date'] !== '0000-00-00') ? gp_date($r['paid_date']) : '—'; ?>
          </td>
          <?php endif; ?>
          <?php endif; ?>
          <td>
            <span class="status-pill" style="background:<?php echo $statusColor; ?>1a;color:<?php echo $statusColor; ?>;border:1px solid <?php echo $statusColor; ?>33;">
              <?php echo h($statusLabel); ?>
            </span>
          </td>
          <td>
            <a href="/gopools/public/projects/view.php?id=<?php echo (int)$r['project_id']; ?>"
               class="btn btn-sm btn-outline-light" style="font-size:.75rem;">Έργο →</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
      <?php if ($canViewCostings && count($displayRows) > 1): ?>
      <tfoot>
        <tr style="background:var(--gp-nav-bg-2);font-weight:700;">
          <td colspan="3" style="font-size:.82rem;color:var(--gp-muted);">Σύνολο (<?php echo count($displayRows); ?> εγγραφές)</td>
          <td>€ <?php echo number_format(array_sum(array_map(fn($r) => (float)(is_numeric($r['agreed_cost'] ?? null) ? $r['agreed_cost'] : ($r['quote_amount'] ?? 0)), iterator_to_array(new ArrayIterator($displayRows)))), 2); ?></td>
          <?php if ($activeTab === 'paid' || $activeTab === 'all'): ?>
          <td style="color:#10b981;">€ <?php echo number_format(array_sum(array_map($getPaid, iterator_to_array(new ArrayIterator($displayRows)))), 2); ?></td>
          <td></td>
          <?php endif; ?>
          <td colspan="2"></td>
        </tr>
      </tfoot>
      <?php endif; ?>
    </table>
  </div>
  <?php endif; ?>
</div>

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