<?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 = '?e?t????';

$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/my_jobs.php?partner_id=<?php echo (int)$p['id']; ?>">Open portal</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.*, p.title, p.code, p.address, p.city, p.notes AS project_notes,
           p.start_date, p.end_date_planned, p.end_date_actual,
           c.name AS customer_name, c.phone AS customer_phone
    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.assigned_date ASC, pa.assigned_time ASC, pa.id DESC
");
$stmt->execute([':partner_id' => $partnerId]);
$rows = $stmt->fetchAll();

// ── Load billing / charges for this partner (from project_partners table) ──
$billingStmt = $pdo->prepare("
    SELECT
        pp.*,
        p.id AS project_id,
        p.code,
        p.title AS project_title,
        p.status AS project_status,
        p.city AS project_city
    FROM project_partners pp
    LEFT JOIN projects p ON p.id = pp.project_id
    WHERE pp.external_partner_id = :partner_id
    ORDER BY pp.status ASC, pp.work_date DESC
");
$billingStmt->execute([':partner_id' => $partnerId]);
$billingRows = $billingStmt->fetchAll();

$billingPending = array_filter($billingRows, fn($r) => $r['status'] !== 'paid' && $r['status'] !== 'cancelled');
$billingPaid    = array_filter($billingRows, fn($r) => $r['status'] === 'paid');
$totalAgreed    = array_sum(array_column($billingRows, 'agreed_cost'));
$totalPaid      = array_sum(array_column($billingPaid, 'paid_amount'));
$totalPending   = array_sum(array_column($billingPending, 'agreed_cost'));

// Load existing suggestions per project for this user
$mySuggestions = [];
$myPhotos = [];
$myMissingParts = [];

if ($rows) {
    $pids = array_unique(array_column($rows, 'project_id'));
    $in   = implode(',', array_fill(0, count($pids), '?'));
    $ss   = $pdo->prepare("SELECT project_id, proposed_start_date, proposed_end_date, proposed_days, status, created_at FROM project_duration_suggestions WHERE project_id IN ($in) AND suggested_by_user_id = ? ORDER BY id DESC");
    $ss->execute([...$pids, (int)(auth_user()['id'] ?? 0)]);
    foreach ($ss->fetchAll() as $sg) {
        $mySuggestions[$sg['project_id']] = $sg;
    }

    // Load all partner-uploaded photos per project (not just current user)
    $ps = $pdo->prepare("SELECT project_id, id, category, filename, original_name, created_at FROM project_photos WHERE project_id IN ($in) AND uploaded_by_type = 'partner' ORDER BY id DESC");
    $ps->execute($pids);
    foreach ($ps->fetchAll() as $photo) {
        $myPhotos[$photo['project_id']][] = $photo;
    }

    // Load shared customer photos
    $customerPhotos = [];
    $cp = $pdo->prepare("SELECT project_id, id, category, title, filename, created_at FROM project_photos WHERE project_id IN ($in) AND uploaded_by_user_id != ? AND shared_with_crew = 1 ORDER BY id DESC");
    $cp->execute([...$pids, (int)(auth_user()['id'] ?? 0)]);
    foreach ($cp->fetchAll() as $photo) {
        $customerPhotos[$photo['project_id']][] = $photo;
    }

    // Load existing missing part requests
    $mp = $pdo->prepare("SELECT project_id, id, part_description, photo_filename, status, tracking_number, created_at FROM project_missing_parts WHERE project_id IN ($in) AND requested_by_user_id = ? ORDER BY id DESC");
    $mp->execute([...$pids, (int)(auth_user()['id'] ?? 0)]);
    foreach ($mp->fetchAll() as $part) {
        $myMissingParts[$part['project_id']][] = $part;
    }
}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Partner Portal</h1>
    <span><?php echo auth_is_admin_like() ? 'Admin view' : 'Ανατεθειμένα έργα'; ?></span>
  </div>
</div>

<script>
// --- GP GLOBAL HELPERS ---
window.gp_delete_offer = function(btn, aid, csrf) {
  if (btn.dataset.confirmed !== 'true') {
    btn.dataset.confirmed = 'true';
    btn.textContent = 'Είστε σίγουρος;';
    btn.style.background = '#000';
    setTimeout(function() { 
      if (btn) { btn.dataset.confirmed = 'false'; btn.textContent = '🗑 Delete'; btn.style.background = '#ef4444'; }
    }, 4000);
    return;
  }
  btn.disabled = true; btn.textContent = '...';
  fetch('/gopools/public/api/delete_assignment_offer.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: 'assignment_id=' + encodeURIComponent(aid) + '&csrf_token=' + encodeURIComponent(csrf)
  })
  .then(function(r) { return r.json(); })
  .then(function(res) {
    if (res.ok) {
      var row = btn.closest('.offer-uploaded-container');
      if (row) row.remove(); else window.location.reload();
    } else {
      alert('Error: ' + res.error);
      btn.disabled = false; btn.textContent = '🗑 Delete'; btn.dataset.confirmed = 'false';
    }
  })
  .catch(function(err) {
    alert('Network error');
    btn.disabled = false; btn.textContent = '🗑 Delete'; btn.dataset.confirmed = 'false';
  });
};
window.gp_complete_assignment = function(btn, aid, csrf) {
  if (btn.dataset.confirmed !== 'true') {
    btn.dataset.confirmed = 'true';
    btn.textContent = 'Confirm?';
    setTimeout(() => { if(btn){btn.dataset.confirmed='false'; btn.textContent='Complete Assignment';} }, 4000);
    return;
  }
  btn.disabled = true; btn.textContent = '...';
  var fd = new FormData(); fd.append('assignment_id', aid); fd.append('csrf_token', csrf);
  fetch('/gopools/public/api/complete_assignment.php', { method: 'POST', body: fd })
    .then(r => r.json()).then(res => {
      if (res.ok) { window.location.reload(); }
      else { alert('Error: ' + res.error); btn.disabled = false; btn.textContent = 'Complete Assignment'; }
    }).catch(err => { console.error(err); btn.disabled = false; });
};
</script>

