<?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 = 'Employee Portal';

$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/my_jobs.php?employee_id=<?php echo (int)$e['id']; ?>">??????a Portal</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.'); }

// Active assignments ?�� join through users to get correct employee_id
$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.employee_id = :employee_id AND pa.status != 'completed'
    ORDER BY pa.assigned_date ASC, pa.assigned_time ASC, pa.id DESC
");
$stmt->execute([':employee_id' => $employeeId]);
$rows = $stmt->fetchAll();

// Completed jobs count
$stmtDone = $pdo->prepare("SELECT COUNT(*) FROM project_assignments WHERE employee_id = :employee_id AND status = 'completed'");
$stmtDone->execute([':employee_id' => $employeeId]);
$completedJobs = (int)$stmtDone->fetchColumn();

// Load existing suggestions (pending) 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 existing uploaded photos per project for this 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_user_id = ? OR uploaded_by_type = 'employee') ORDER BY id DESC");
    $ps->execute([...$pids, (int)(auth_user()['id'] ?? 0)]);
    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_type = 'customer' AND shared_with_crew = 1 ORDER BY id DESC");
    $cp->execute($pids);
    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;
    }
}

$activeJobs = $rows;
$totalHours = 0;
$chartData = [];

foreach ($rows as $r) {
    // Calculate hours if started and stopped
    if (!empty($r['started_at']) && !empty($r['stopped_at'])) {
        $t1 = strtotime($r['started_at']);
        $t2 = strtotime($r['stopped_at']);
        $hours = round(($t2 - $t1) / 3600, 1);
        if ($hours > 0) {
            $totalHours += $hours;
            $chartData[] = [
                'title' => $r['title'],
                'hours' => $hours
            ];
        }
    }
}

include __DIR__ . '/../includes/header.php';
?>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<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, var(--gp-primary), #8b5cf6); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">Employee Portal</h1>
    <span style="color: var(--gp-muted); font-weight: 500; font-size: 0.95rem;"><?php echo auth_is_admin_like() ? 'Admin view' : 'My workspace'; ?></span>
  </div>
  <div class="page-header-actions" style="display: flex; gap: 12px;">
    <?php if (file_exists(__DIR__ . '/timeclock.php')): ?>
      <a class="btn" style="background: linear-gradient(135deg, #10b981, #059669); color: white; border: none; font-weight: 600; padding: 8px 16px; border-radius: 8px; box-shadow: 0 4px 12px rgba(16,185,129,0.3);" href="/gopools/public/employees/timeclock.php<?php echo auth_is_admin_like() ? '?employee_id=' . (int)$employeeId : ''; ?>">?��� Time Clock</a>
    <?php endif; ?>
  </div>
</div>

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

<!-- Statistics Section -->
<div class="grid-3" style="margin-bottom: 24px; gap: 20px;">
  <div class="card stat-card" style="background: rgba(255,255,255,0.03); backdrop-filter: blur(12px); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; padding: 20px; box-shadow: 0 8px 32px rgba(0,0,0,0.05);">
    <div style="font-size: 0.85rem; text-transform: uppercase; letter-spacing: 1px; color: var(--gp-muted); font-weight: 700;">Ενεργά Έργα</div>
    <div style="font-size: 2.5rem; font-weight: 800; color: #3b82f6; margin-top: 8px;"><?php echo count($activeJobs); ?></div>
  </div>
  <div class="card stat-card" style="background: rgba(255,255,255,0.03); backdrop-filter: blur(12px); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; padding: 20px; box-shadow: 0 8px 32px rgba(0,0,0,0.05);">
    <div style="font-size: 0.85rem; text-transform: uppercase; letter-spacing: 1px; color: var(--gp-muted); font-weight: 700;">Ολοκληρωμένα Έργα</div>
    <div style="font-size: 2.5rem; font-weight: 800; color: #10b981; margin-top: 8px;"><?php echo $completedJobs; ?></div>
  </div>
  <div class="card stat-card" style="background: rgba(255,255,255,0.03); backdrop-filter: blur(12px); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; padding: 20px; box-shadow: 0 8px 32px rgba(0,0,0,0.05);">
    <div style="font-size: 0.85rem; text-transform: uppercase; letter-spacing: 1px; color: var(--gp-muted); font-weight: 700;">Συνολικές Ώρες</div>
    <div style="font-size: 2.5rem; font-weight: 800; color: #f59e0b; margin-top: 8px;"><?php echo $totalHours; ?><span style="font-size: 1rem; color: var(--gp-muted);"> h</span></div>
  </div>
</div>

