<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/project_menu.php';
require_once __DIR__ . '/../../app/core/i18n.php';
auth_require_login();
$pdo = crm_pdo();
$page_title = 'Φωτογραφίες Έργου';

$id = (int)($_GET['project_id'] ?? 0);
if ($id <= 0) die('Project not found.');

// Επιτρέπουμε πρόσβαση (view) σε όλους τους logged-in χρήστες.
// Μόνο αυτοί με δικαίωμα edit μπορούν να κάνουν upload/delete.
$canEditPhotos = gp_can_edit_project($pdo, $id);

$stmt = $pdo->prepare("SELECT p.*, c.name AS customer_name FROM projects p LEFT JOIN customers c ON c.id = p.customer_id WHERE p.id = :id LIMIT 1");
$stmt->execute([':id' => $id]);
$project = $stmt->fetch();
if (!$project) die('Project not found.');

$projectPhotos = [];
try {
    $stmtP = $pdo->prepare("
        SELECT p.*, u.username, 
               CASE p.uploaded_by_type
                   WHEN 'employee' THEN e.full_name
                   WHEN 'partner'  THEN ep.company_name
                   WHEN 'customer' THEN c.name
                   ELSE u.username
               END AS uploader_name
        FROM project_photos p
        JOIN users u ON u.id = p.uploaded_by_user_id
        LEFT JOIN employees e ON e.id = (SELECT employee_id FROM users WHERE id=p.uploaded_by_user_id LIMIT 1)
        LEFT JOIN external_partners ep ON ep.id = (SELECT external_partner_id FROM users WHERE id=p.uploaded_by_user_id LIMIT 1)
        LEFT JOIN customers c ON c.id = (SELECT customer_id FROM users WHERE id=p.uploaded_by_user_id LIMIT 1)
        WHERE p.project_id = ?
        ORDER BY p.id DESC
    ");
    $stmtP->execute([$id]);
    $projectPhotos = $stmtP->fetchAll();
} catch (Throwable $e) {}

include __DIR__ . '/../includes/header.php';
?>
<?php gp_render_project_menu($pdo, $id); ?>

<div class="page-header">
  <div class="page-header-title">
    <h1>📸 Φωτο/Χάρτης</h1>
    <span><?php echo h($project['code'] . ' · ' . $project['title']); ?></span>
  </div>
</div>

<div class="card">
  <div class="page-header-title">
    <h1 style="font-size:1.05rem">📸 Φωτογραφίες Έργου</h1>
    <span>Φωτογραφίες από συνεργεία &amp; γραφείο</span>
  </div>

  <!-- Creator Upload Form - only for users with edit rights -->
  <?php if ($canEditPhotos): ?>
  <div style="margin-top:12px; padding:12px; background:rgba(37,99,235,0.05); border:1px solid rgba(37,99,235,0.1); border-radius:12px;">
      <h3 style="font-size:0.85rem; margin:0 0 10px 0;">⬆️ Ανέβασμα Φωτογραφίας</h3>
    <form id="creator-photo-upload" enctype="multipart/form-data">
      <div style="display:flex; gap:10px; align-items:flex-end; flex-wrap:wrap;">
        <div class="form-group" style="margin:0; flex:1; min-width:150px;">
          <label style="font-size:0.7rem;">Category</label>
          <select name="category" id="photo-category" style="padding:4px 8px; font-size:0.8rem;">
            <option value="pool">Pool</option>
            <option value="mechanical">Mechanical Room</option>
          </select>
        </div>
        <div class="form-group" style="margin:0; flex:2; min-width:200px;">
          <label style="font-size:0.7rem;">Αρχεία (μπορείτε να επιλέξετε πολλές)</label>
          <input type="file" name="photo" id="creator-photo-input" accept="image/*" multiple required style="font-size:0.8rem;">
        </div>
        <button type="button" id="btn-upload-photo" class="btn btn-sm btn-primary">Ανέβασμα</button>
      </div>
      <div id="creator-upload-progress" style="display:none;margin-top:8px;font-size:0.78rem;font-weight:600;"></div>
    </form>
  </div>
  <?php endif; ?>

  
  <?php if ($projectPhotos): ?>
    <div style="display:flex;flex-wrap:wrap;gap:12px;margin-top:12px;">
      <?php foreach ($projectPhotos as $ph): ?>
        <div style="width:140px;border:1px solid var(--gp-card-border);border-radius:8px;overflow:hidden;background:var(--gp-card-bg);display:flex;flex-direction:column;">
          <a href="<?php echo gp_upload_url('photos', $ph['filename']); ?>" target="_blank">
            <img src="<?php echo gp_upload_url('photos', $ph['filename']); ?>" style="width:140px;height:120px;object-fit:cover;display:block;">
          </a>
          <div style="padding:6px 8px;font-size:.7rem;text-align:center;flex-grow:1;display:flex;flex-direction:column;">
            <span style="display:block;font-weight:700;color:var(--gp-primary);margin-bottom:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;" title="<?php echo h($ph['category']); ?>">
              <?php echo h($ph['category']); ?>
            </span>
            <?php if (!empty($ph['title'])): ?>
              <span style="display:block;color:var(--gp-text);margin-bottom:2px;font-size:.65rem;font-style:italic;">
                <?php echo h($ph['title']); ?>
              </span>
            <?php endif; ?>
            <span style="display:block;color:var(--gp-muted);text-overflow:ellipsis;overflow:hidden;white-space:nowrap;" title="<?php echo h($ph['uploader_name'] ?: $ph['username']); ?>">
              <?php echo $ph['uploaded_by_type'] === 'customer' ? '👤 ' : '🏢 '; ?><?php echo h($ph['uploader_name'] ?: $ph['username']); ?>
            </span>
            <span style="display:block;color:var(--gp-muted);font-size:.65rem;margin-top:2px;">
              📅 <?php echo h(gp_date((string)$ph['created_at'])) . ' ' . date('H:i', strtotime($ph['created_at'])); ?>
            </span>
            
            <?php if ($canEditPhotos): ?>
            <div style="margin-top:auto;padding-top:6px;border-top:1px solid var(--gp-card-border);display:flex;flex-direction:column;gap:4px;">
              <label style="display:flex;align-items:center;justify-content:center;gap:4px;font-size:.65rem;cursor:pointer;margin:0;">
                <input type="checkbox" class="share-photo-cb" data-id="<?php echo (int)$ph['id']; ?>" <?php echo $ph['shared_with_crew'] ? 'checked' : ''; ?>>
                  <span>Ορατό στο Συνεργείο</span>
              </label>
              <button class="delete-photo-btn" data-id="<?php echo (int)$ph['id']; ?>" style="background:none;border:none;color:#ef4444;font-size:.65rem;cursor:pointer;padding:2px 0;font-weight:700;">🗑 Διαγραφή</button>
            </div>
            <?php endif; ?>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  <?php else: ?>
    <p class="small text-muted" style="margin-top:12px;">Δεν υπάρχουν φωτογραφίες ακόμα.</p>
  <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){
  const btnUpload = document.getElementById('btn-upload-photo');
  const progressEl = document.getElementById('creator-upload-progress');

  if (btnUpload) {
    btnUpload.addEventListener('click', async function() {
      const fileInput = document.getElementById('creator-photo-input');
      const files = fileInput.files;
      if (!files || files.length === 0) { alert('Παρακαλώ επιλέξτε τουλάχιστον μία φωτογραφία.'); return; }
      const category = document.getElementById('photo-category').value;
      const projectId = '<?php echo $id; ?>';
      const csrfToken = '<?php echo csrf_token(); ?>';

      btnUpload.disabled = true;
      btnUpload.innerText = 'Uploading...';
      progressEl.style.display = 'block';

      let successCount = 0;
      let failCount = 0;

      for (let i = 0; i < files.length; i++) {
        progressEl.textContent = `Ανέβασμα ${i + 1} από ${files.length}...`;
        progressEl.style.color = 'var(--gp-primary)';
        const fd = new FormData();
        fd.append('photo', files[i]);
        fd.append('category', category);
        fd.append('project_id', projectId);
        fd.append('csrf_token', csrfToken);
        try {
          const r = await fetch('/gopools/public/api/upload_creator_photo.php', { method: 'POST', body: fd });
          let res;
          try { res = await r.json(); } catch(je) { res = { ok: false, error: 'HTTP ' + r.status + ' – ' + await r.text().catch(()=>'') }; }
          if (res.ok) {
            successCount++;
          } else {
            failCount++;
            progressEl.textContent = `❌ Σφάλμα: ${res.error || 'HTTP ' + r.status}`;
            progressEl.style.color = '#dc2626';
            console.error('Upload API error:', res);
          }
        } catch(e) {
          failCount++;
          progressEl.textContent = `❌ Network error: ${e.message}`;
          progressEl.style.color = '#dc2626';
          console.error('Upload exception:', e);
        }
      }

      if (failCount === 0) {
        progressEl.textContent = `✅ ${successCount} φωτογραφίες ανέβηκαν επιτυχώς!`;
        progressEl.style.color = '#16a34a';
        setTimeout(() => location.reload(), 800);
      } else {
        progressEl.textContent += ` (${successCount} επιτυχία, ${failCount} αποτυχία)`;
        progressEl.style.color = '#f59e0b';
        btnUpload.disabled = false;
        btnUpload.innerText = 'Upload';
      }
    });
  }

  document.querySelectorAll('.share-photo-cb').forEach(cb => {
    cb.addEventListener('change', function(){
      const checked = this.checked ? 1 : 0;
      const photoId = this.getAttribute('data-id');
      fetch('/gopools/public/api/toggle_photo_share.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          photo_id: photoId,
          project_id: <?php echo (int)$id; ?>,
          shared: checked,
          csrf_token: '<?php echo csrf_token(); ?>'
        })
      }).then(r => r.json()).then(res => {
        if(!res.ok) { alert(res.error || 'Failed'); this.checked = !checked; }
      });
    });
  });

  // Delete photo buttons
  document.querySelectorAll('.delete-photo-btn').forEach(btn => {
    btn.addEventListener('click', function() {
      if (!confirm('Διαγραφή αυτής της φωτογραφίας; Η ενέργεια δεν αναιρείται.')) return;
      const photoId = this.getAttribute('data-id');
      const card = this.closest('div[style*="width:140px"]');
      fetch('/gopools/public/api/delete_project_photo.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          photo_id: photoId,
          project_id: <?php echo (int)$id; ?>,
          csrf_token: '<?php echo csrf_token(); ?>'
        })
      }).then(r => r.json()).then(res => {
        if (res.ok) {
          if (card) card.remove();
        } else {
          alert('❌ ' + (res.error || 'Αποτυχία διαγραφής'));
        }
      }).catch(() => alert('❌ Network error'));
    });
  });
});
</script>

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