<?php if ($billingRows): ?>
<!-- ══ Billing Summary ══ -->
<style>
.my-billing-section { margin-bottom: 24px; }
.my-billing-header {
  display: flex; align-items: center; justify-content: space-between;
  margin-bottom: 12px; flex-wrap: wrap; gap: 8px;
}
.my-billing-title { font-size: 1.1rem; font-weight: 800; display: flex; align-items: center; gap: 8px; }
.my-billing-cards { display: grid; grid-template-columns: repeat(3,1fr); gap: 10px; margin-bottom: 14px; }
.my-billing-card {
  background: var(--gp-card-bg); border: 1px solid var(--gp-card-border);
  border-radius: 14px; padding: 14px 16px;
}
.my-billing-label { font-size: .68rem; font-weight: 700; text-transform: uppercase; letter-spacing: .07em; color: var(--gp-muted); }
.my-billing-value { font-size: 1.35rem; font-weight: 800; margin-top: 4px; }
.billing-status-pill {
  display: inline-flex; align-items: center; gap: 4px;
  padding: 3px 8px; border-radius: 999px; font-size: .7rem; font-weight: 700;
}
@media(max-width:480px) { .my-billing-cards { grid-template-columns: 1fr 1fr; } }
</style>

<div class="my-billing-section">
  <div class="my-billing-header">
    <div class="my-billing-title">💰 Ενεργές Χρεώσεις</div>
    <span style="font-size:.78rem;color:var(--gp-muted);"><?php echo count($billingPending); ?> εκκρεμείς</span>
  </div>

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

  <!-- Charges table -->
  <div class="card" style="padding:0;overflow:hidden;">
    <div class="table-responsive">
      <table class="table" style="margin:0;">
        <thead>
          <tr>
            <th>Έργο</th>
            <th>Ημ. Εργασίας</th>
            <th>Περιγραφή</th>
            <th>Συμφωνηθέν</th>
            <th>Εξοφλήθηκε</th>
            <th>Ημ. Εξόφλησης</th>
            <th>Κατάσταση</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($billingPending as $b):
            $isPaid = ($b['status'] === 'paid');
            $statusColor = match($b['status']) {
              'paid'     => '#10b981',
              'working'  => '#f59e0b',
              'done'     => '#3b82f6',
              'cancelled'=> '#ef4444',
              default    => '#8b5cf6',
            };
            $statusLabel = match($b['status']) {
              'paid'     => '✅ Εξοφλήθηκε',
              'working'  => '🔧 Σε εξέλιξη',
              'done'     => '☑️ Ολοκληρώθηκε',
              'cancelled'=> '❌ Ακυρώθηκε',
              'planned'  => '📅 Προγραμματισμένο',
              default    => h($b['status']),
            };
          ?>
          <tr style="<?php echo !$isPaid && $b['status'] !== 'cancelled' ? 'background:rgba(239,68,68,0.02);' : ''; ?>">
            <td>
              <div style="font-weight:700;font-size:.85rem;"><?php echo h($b['code'] ?? '—'); ?></div>
              <div style="font-size:.72rem;color:var(--gp-muted);"><?php echo h($b['project_title'] ?? ''); ?></div>
              <?php if ($b['project_city']): ?>
              <div style="font-size:.68rem;color:var(--gp-muted);">📍<?php echo h($b['project_city']); ?></div>
              <?php endif; ?>
            </td>
            <td style="font-size:.82rem;white-space:nowrap;"><?php echo !empty($b['work_date']) ? gp_date($b['work_date']) : '—'; ?></td>
            <td style="font-size:.8rem;max-width:160px;color:var(--gp-muted);"><?php echo h($b['description'] ?? ''); ?></td>
            <td style="font-weight:800;font-size:.9rem;">€ <?php echo number_format((float)($b['agreed_cost'] ?? 0), 2); ?></td>
            <td style="color:#10b981;font-weight:700;font-size:.88rem;">
              <?php echo $b['paid_amount'] ? '€ ' . number_format((float)$b['paid_amount'], 2) : '—'; ?>
            </td>
            <td style="font-size:.8rem;white-space:nowrap;">
              <?php echo (!empty($b['paid_date']) && $b['paid_date'] !== '0000-00-00') ? gp_date($b['paid_date']) : '—'; ?>
            </td>
            <td>
              <span class="billing-status-pill" style="background:<?php echo $statusColor; ?>1a;color:<?php echo $statusColor; ?>;border:1px solid <?php echo $statusColor; ?>33;">
                <?php echo $statusLabel; ?>
              </span>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
        <?php if (count($billingPending) > 1): ?>
        <tfoot>
          <tr style="background:var(--gp-nav-bg-2);font-weight:700;font-size:.85rem;">
            <td colspan="3" style="color:var(--gp-muted);">Σύνολο</td>
            <td>€ <?php echo number_format($totalAgreed, 2); ?></td>
            <td style="color:#10b981;">€ <?php echo number_format($totalPaid, 2); ?></td>
            <td colspan="2" style="color:#ef4444;">Εκκρεμεί: € <?php echo number_format($totalPending, 2); ?></td>
          </tr>
        </tfoot>
        <?php endif; ?>
      </table>
    </div>
  </div>