<?php if (count($chartData) > 0): ?>
<div class="card" style="margin-bottom: 24px; padding: 20px; border-radius: 16px; background: rgba(255,255,255,0.02); backdrop-filter: blur(12px); border: 1px solid rgba(255,255,255,0.05);">
  <h3 style="font-size: 1.1rem; font-weight: 700; margin-bottom: 16px;">⏱ Ώρες ανά Έργο</h3>
  <canvas id="hoursChart" height="80"></canvas>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('hoursChart').getContext('2d');
    const data = <?php echo json_encode($chartData); ?>;
    const labels = data.map(d => d.title.length > 25 ? d.title.substring(0, 25) + '...' : d.title);
    const hours = data.map(d => d.hours);

    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Συνολικές Ώρες',
                data: hours,
                backgroundColor: 'rgba(59, 130, 246, 0.6)',
                borderColor: 'rgba(59, 130, 246, 1)',
                borderWidth: 1,
                borderRadius: 4
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { display: false } },
            scales: { y: { beginAtZero: true } }
        }
    });
});
</script>
<?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>

<?php if (!$activeJobs): ?>
  <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: #10b981; font-weight: 700; margin: 0;">Δεν υπάρχουν ενεργά έργα!</h3>
    <p style="color: var(--gp-muted); font-size: 0.95rem; margin-top: 8px;">Όλα τα έργα σας έχουν ολοκληρωθεί.</p>
  </div>
