<?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();
$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { http_response_code(404); exit('Project not found.'); }

$_lang = gp_lang($pdo);
$canEdit = gp_can_edit_project($pdo, $id);
$canViewCostings = function_exists('gp_user_perm') ? gp_user_perm($pdo, 'perm_costings') : gp_is_admin_like();

// Load project
$stmt = $pdo->prepare("
    SELECT p.*, c.name AS customer_name, c.phone AS customer_phone, c.email AS customer_email,
           cat.name AS category_name
    FROM projects p
    LEFT JOIN customers c ON c.id = p.customer_id
    LEFT JOIN project_categories cat ON cat.id = p.category_id
    WHERE p.id = :id LIMIT 1
");
$stmt->execute([':id' => $id]);
$project = $stmt->fetch();
if (!$project) { http_response_code(404); exit('Project not found.'); }

// Load assignments (partners + employees)
$assignments = $pdo->prepare("
    SELECT pa.*, pa.role_label,
           ep.company_name AS partner_name,
           e.full_name AS employee_name
    FROM project_assignments pa
    LEFT JOIN external_partners ep ON ep.id = pa.external_partner_id
    LEFT JOIN employees e ON e.id = pa.employee_id
    WHERE pa.project_id = :pid
    ORDER BY pa.status ASC, pa.assigned_date DESC
");
$assignments->execute([':pid' => $id]);
$assignmentRows = $assignments->fetchAll();

// Load recent photos
$photoStmt = $pdo->prepare("
    SELECT * FROM project_photos
    WHERE project_id = :pid
    ORDER BY created_at DESC
    LIMIT 6
");
$photoStmt->execute([':pid' => $id]);
$photos = $photoStmt->fetchAll();

// Load comments
$commentStmt = $pdo->prepare("
    SELECT pc.*, u.username
    FROM project_comments pc
    LEFT JOIN users u ON u.id = pc.user_id
    WHERE pc.project_id = :pid
    ORDER BY pc.created_at DESC
    LIMIT 5
");
$commentStmt->execute([':pid' => $id]);
$comments = $commentStmt->fetchAll();

// Load email attachments
$attachStmt = $pdo->prepare("
    SELECT a.*, e.subject 
    FROM inbox_attachments a
    JOIN inbox_emails e ON e.id = a.inbox_email_id
    WHERE e.linked_project_id = :pid
    ORDER BY a.created_at DESC
");
$attachStmt->execute([':pid' => $id]);
$attachments = $attachStmt->fetchAll();

// Load financial summary (only if has perm)
$totalPaid = 0; $totalExpenses = 0;
if ($canViewCostings) {
    try {
        $r = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM project_payments WHERE project_id=? AND payment_type IN ('deposit','payment')");
        $r->execute([$id]); $totalPaid = (float)$r->fetchColumn();
        $r2 = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM project_expenses WHERE project_id=?");
        $r2->execute([$id]); $totalExpenses = (float)$r2->fetchColumn();
    } catch (Throwable $e) {}
}
$budget = (float)($project['budget'] ?? 0);
$balance = $budget - $totalPaid;

$status_colors = [
    'new' => ['#3b82f6', 'rgba(59,130,246,0.12)'],
    'in_progress' => ['#f59e0b', 'rgba(245,158,11,0.12)'],
    'done' => ['#10b981', 'rgba(16,185,129,0.12)'],
    'cancelled' => ['#ef4444', 'rgba(239,68,68,0.12)'],
    'on_hold' => ['#8b5cf6', 'rgba(139,92,246,0.12)'],
];
$sc = $status_colors[$project['status'] ?? ''] ?? ['#6b7280', 'rgba(107,114,128,0.12)'];

$page_title = h($project['title']);
include __DIR__ . '/../includes/header.php';
?>
<?php gp_render_project_menu($pdo, $id); ?>

<!-- Page Header -->
<div class="page-header" style="display:flex;justify-content:space-between;align-items:flex-start;gap:16px;flex-wrap:wrap;margin-bottom:24px;">
  <div>
    <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:6px;">
      <h1 style="font-size:1.6rem;font-weight:800;margin:0;"><?php echo h($project['title']); ?></h1>
      <span style="background:<?php echo $sc[1]; ?>;color:<?php echo $sc[0]; ?>;border:1px solid <?php echo $sc[0]; ?>33;padding:4px 14px;border-radius:20px;font-size:0.78rem;font-weight:700;text-transform:uppercase;letter-spacing:.05em;">
        <?php echo h($project['status'] ?? 'new'); ?>
      </span>
    </div>
    <div style="color:var(--gp-muted);font-size:0.88rem;display:flex;gap:12px;flex-wrap:wrap;">
      <?php if ($project['code']): ?><span>📁 <?php echo h($project['code']); ?></span><?php endif; ?>
      <?php if ($project['customer_name']): ?><span>👤 <?php echo h($project['customer_name']); ?></span><?php endif; ?>
      <?php if ($project['city']): ?><span>📍 <?php echo h($project['city']); ?></span><?php endif; ?>
      <?php if ($project['category_name']): ?><span>🏷️ <?php echo h($project['category_name']); ?></span><?php endif; ?>
    </div>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap;">
    <?php if (!empty($project['customer_phone'])): ?>
      <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $project['customer_phone']); ?>" target="_blank" class="btn btn-sm" style="background:#25D366;color:#fff;border:none;">📱 WhatsApp</a>
    <?php endif; ?>
    <?php if (!empty($project['customer_email'])): ?>
      <a href="mailto:<?php echo h($project['customer_email']); ?>" class="btn btn-sm" style="background:#ea4335;color:#fff;border:none;">✉️ Email</a>
    <?php endif; ?>
    <?php if ($canEdit): ?>
      <a href="/gopools/public/projects/edit.php?id=<?php echo $id; ?>" class="btn btn-sm btn-outline-light">✏️ Επεξεργασία</a>
    <?php endif; ?>
    <a href="/gopools/public/projects/index.php" class="btn btn-sm btn-outline-light">← Λίστα</a>
  </div>
</div>

<!-- Stats Row -->
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:14px;margin-bottom:24px;">

  <div class="card" style="padding:16px;border-radius:14px;text-align:center;">
    <div style="font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--gp-muted);font-weight:700;margin-bottom:6px;">Έναρξη</div>
    <div style="font-size:1rem;font-weight:700;"><?php echo $project['start_date'] ? gp_date($project['start_date']) : '—'; ?></div>
  </div>
  <div class="card" style="padding:16px;border-radius:14px;text-align:center;">
    <div style="font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--gp-muted);font-weight:700;margin-bottom:6px;">Λήξη Πλάν.</div>
    <div style="font-size:1rem;font-weight:700;"><?php echo $project['end_date_planned'] ? gp_date($project['end_date_planned']) : '—'; ?></div>
  </div>
  <div class="card" style="padding:16px;border-radius:14px;text-align:center;">
    <div style="font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--gp-muted);font-weight:700;margin-bottom:6px;">Αναθέσεις</div>
    <div style="font-size:1.6rem;font-weight:800;color:#3b82f6;"><?php echo count($assignmentRows); ?></div>
  </div>
  <div class="card" style="padding:16px;border-radius:14px;text-align:center;">
    <div style="font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--gp-muted);font-weight:700;margin-bottom:6px;">Φωτογραφίες</div>
    <div style="font-size:1.6rem;font-weight:800;color:#8b5cf6;"><?php
      try {
        $pCount = $pdo->prepare("SELECT COUNT(*) FROM project_photos WHERE project_id=?");
        $pCount->execute([$id]);
        echo (int)$pCount->fetchColumn();
      } catch(Throwable $e) { echo '—'; }
    ?></div>
  </div>

  <?php if ($canViewCostings): ?>
  <div class="card" style="padding:16px;border-radius:14px;text-align:center;background:rgba(16,185,129,0.06);border:1px solid rgba(16,185,129,0.2);">
    <div style="font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:#10b981;font-weight:700;margin-bottom:6px;">Budget</div>
    <div style="font-size:1.2rem;font-weight:800;color:#10b981;">€<?php echo number_format($budget, 0); ?></div>
  </div>
  <div class="card" style="padding:16px;border-radius:14px;text-align:center;background:rgba(59,130,246,0.06);border:1px solid rgba(59,130,246,0.2);">
    <div style="font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:#3b82f6;font-weight:700;margin-bottom:6px;">Εισπραχθέντα</div>
    <div style="font-size:1.2rem;font-weight:800;color:#3b82f6;">€<?php echo number_format($totalPaid, 0); ?></div>
  </div>
  <div class="card" style="padding:16px;border-radius:14px;text-align:center;background:<?php echo $balance > 0 ? 'rgba(245,158,11,0.06)' : 'rgba(16,185,129,0.06)'; ?>;border:1px solid <?php echo $balance > 0 ? 'rgba(245,158,11,0.2)' : 'rgba(16,185,129,0.2)'; ?>;">
    <div style="font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:<?php echo $balance > 0 ? '#f59e0b' : '#10b981'; ?>;font-weight:700;margin-bottom:6px;">Υπόλοιπο</div>
    <div style="font-size:1.2rem;font-weight:800;color:<?php echo $balance > 0 ? '#f59e0b' : '#10b981'; ?>;">€<?php echo number_format($balance, 0); ?></div>
  </div>
  <?php endif; ?>
</div>

<div class="grid-2" style="gap:20px;margin-bottom:20px;align-items:start;">

  <!-- Info Card -->
  <div class="card" style="border-radius:16px;padding:20px;">
    <div style="font-size:.75rem;text-transform:uppercase;letter-spacing:.06em;color:var(--gp-muted);font-weight:700;margin-bottom:16px;padding-bottom:10px;border-bottom:1px solid var(--gp-card-border);">📋 Στοιχεία Έργου</div>
    <dl style="display:grid;grid-template-columns:auto 1fr;gap:8px 16px;font-size:.88rem;margin:0;">
      <?php if ($project['address'] || $project['city']): ?>
        <dt style="color:var(--gp-muted);white-space:nowrap;">📍 Διεύθυνση</dt>
        <dd style="margin:0;font-weight:600;"><?php echo h(trim($project['address'] . ' ' . $project['city'])); ?></dd>
      <?php endif; ?>
      <?php if ($project['customer_phone']): ?>
        <dt style="color:var(--gp-muted);">📞 Τηλέφωνο</dt>
        <dd style="margin:0;font-weight:600;"><a href="tel:<?php echo h($project['customer_phone']); ?>" style="color:var(--gp-text);"><?php echo h($project['customer_phone']); ?></a></dd>
      <?php endif; ?>
      <?php if ($project['manager_username'] ?? null): ?>
        <dt style="color:var(--gp-muted);">👷 Υπεύθυνος</dt>
        <dd style="margin:0;font-weight:600;"><?php echo h($project['manager_username']); ?></dd>
      <?php endif; ?>
      <?php if ($project['distance_km']): ?>
        <dt style="color:var(--gp-muted);">🗺️ Απόσταση</dt>
        <dd style="margin:0;font-weight:600;"><?php echo h($project['distance_km']); ?> km</dd>
      <?php endif; ?>
      <?php if (!empty($project['offer_filename'])): ?>
        <dt style="color:var(--gp-muted);">📎 Προσφορά</dt>
        <dd style="margin:0;"><a href="/gopools/public/uploads/project_offers/<?php echo h($project['offer_filename']); ?>" target="_blank" class="btn btn-sm btn-outline-light" style="font-size:.75rem;padding:2px 10px;">Download</a></dd>
      <?php endif; ?>
    </dl>
    <?php if ($project['notes']): ?>
      <div style="margin-top:16px;padding-top:16px;border-top:1px solid var(--gp-card-border);font-size:.85rem;color:var(--gp-muted);line-height:1.6;">
        <?php echo nl2br(h($project['notes'])); ?>
      </div>
    <?php endif; ?>
  </div>

  <!-- Assignments Card -->
  <div class="card" style="border-radius:16px;padding:20px;">
    <div style="font-size:.75rem;text-transform:uppercase;letter-spacing:.06em;color:var(--gp-muted);font-weight:700;margin-bottom:16px;padding-bottom:10px;border-bottom:1px solid var(--gp-card-border);display:flex;justify-content:space-between;align-items:center;">
      <span>👥 Αναθέσεις</span>
      <?php if ($canEdit): ?>
        <a href="/gopools/public/projects/dispatch.php" class="btn btn-sm btn-outline-light" style="font-size:.72rem;padding:2px 10px;">+ Ανάθεση</a>
      <?php endif; ?>
    </div>
    <?php if (!$assignmentRows): ?>
      <p style="color:var(--gp-muted);font-size:.85rem;margin:0;">Δεν υπάρχουν αναθέσεις.</p>
    <?php else: ?>
      <div style="display:flex;flex-direction:column;gap:8px;">
        <?php foreach ($assignmentRows as $a):
          $name = $a['partner_name'] ?? $a['employee_name'] ?? '—';
          $isCompleted = $a['status'] === 'completed';
          $badgeColor = $isCompleted ? '#10b981' : '#f59e0b';
          $badgeBg = $isCompleted ? 'rgba(16,185,129,0.12)' : 'rgba(245,158,11,0.12)';
        ?>
        <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 12px;background:var(--gp-nav-bg-2);border-radius:10px;gap:8px;">
          <div>
            <div style="font-weight:700;font-size:.88rem;"><?php echo h($name); ?></div>
            <?php if ($a['role_label']): ?><div style="font-size:.72rem;color:var(--gp-muted);"><?php echo h($a['role_label']); ?></div><?php endif; ?>
          </div>
          <span style="background:<?php echo $badgeBg; ?>;color:<?php echo $badgeColor; ?>;border:1px solid <?php echo $badgeColor; ?>33;padding:2px 10px;border-radius:20px;font-size:.7rem;font-weight:700;white-space:nowrap;">
            <?php echo $isCompleted ? '✅ Ολοκλ.' : '🔄 Ενεργό'; ?>
          </span>
        </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>

</div>

<!-- Photos Row -->
<?php if ($photos): ?>
<div class="card" style="border-radius:16px;padding:20px;margin-bottom:20px;">
  <div style="font-size:.75rem;text-transform:uppercase;letter-spacing:.06em;color:var(--gp-muted);font-weight:700;margin-bottom:16px;padding-bottom:10px;border-bottom:1px solid var(--gp-card-border);display:flex;justify-content:space-between;align-items:center;">
    <span>📸 Φωτογραφίες</span>
    <a href="/gopools/public/projects/photos.php?project_id=<?php echo $id; ?>" class="btn btn-sm btn-outline-light" style="font-size:.72rem;padding:2px 10px;">Όλες →</a>
  </div>
  <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:10px;">
    <?php foreach ($photos as $ph): ?>
      <a href="<?php echo gp_upload_url('photos', $ph['filename']); ?>" target="_blank" style="display:block;aspect-ratio:1;border-radius:10px;overflow:hidden;background:var(--gp-nav-bg-2);">
        <img src="<?php echo gp_upload_url('photos', $ph['filename']); ?>" alt="" style="width:100%;height:100%;object-fit:cover;transition:transform .2s;" onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'">
      </a>
    <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

<!-- Email Attachments -->
<?php if ($attachments): ?>
<div class="card" style="border-radius:16px;padding:20px;margin-bottom:20px;">
  <div style="font-size:.75rem;text-transform:uppercase;letter-spacing:.06em;color:var(--gp-muted);font-weight:700;margin-bottom:16px;padding-bottom:10px;border-bottom:1px solid var(--gp-card-border);display:flex;justify-content:space-between;align-items:center;">
    <span>?? ???S?????????? EMAIL</span>
  </div>
  <div style="display:flex;flex-direction:column;gap:10px;">
    <?php foreach ($attachments as $att): 
        $icon = '??';
        $ext = strtolower(pathinfo($att['file_name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['pdf'])) $icon = '??';
        elseif (in_array($ext, ['jpg','jpeg','png','gif','webp'])) $icon = '???';
        elseif (in_array($ext, ['doc','docx'])) $icon = '??';
        elseif (in_array($ext, ['xls','xlsx'])) $icon = '??';
    ?>
      <div style="display:flex;align-items:center;justify-content:space-between;padding:10px 14px;background:var(--gp-nav-bg-2);border-radius:10px;border:1px solid var(--gp-card-border);">
        <div style="display:flex;align-items:center;gap:12px;">
            <span style="font-size:1.5rem;"><?php echo $icon; ?></span>
            <div>
                <a href="<?php echo h($att['file_path']); ?>" target="_blank" style="font-weight:600;font-size:0.9rem;text-decoration:none;color:var(--gp-text);"><?php echo h($att['file_name']); ?></a>
                <div style="font-size:0.75rem;color:var(--gp-muted);margin-top:2px;">
                    ?p?: <strong><?php echo h($att['subject']); ?></strong> &bull; <?php echo number_format($att['file_size'] / 1024, 1); ?> KB
                </div>
            </div>
        </div>
        <a href="<?php echo h($att['file_path']); ?>" download class="btn btn-sm btn-outline-light" style="font-size:.75rem;padding:4px 10px;">????</a>
      </div>
    <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

<!-- Comments -->
<?php if ($comments): ?>
<div class="card" style="border-radius:16px;padding:20px;">
  <div style="font-size:.75rem;text-transform:uppercase;letter-spacing:.06em;color:var(--gp-muted);font-weight:700;margin-bottom:16px;padding-bottom:10px;border-bottom:1px solid var(--gp-card-border);">💬 Τελευταία Σχόλια</div>
  <div style="display:flex;flex-direction:column;gap:12px;">
    <?php foreach ($comments as $cm): ?>
    <div style="padding:12px;background:var(--gp-nav-bg-2);border-radius:10px;border-left:3px solid var(--gp-primary);">
      <div style="font-size:.75rem;color:var(--gp-muted);margin-bottom:4px;display:flex;justify-content:space-between;">
        <span>👤 <?php echo h($cm['username'] ?? 'System'); ?></span>
        <span><?php echo gp_date($cm['created_at'], true); ?></span>
      </div>
      <div style="font-size:.88rem;line-height:1.5;"><?php echo nl2br(h($cm['comment'] ?? $cm['body'] ?? '')); ?></div>
    </div>
    <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

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