</div>
<?php endif; ?>

<div class="card" style="margin-bottom:24px">
  <div class="page-header-title" style="margin-bottom:20px;">
    <h1 style="font-size:1.4rem">My Schedule</h1>
    <span>Your assigned jobs on the calendar</span>
  </div>
  <div id="job-calendar"></div>
</div>

<style>
.job-accordion{display:flex;flex-direction:column;gap:8px;}
.job-item{background:var(--gp-card-bg);border:1px solid var(--gp-card-border);border-radius:14px;overflow:hidden;transition:box-shadow .18s;}
.job-item:hover{box-shadow:0 4px 18px rgba(0,0,0,.08);}
.job-item-header{display:flex;align-items:center;gap:12px;padding:14px 18px;cursor:pointer;user-select:none;border-left:4px solid var(--jsc,var(--gp-primary));}
.job-item-header:hover{background:var(--gp-nav-bg-2);}
.job-sdot{width:10px;height:10px;border-radius:50%;flex-shrink:0;background:var(--jsc,var(--gp-primary));}
.job-main{flex:1;min-width:0;}
.job-title{font-weight:700;font-size:.95rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.job-meta{font-size:.75rem;color:var(--gp-muted);display:flex;flex-wrap:wrap;gap:8px;margin-top:3px;}
.job-badges{display:flex;gap:6px;flex-shrink:0;flex-wrap:wrap;align-items:center;}
.job-badge{padding:3px 9px;border-radius:999px;font-size:.68rem;font-weight:700;border:1px solid transparent;}
.job-chevron{font-size:.8rem;color:var(--gp-muted);flex-shrink:0;transition:transform .2s;}
.job-body{display:none;padding:0 18px 16px;border-top:1px solid var(--gp-card-border);}
.job-item.open .job-body{display:block;}
.job-item.open .job-chevron{transform:rotate(180deg);}
.job-ig{display:grid;grid-template-columns:1fr 1fr;gap:6px 16px;margin:12px 0 8px;font-size:.83rem;}
.job-il{color:var(--gp-muted);font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.05em;}
.job-iv{font-weight:600;}
@media(max-width:600px){.job-ig{grid-template-columns:1fr}}
</style>

<?php if (!$rows): ?>
  <div class="card"><p class="small">Δεν υπάρχουν ανατεθειμένα έργα.</p></div>
<?php else: ?>
  <div class="job-accordion">
    <?php foreach ($rows as $r):
      $durText = '';
      if (!empty($r['start_date']) && !empty($r['end_date_planned'])) {
          $d1 = new DateTime($r['start_date']);
          $d2 = new DateTime($r['end_date_planned']);
          $durDays = (int)$d1->diff($d2)->days;
          $durText = gp_date($r['start_date']) . ' → ' . gp_date($r['end_date_planned']) . ' (' . $durDays . ' ημ.)'; 
      } elseif (!empty($r['start_date'])) {
          $durText = 'Έναρξη: ' . gp_date($r['start_date']);
      }
      $existingSuggestion = $mySuggestions[$r['project_id']] ?? null;
      $jobPhotos = $myPhotos[$r['project_id']] ?? [];
      $jsc = match($r['status']) {
        'working'   => '#f59e0b',
        'done'      => '#3b82f6',
        'cancelled' => '#ef4444',
        'planned'   => '#8b5cf6',
        default     => '#10b981',
      };
      $jsl = match($r['status']) {
        'working'   => '🔧 Σε εξέλιξη',
        'done'      => '☑️ Ολοκληρώθηκε',
        'cancelled' => '❌ Ακυρώθηκε',
        'planned'   => '📅 Προγραμματισμένο',
        default     => h($r['status']),
      };
    ?>
    <div class="job-item" style="--jsc:<?php echo $jsc; ?>">
      <div class="job-item-header" onclick="this.closest('.job-item').classList.toggle('open')">
        <div class="job-sdot"></div>
        <div class="job-main">
          <div class="job-title"><?php echo h($r['title']); ?></div>
          <div class="job-meta">
            <span>📋 <?php echo h($r['code']); ?></span>
            <?php if ($r['customer_name']): ?><span>👤 <?php echo h($r['customer_name']); ?></span><?php endif; ?>
            <?php if ($r['city']): ?><span>📍 <?php echo h($r['city']); ?></span><?php endif; ?>
            <?php if ($durText): ?><span>📅 <?php echo h($durText); ?></span><?php endif; ?>
          </div>
        </div>
        <div class="job-badges">
          <span class="job-badge" style="background:<?php echo $jsc; ?>1a;color:<?php echo $jsc; ?>;border-color:<?php echo $jsc; ?>44;"><?php echo $jsl; ?></span>
          <?php if (count($jobPhotos) > 0): ?>
          <span class="job-badge" style="background:rgba(37,99,235,.1);color:var(--gp-primary);border-color:rgba(37,99,235,.2);">📸 <?php echo count($jobPhotos); ?></span>
          <?php endif; ?>
        </div>
        <span class="job-chevron">▼</span>
      </div>
      <div class="job-body">
        <div class="job-ig">
          <div><div class="job-il">Πελάτης</div><div class="job-iv"><?php echo h($r['customer_name'] ?? '—'); ?></div></div>
          <div><div class="job-il">Τηλέφωνο</div><div class="job-iv"><a href="tel:<?php echo h($r['customer_phone'] ?? ''); ?>"><?php echo h($r['customer_phone'] ?? '—'); ?></a></div></div>
          <div><div class="job-il">Διεύθυνση</div><div class="job-iv"><?php echo h(trim(($r['address'] ?? '') . ' ' . ($r['city'] ?? ''))); ?></div></div>
          <div><div class="job-il">Ρόλος</div><div class="job-iv"><?php echo h($r['role_label'] ?? '—'); ?></div></div>
          <?php if ($durText): ?><div><div class="job-il">Διάρκεια</div><div class="job-iv"><?php echo h($durText); ?></div></div><?php endif; ?>
        </div>

        <?php if (!empty($r['project_notes'])): ?>
        <div style="background:var(--gp-card-bg);border-left:3px solid var(--gp-primary);padding:.5rem;margin:.5rem 0;font-size:.85rem;border-radius:0 4px 4px 0;">
          <strong>Project Notes:</strong><br>
          <span style="white-space:pre-wrap;"><?php echo h($r['project_notes']); ?></span>
        </div>
        <?php endif; ?>

        <?php if (!empty($r['notes'])): ?>
        <div style="background:rgba(245,158,11,0.1);border-left:3px solid #f59e0b;padding:.5rem;margin:.5rem 0;font-size:.85rem;border-radius:0 4px 4px 0;">
          <strong>Assignment Notes:</strong><br>
          <span style="white-space:pre-wrap;"><?php echo h($r['notes']); ?></span>
        </div>
        <?php endif; ?>

        <?php $customerShared = $customerPhotos[$r['project_id']] ?? []; if ($customerShared): ?>
          <div style="margin-top:1rem;padding-top:1rem;border-top:1px solid var(--gp-card-border);">
            <div style="font-size:.9rem;font-weight:700;margin-bottom:8px;color:var(--gp-primary)">📸 Shared Photos</div>
            <div style="display:flex;flex-wrap:wrap;gap:8px;">
              <?php foreach ($customerShared as $csp): ?>
                <div style="border:1px solid var(--gp-card-border);border-radius:6px;overflow:hidden;background:var(--gp-nav-bg-2);">
                  <a href="<?php echo gp_upload_url('photos', $csp['filename']); ?>" target="_blank">
                    <img src="<?php echo gp_upload_url('photos', $csp['filename']); ?>" style="width:120px;height:90px;object-fit:cover;display:block;">
                  </a>
                  <div style="padding:4px;font-size:.65rem;text-align:center;">
                    <div style="font-weight:700;color:var(--gp-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:110px;" title="<?php echo h($csp['category']); ?>"><?php echo h($csp['category']); ?></div>
                    <?php if (!empty($csp['title'])): ?>
                      <div style="color:var(--gp-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:110px;" title="<?php echo h($csp['title']); ?>"><?php echo h($csp['title']); ?></div>
                    <?php endif; ?>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          </div>
        <?php endif; ?>

        <!-- Duration -->
        <div class="duration-block">
          <div class="duration-label">⏱ Duration</div>
          <?php if ($durText): ?>
            <div class="duration-value"><?php echo h($durText); ?></div>
          <?php else: ?>
            <div class="duration-value" style="color:var(--gp-muted)">Not set by admin</div>
          <?php endif; ?>
        </div>

        <!-- Existing suggestion status -->
        <?php if ($existingSuggestion && $existingSuggestion['status'] === 'pending'): ?>
          <div class="suggest-sent">
            📤 Suggestion sent:
            <?php
              $sugParts = [];
              if (!empty($existingSuggestion['proposed_start_date'])) $sugParts[] = gp_date($existingSuggestion['proposed_start_date']);
              if (!empty($existingSuggestion['proposed_end_date']))   $sugParts[] = '→ ' . gp_date($existingSuggestion['proposed_end_date']);
              if (!empty($existingSuggestion['proposed_days']))       $sugParts[] = '(' . (int)$existingSuggestion['proposed_days'] . ' days)';
              echo implode(' ', $sugParts);
            ?>
            <span class="suggest-badge pending">Pending review</span>
          </div>
        <?php elseif ($existingSuggestion && $existingSuggestion['status'] === 'accepted'): ?>
          <div class="suggest-sent" style="color:var(--gp-success,#16a34a)">✅ Your suggestion was accepted!</div>
        <?php elseif ($existingSuggestion && $existingSuggestion['status'] === 'rejected'): ?>
          <div class="suggest-sent" style="color:#dc2626">❌ Suggestion rejected. You may submit a new one.</div>
        <?php endif; ?>

        <!-- Suggestion form -->
        <?php if (!$existingSuggestion || $existingSuggestion['status'] === 'rejected'): ?>
        <details class="suggest-form-wrap">
          <summary>💡 Suggest a duration</summary>
          <form class="suggest-form" data-project="<?php echo (int)$r['project_id']; ?>" data-assignment="<?php echo (int)$r['id']; ?>">
            <?php echo csrf_field(); ?>
            <input type="hidden" name="assignment_id" value="<?php echo (int)$r['id']; ?>">
                <input type="hidden" name="by_type" value="partner">
            <div class="form-group" style="margin-top:.75rem">
              <label>Proposed start date</label>
              <input type="date" name="proposed_start_date" value="<?php echo h($r['start_date'] ?? ''); ?>">
            </div>
            <div class="form-group">
              <label>Proposed end date</label>
              <input type="date" name="proposed_end_date" value="<?php echo h($r['end_date_planned'] ?? ''); ?>">
            </div>
            <div class="form-group">
              <label>Notes / reason</label>
              <textarea name="notes" rows="2" placeholder="Explain the proposed timeline..."></textarea>
            </div>
            <div class="form-actions">
              <button type="submit" class="btn btn-sm btn-primary">Submit suggestion</button>
            </div>
            <div class="suggest-feedback" style="display:none"></div>
          </form>
        </details>
        <?php endif; ?>

        <!-- Photos -->
        <?php $jobPhotos = $myPhotos[$r['project_id']] ?? []; ?>
        <details class="suggest-form-wrap" style="margin-top:.5rem">
          <summary>📸 Upload Photos (<?php echo count($jobPhotos); ?>)</summary>
          <div style="padding-top:.75rem">
            
            <form class="photo-upload-form" data-project="<?php echo (int)$r['project_id']; ?>" data-assignment="<?php echo (int)$r['id']; ?>" enctype="multipart/form-data">
              <?php echo csrf_field(); ?>
              <input type="hidden" name="assignment_id" value="<?php echo (int)$r['id']; ?>">
                <input type="hidden" name="by_type" value="partner">
              <div style="display:flex;gap:.5rem;margin-bottom:.5rem;align-items:center;flex-wrap:wrap;">
                <select name="category" class="form-select" style="max-width:140px;font-size:.85rem;padding:.3rem .5rem" required>
                  <option value="pool">Πισίνα</option>
                  <option value="mechanical">Μηχανοστάσιο</option>
                </select>
                <input type="file" name="photo" accept="image/*" multiple required style="font-size:.85rem;flex:1">
                <button type="submit" class="btn btn-sm btn-primary">Upload</button>
              </div>
              <div class="photo-feedback" style="display:none;font-size:.8rem;font-weight:600;margin-bottom:.5rem;"></div>
            </form>

            <?php if ($jobPhotos): ?>
              <div class="photo-gallery" style="display:flex;gap:.5rem;overflow-x:auto;padding-bottom:.5rem;flex-wrap:wrap;">
                <?php foreach ($jobPhotos as $ph): ?>
                  <div style="position:relative;flex-shrink:0;">
                    <a href="<?php echo gp_upload_url('project_photos', $ph['filename']); ?>" target="_blank">
                      <img src="<?php echo gp_upload_url('project_photos', $ph['filename']); ?>" style="width:80px;height:80px;object-fit:cover;border-radius:8px;border:1px solid var(--gp-card-border);" onerror="this.style.display='none'">
                    </a>
                    <span style="position:absolute;bottom:0;left:0;right:0;background:rgba(0,0,0,0.6);color:#fff;font-size:.6rem;text-align:center;border-radius:0 0 8px 8px;padding:2px 0;">
                      <?php echo $ph['category'] === 'pool' ? 'Πισίνα' : 'Μηχ/σιο'; ?>
                    </span>
                  </div>
                <?php endforeach; ?>
              </div>
            <?php else: ?>
              <p class="small text-muted" style="margin:0">Δεν έχουν ανεβαστεί φωτογραφίες ακόμα.</p>
            <?php endif; ?>
          </div>
        </details>

        <!-- Missing Parts Request -->
        <?php $missParts = $myMissingParts[$r['project_id']] ?? []; ?>
        <details class="suggest-form-wrap" style="margin-top:.5rem">
          <summary>📦 Request Missing Part / Tool</summary>
          <div style="padding-top:.75rem">
            <form class="missing-part-form" data-project="<?php echo (int)$r['project_id']; ?>" data-assignment="<?php echo (int)$r['id']; ?>">
              <?php echo csrf_field(); ?>
              <input type="hidden" name="assignment_id" value="<?php echo (int)$r['id']; ?>">
                <input type="hidden" name="by_type" value="partner">
              <div class="form-group" style="margin-bottom:.5rem;">
                <label>What's missing?</label>
                <textarea name="part_description" rows="2" placeholder="Explain what part or tool you need..." required></textarea>
                <input type="file" name="photo" accept="image/*" style="margin-top:.5rem;font-size:.8rem;max-width:100%;">
              </div>
              <button type="submit" class="btn btn-sm btn-primary">Send Request</button>
              <div class="missing-part-feedback" style="display:none;margin-top:.5rem;font-size:.8rem;font-weight:600;"></div>
            </form>

            <?php if ($missParts): ?>
              <div style="margin-top:1rem;border-top:1px solid var(--gp-border);padding-top:1rem;">
                <h4 style="font-size:.85rem;margin-bottom:.5rem;font-weight:700;">Previous Requests</h4>
                <?php foreach ($missParts as $mp): ?>
                  <div style="background:var(--gp-card-bg);border:1px solid var(--gp-border);border-radius:6px;padding:.5rem;margin-bottom:.5rem;font-size:.8rem;">
                    <div style="font-weight:600;margin-bottom:.25rem;">
                      <?php echo nl2br(h($mp['part_description'])); ?>
                      <?php if (!empty($mp['photo_filename'])): ?>
                        <div style="margin-top:.5rem;">
                          <a href="/gopools/public/uploads/missing_parts/<?php echo h($mp['photo_filename']); ?>" target="_blank">
                            <img src="/gopools/public/uploads/missing_parts/<?php echo h($mp['photo_filename']); ?>" style="max-height:80px;border-radius:4px;border:1px solid var(--gp-border);">
                          </a>
                        </div>
                      <?php endif; ?>
                    </div>
                    <div style="display:flex;justify-content:space-between;align-items:center;">
                      <span style="color:var(--gp-muted);font-size:.7rem;"><?php echo h(gp_date($mp['created_at'], true)); ?></span>
                      <?php if ($mp['status'] === 'pending'): ?>
                        <span style="background:#f59e0b;color:#fff;border-radius:4px;padding:2px 6px;font-size:.65rem;font-weight:700;">PENDING</span>
                      <?php else: ?>
                        <span style="background:#16a34a;color:#fff;border-radius:4px;padding:2px 6px;font-size:.65rem;font-weight:700;">SENT</span>
                      <?php endif; ?>
                    </div>
                    <?php if ($mp['status'] === 'sent' && !empty($mp['tracking_number'])): ?>
                      <div style="margin-top:.5rem;padding:.5rem;background:rgba(22,163,74,0.1);border-radius:4px;border-left:3px solid #16a34a;">
                        <strong>Tracking Number:</strong> <br><?php echo h($mp['tracking_number']); ?>
                      </div>
                    <?php endif; ?>
                  </div>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>
        </details>

        <?php
          $quote = null;
          try {
              $qs = $pdo->prepare("SELECT quote_amount, status, updated_at FROM partner_project_costings WHERE project_id = :pid AND external_partner_id = :partner_id LIMIT 1");
              $qs->execute([':pid' => (int)$r['project_id'], ':partner_id' => (int)$partnerId]);
              $quote = $qs->fetch();
          } catch (Throwable $e) {}
        ?>
        <p><strong>My costing:</strong>
          <?php if ($quote): ?>
            € <?php echo h(number_format((float)($quote['quote_amount'] ?? 0), 2)); ?> · <?php echo h($quote['status'] ?? 'submitted'); ?>
          <?php else: ?>
            Not submitted
          <?php endif; ?>
        </p>

        <!-- Offer Document Upload -->
        <details class="suggest-form-wrap" style="margin-top:.5rem">
          <summary>📄 Προσφορά / Offer Document</summary>
          <div style="padding-top:.75rem">
            <?php if (!empty($r['offer_filename'])): ?>
              <div class="offer-uploaded-container" style="margin-bottom:10px;padding:8px 12px;background:rgba(16,185,129,0.1);border:1px solid rgba(16,185,129,0.3);border-radius:6px;font-size:0.85rem;display:flex;align-items:center;justify-content:space-between;gap:8px;">
                <span><strong>&#x2705; Uploaded:</strong> <a href="/gopools/public/uploads/project_offers/<?php echo h($r['offer_filename']); ?>" target="_blank" style="font-weight:700;color:var(--gp-primary);"><?php echo h($r['offer_filename']); ?></a></span>
                <button class="delete-offer-btn" 
                        onclick="window.gp_delete_offer(this, '<?php echo (int)$r['id']; ?>', '<?php echo csrf_token(); ?>'); event.stopPropagation();" 
                        style="background:#ef4444;color:#fff;border:none;padding:3px 10px;border-radius:6px;font-size:.75rem;cursor:pointer;flex-shrink:0;">&#128465; Delete</button>
              </div>
            <?php else: ?>
              <form class="offer-upload-form" data-assignment="<?php echo (int)$r['id']; ?>" enctype="multipart/form-data">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="assignment_id" value="<?php echo (int)$r['id']; ?>">
                  <input type="hidden" name="by_type" value="partner">
                <div style="display:flex;gap:.5rem;align-items:center;flex-wrap:wrap;">
                  <input type="file" name="offer_file" accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png" required style="font-size:.85rem;flex:1;">
                  <button type="submit" class="btn btn-sm btn-primary">Upload Offer</button>
                </div>
                <div class="offer-feedback" style="display:none;margin-top:.5rem;font-size:.8rem;font-weight:600;"></div>
              </form>
            <?php endif; ?>
          </div>
        </details>

        <div class="form-actions" style="margin-top:16px;">
          <a class="btn btn-sm btn-outline-light" href="/gopools/public/partners/project_costing.php?project_id=<?php echo (int)$r['project_id']; ?><?php echo auth_is_admin_like() ? '&partner_id=' . (int)$partnerId : ''; ?>">My Costing</a>
          <?php if ($r['status'] !== 'completed'): ?>
            <button class="btn btn-sm btn-primary complete-assignment-btn" 
                    onclick="window.gp_complete_assignment(this, '<?php echo (int)$r['id']; ?>', '<?php echo csrf_token(); ?>'); event.stopPropagation();" 
                    data-assignment="<?php echo (int)$r['id']; ?>">Complete Assignment</button>
          <?php endif; ?>
        </div><!-- /form-actions -->
      </div><!-- /job-body -->
    </div><!-- /job-item -->
    <?php endforeach; ?>
  </div><!-- /job-accordion -->
<?php endif; ?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.17/index.global.min.css">
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.17/index.global.min.js"></script>
<script>
// --- DOMContentLoaded Handlers (Secondary) ---
document.addEventListener('DOMContentLoaded', function () {
  // ── Missing Part forms ────────────────────────────────────────────────────
  try {
    document.querySelectorAll('.missing-part-form').forEach(function(form) {
    form.addEventListener('submit', function(e) {
      e.preventDefault();
      var fb = form.querySelector('.missing-part-feedback');
      var btn = form.querySelector('button[type=submit]');
      var data = new FormData(form);
      data.append('project_id', form.dataset.project);
      data.append('assignment_id', form.dataset.assignment);
      btn.disabled = true; btn.textContent = 'Sending...';
      fetch('/gopools/public/api/request_missing_part.php', {method:'POST', body: data})
        .then(r => r.json())
        .then(function(res) {
          fb.style.display = 'block';
          if (res.ok) {
            fb.textContent = '✅ Request sent to managers!';
            fb.style.color = 'var(--gp-success, #16a34a)';
            setTimeout(() => window.location.reload(), 1000);
          } else {
            fb.textContent = '❌ Error: ' + (res.error || 'Unknown error');
            fb.style.color = '#dc2626';
            btn.disabled = false; btn.textContent = 'Send Request';
          }
        })
        .catch(function() {
          fb.style.display = 'block';
          fb.textContent = '❌ Network error.';
          fb.style.color = '#dc2626';
          btn.disabled = false; btn.textContent = 'Send Request';
        });
    });
  });
  } catch(e) { console.warn('Missing parts handler failed:', e); }

  var calendarEl = document.getElementById('job-calendar');
  if (calendarEl) {
    try {
      var events = [
        <?php
          $palette = ['#3b82f6','#ef4444','#10b981','#f59e0b','#8b5cf6','#ec4899','#0ea5e9','#14b8a6','#f97316','#6366f1'];
          foreach ($rows as $r):
            $startDate = $r['start_date'] ?: $r['assigned_date'];
            $endDate = $r['end_date_planned'] ?: $startDate;
            $endExclusive = date('Y-m-d', strtotime($endDate . ' +1 day'));
            $weather = gp_get_weather_forecast($pdo, (string)$r['city'], $startDate);
        ?>
        {
          title: <?php echo json_encode(trim($r['title'] . ' - ' . $r['role_label'])); ?>,
          start: "<?php echo $startDate; ?>",
          end: "<?php echo $endExclusive; ?>",
          allDay: true,
          color: "<?php echo $palette[(int)$r['project_id'] % count($palette)]; ?>",
          extendedProps: {
            weather: <?php echo json_encode($weather); ?>
          }
        },
        <?php endforeach; ?>
      ];
      var calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        height: 'auto',
        events: events,
        eventContent: function(arg) {
          let weatherHtml = '';
          if (arg.event.extendedProps.weather) {
            const w = arg.event.extendedProps.weather;
            weatherHtml = `<span style="display:inline-flex; align-items:center; gap:4px; background:rgba(255,255,255,0.3); padding:2px 6px; border-radius:6px; margin-left:8px; font-size:0.85em; font-weight:700; color:white;">
              <img src="https://openweathermap.org/img/wn/${w.icon}.png" style="width:20px; height:20px;" alt="${w.description}">
              ${Math.round(w.temp)}°
            </span>`;
          }
          return {
            html: `<div style="display:flex; align-items:center; width:100%; overflow:hidden;">
              <div style="flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${arg.event.title}</div>
              ${weatherHtml}
            </div>`
          };
        }
      });
      calendar.render();
    } catch(calErr) {
      console.warn('Calendar init failed:', calErr);
    }
  }

  // Duration suggestion forms
  try {
    document.querySelectorAll('.suggest-form').forEach(function(form) {
    form.addEventListener('submit', function(e) {
      e.preventDefault();
      var fb = form.querySelector('.suggest-feedback');
      var btn = form.querySelector('button[type=submit]');
      var data = new FormData(form);
      data.append('project_id', form.dataset.project);
      data.append('assignment_id', form.dataset.assignment);
      btn.disabled = true; btn.textContent = 'Sending…';
      fetch('/gopools/public/api/duration_suggest.php', {method:'POST', body: data})
        .then(r => r.json())
        .then(function(res) {
          fb.style.display = 'block';
          if (res.ok) {
            fb.textContent = '✅ Suggestion submitted!';
            fb.style.color = 'var(--gp-success, #16a34a)';
            form.closest('details').querySelector('summary').textContent = '📤 Suggestion sent (pending review)';
            form.style.display = 'none';
          } else {
            fb.textContent = '❌ Error: ' + (res.error || 'Unknown error');
            fb.style.color = '#dc2626';
            btn.disabled = false; btn.textContent = 'Submit suggestion';
          }
        })
        .catch(function() {
          fb.style.display = 'block';
          btn.disabled = false; btn.textContent = 'Submit suggestion';
        });
    });
  });
  } catch(e) { console.warn('Suggestions handler failed:', e); }

  // Photo upload forms
  document.querySelectorAll('.photo-upload-form').forEach(function(form) {
    form.addEventListener('submit', async function(e) {
      e.preventDefault();
      var fb = form.querySelector('.photo-feedback');
      var btn = form.querySelector('button[type=submit]');
      var fileInput = form.querySelector('input[type=file]');
      var files = fileInput.files;
      if (!files || files.length === 0) return;
      var category = form.querySelector('select[name=category]').value;
      var byType = form.querySelector('input[name=by_type]').value;
      var csrfVal = form.querySelector('input[name=csrf_token]').value;
      btn.disabled = true; btn.textContent = '...';
      fb.style.display = 'block';
      var successCount = 0; var failCount = 0;
      for (var i = 0; i < files.length; i++) {
        fb.textContent = 'Ανέβασμα ' + (i + 1) + ' από ' + files.length + '...';
        fb.style.color = 'var(--gp-primary)';
        var fd = new FormData();
        fd.append('photo', files[i]);
        fd.append('category', category);
        fd.append('by_type', byType);
        fd.append('csrf_token', csrfVal);
        fd.append('project_id', form.dataset.project);
        fd.append('assignment_id', form.dataset.assignment);
        try {
          var res = await fetch('/gopools/public/api/upload_project_photo.php', {method:'POST', body: fd}).then(r => r.json());
          if (res.ok) successCount++;
          else { failCount++; }
        } catch(err) { failCount++; }
      }
      if (failCount === 0) {
        fb.textContent = '✅ ' + successCount + ' φωτογραφίες ανέβηκαν!';
        fb.style.color = 'var(--gp-success, #16a34a)';
        setTimeout(function() { window.location.reload(); }, 1000);
      } else {
        fb.textContent = '⚠️ ' + successCount + ' επιτυχία, ' + failCount + ' αποτυχία.';
        fb.style.color = '#f59e0b';
        btn.disabled = false; btn.textContent = 'Upload';
      }
    });
  });
  // Offer upload forms
  document.querySelectorAll('.offer-upload-form').forEach(function(form) {
    form.addEventListener('submit', function(e) {
      e.preventDefault();
      var fb = form.querySelector('.offer-feedback');
      var btn = form.querySelector('button[type=submit]');
      var fd = new FormData(form);
      fd.append('assignment_id', form.dataset.assignment);
      btn.disabled = true; btn.textContent = 'Uploading...';
      fetch('/gopools/public/api/upload_assignment_offer.php', { method: 'POST', body: fd })
        .then(r => r.json())
        .then(res => {
          fb.style.display = 'block';
          if (res.ok || res.status === 'success') {
            fb.textContent = '✅ Προσφορά ανεβάστηκε!';
            fb.style.color = 'var(--gp-success, #16a34a)';
            setTimeout(() => window.location.reload(), 1000);
          } else {
            fb.textContent = '❌ Error: ' + (res.error || res.message || 'Unknown error');
            fb.style.color = '#dc2626';
            btn.disabled = false; btn.textContent = 'Upload Offer';
          }
        })
        .catch(err => {
          fb.style.display = 'block';
          fb.textContent = '❌ Network error: ' + err;
          fb.style.color = '#dc2626';
          btn.disabled = false; btn.textContent = 'Upload Offer';
        });
    });
  });

  // (Handlers moved to top for stability)
});
</script>