<?php else: ?>
  <div class="grid-2">
    <?php foreach ($activeJobs as $r):
      // Calculate duration
      $durText = '';
      $durDays = null;
      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 . ' ' . ($durDays === 1 ? 'day' : 'days') . ')';
      } elseif (!empty($r['start_date'])) {
          $durText = 'Starts: ' . gp_date($r['start_date']);
      }
      $existingSuggestion = $mySuggestions[$r['project_id']] ?? null;
    ?>
      <div class="card premium-job-card" style="border-radius: 16px; overflow: hidden; position: relative; border: 1px solid var(--gp-card-border); transition: all 0.3s ease;">
        <!-- Status Ribbon -->
        <div style="position: absolute; top: 16px; right: 16px;">
          <?php if ($r['status'] === 'in_progress'): ?>
            <span style="background: rgba(59, 130, 246, 0.1); color: #3b82f6; padding: 4px 12px; border-radius: 20px; font-size: 0.75rem; font-weight: 700; border: 1px solid rgba(59, 130, 246, 0.2);">▶ In Progress</span>
          <?php else: ?>
            <span style="background: rgba(245, 158, 11, 0.1); color: #f59e0b; padding: 4px 12px; border-radius: 20px; font-size: 0.75rem; font-weight: 700; border: 1px solid rgba(245, 158, 11, 0.2);">⏳ Assigned</span>
          <?php endif; ?>
        </div>

        <div class="page-header-title" style="margin-bottom: 16px;">
          <h1 style="font-size:1.15rem; font-weight: 700; padding-right: 100px;"><?php echo h($r['title']); ?></h1>
          <span style="font-size: 0.8rem; color: var(--gp-muted);"><i class="fas fa-calendar-alt"></i> <?php echo h(gp_date((string)$r['assigned_date']) . ' ' . substr((string)$r['assigned_time'], 0, 5)); ?></span>
        </div>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 16px; font-size: 0.85rem;">
          <div style="background: var(--gp-nav-bg-2); padding: 10px; border-radius: 8px;">
            <div style="color: var(--gp-muted); font-size: 0.7rem; text-transform: uppercase; font-weight: 700; margin-bottom: 4px;">Κωδικός Έργου</div>
            <div style="font-weight: 600;"><?php echo h($r['code']); ?></div>
          </div>
          <div style="background: var(--gp-nav-bg-2); padding: 10px; border-radius: 8px;">
            <div style="color: var(--gp-muted); font-size: 0.7rem; text-transform: uppercase; font-weight: 700; margin-bottom: 4px;">Ρόλος</div>
            <div style="font-weight: 600; color: var(--gp-primary);"><?php echo h($r['role_label']); ?></div>
          </div>
          <div style="background: var(--gp-nav-bg-2); padding: 10px; border-radius: 8px; grid-column: 1 / -1;">
            <div style="color: var(--gp-muted); font-size: 0.7rem; text-transform: uppercase; font-weight: 700; margin-bottom: 4px;">Πελάτης</div>
            <div style="font-weight: 600; display: flex; justify-content: space-between;">
              <span>👤 <?php echo h($r['customer_name']); ?></span>
              <a href="tel:<?php echo h($r['customer_phone']); ?>" style="color: #10b981; text-decoration: none;">📞 <?php echo h($r['customer_phone']); ?></a>
            </div>
            <div style="margin-top: 4px; color: var(--gp-muted);">📍 <?php echo h(trim(($r['address'] ?? '') . ' ' . ($r['city'] ?? ''))); ?></div>
          </div>
        </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>Σημειώσεις Έργου:</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>Σημειώσεις Ανάθεσης:</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)">📸 Photos from Customer</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="/gopools/public/uploads/photos/<?php echo h($csp['filename']); ?>" target="_blank">
                    <img src="/gopools/public/uploads/photos/<?php echo h($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">⏱ Διάρκεια</div>
          <?php if ($durText): ?>
            <div class="duration-value"><?php echo h($durText); ?></div>
          <?php else: ?>
            <div class="duration-value" style="color:var(--gp-muted)">Δεν έχει οριστεί ακόμα</div>
          <?php endif; ?>
        </div>

        <!-- Suggest duration -->
        <?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; ?>

        <?php if (!$existingSuggestion || $existingSuggestion['status'] === 'rejected'): ?>
        <details class="suggest-form-wrap">
          <summary>📅 Πρότεινε Διάρκεια</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="by_type" value="employee">
            <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>✏️ Λεπτομέρειες / Check in</label>
              <textarea name="notes" rows="2" placeholder="Explain why you propose this timeline..."></textarea>
            </div>
            <div class="form-actions">
              <button type="submit" class="btn btn-sm btn-primary">Αποστολή Αιτήματος</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>📸 Ανέβασμα φωτογραφιών έργου (<?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="by_type" value="employee">
              <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">
                <?php foreach ($jobPhotos as $ph): ?>
                  <div style="position:relative;flex-shrink:0;">
                    <a href="/gopools/public/uploads/project_photos/<?php echo h($ph['filename']); ?>" target="_blank">
                      <img src="/gopools/public/uploads/project_photos/<?php echo h($ph['filename']); ?>" style="width:70px;height:70px;object-fit:cover;border-radius:6px;border:1px solid #ccc;">
                    </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 6px 6px;">
                      <?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>🛠 Αίτημα για ελλείποντα εξαρτήματα / αναλώσιμα</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="by_type" value="employee">
              <div class="form-group" style="margin-bottom:.5rem;">
                <label>Τι λείπει;</label>
                <textarea name="part_description" rows="2" placeholder="Εξηγήστε ποιο εξάρτημα/εργαλείο χρειάζεται..." 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">Αποστολή Αιτήματος</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;">Προηγούμενα Αιτήματα</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>Αριθμός Αποστολής:</strong> <br><?php echo h($mp['tracking_number']); ?>
                      </div>
                    <?php endif; ?>
                  </div>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>
        </details>

        <!-- Action Buttons -->
        <div style="margin-top: 20px; display: flex; gap: 10px; align-items: center; border-top: 1px solid var(--gp-card-border); padding-top: 16px;">
          <a href="/gopools/public/employees/job_action.php?assignment_id=<?php echo (int)$r['id']; ?>" class="btn btn-secondary" style="flex: 1; text-align: center; border-radius: 8px;">
            💼 Διαχείριση / Check in
          </a>
        </div>

      </div>
    <?php endforeach; ?>
  </div>
<?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>
document.addEventListener('DOMContentLoaded', function () {
  // Missing Part forms
  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 = 'Αποστολή Αιτήματος';
          }
        })
        .catch(function() {
          fb.style.display = 'block';
          fb.textContent = '❌ Network error.';
          fb.style.color = '#dc2626';
          btn.disabled = false; btn.textContent = 'Αποστολή Αιτήματος';
        });
    });
  });

  // Calendar
  var calendarEl = document.getElementById('job-calendar');
  if (calendarEl) {
    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();
  }

  // Duration suggestion forms
  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! The manager will review it.';
            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';
          fb.textContent = '❌ Network error. Please try again.';
          fb.style.color = '#dc2626';
          btn.disabled = false; btn.textContent = 'Submit suggestion';
        });
    });
  });

  // 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';
      }
    });
  });
  // ── Quick Ολοκλήρωση ────────────────────────────────────────────────────
  window.quickCompleteJob = function(assignmentId) {
    if (!confirm('Είστε σίγουροι ότι θέλετε να ολοκληρώσετε αυτό το έργο;')) return;
    
    var fd = new FormData();
    fd.append('assignment_id', assignmentId);
    fd.append('action', 'stop');
    fd.append('csrf_token', '<?php echo csrf_token(); ?>');
    
    fetch('/gopools/public/employees/job_action.php', { method: 'POST', body: fd })
      .then(r => r.text())
      .then(res => {
         // Reload page to reflect changes
         window.location.reload();
      })
      .catch(err => {
         alert('?�?�?�?�???� ?�?�?�?????�?�?�. ?�?�?�?�???�?�?� ???????????�?�?�?? ???�?�?�.');
      });
  };
});
</script>

<style>
.premium-job-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 32px rgba(0,0,0,0.08);
  border-color: var(--gp-primary);
}
.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, #64748b);
  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'; ?>