<style>
.duration-block { margin:.75rem 0; padding:.6rem .9rem; background:color-mix(in srgb,var(--gp-primary,#2563eb) 8%,var(--gp-card-bg,#fff)); border-left:3px solid var(--gp-primary,#2563eb); border-radius:0 8px 8px 0; }
.duration-label { font-size:.72rem; font-weight:700; text-transform:uppercase; letter-spacing:.05em; color:var(--gp-primary,#2563eb); margin-bottom:.2rem; }
.duration-value { font-size:.88rem; font-weight:600; color:var(--gp-text,#1e293b); }
.suggest-form-wrap { margin-top:.75rem; border:1.5px dashed var(--gp-card-border,#e2e8f0); border-radius:8px; padding:.5rem .75rem; }
.suggest-form-wrap summary { cursor:pointer; font-size:.82rem; font-weight:600; color:var(--gp-muted,#64748b); user-select:none; }
.suggest-form-wrap[open] summary { color:var(--gp-primary,#2563eb); }
.suggest-sent { margin-top:.6rem; font-size:.82rem; font-weight:600; color:var(--gp-muted); display:flex; align-items:center; gap:.4rem; flex-wrap:wrap; }
.suggest-badge { font-size:.68rem; font-weight:700; text-transform:uppercase; border-radius:999px; padding:2px 8px; }
.suggest-badge.pending { background:#f59e0b; color:#fff; }
.suggest-feedback { margin-top:.5rem; font-size:.82rem; font-weight:600; border-radius:6px; padding:.4rem .6rem; }
</style>

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


