<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_financials.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 = 'Project';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$saved = isset($_GET['saved']) && $_GET['saved'] === '1';

if ($id > 0) {
    gp_require_project_edit($pdo, $id);
} else {
    gp_require_project_create($pdo);
}

$item = [
    'code' => '',
    'title' => '',
    'customer_id' => '',
    'category_id' => '',
    'status' => 'new',
    'address' => '',
    'city' => '',
    'start_date' => '',
    'end_date_planned' => '',
    'end_date_actual' => '',
    'budget' => '',
    'installation_cost' => '',
    'notes' => '',
    'manager_id' => '',
];

$errors = [];
$customers = $pdo->query("SELECT id, name FROM customers WHERE active = 1 ORDER BY name ASC")->fetchAll();
$cats = $pdo->query("SELECT id, name FROM project_categories WHERE is_active = 1 ORDER BY name ASC")->fetchAll();
$statuses = gp_project_statuses($pdo, true);
$managers = $pdo->query("SELECT u.id, u.username, e.full_name, ep.company_name FROM users u LEFT JOIN employees e ON e.id = u.employee_id LEFT JOIN external_partners ep ON ep.id = u.external_partner_id WHERE u.is_active = 1 AND u.role != 'customer' ORDER BY u.username ASC")->fetchAll();

if ($id) {
    $st = $pdo->prepare("
        SELECT p.*, c.name AS customer_name, c.phone AS customer_phone, c.email AS customer_email 
        FROM projects p 
        LEFT JOIN customers c ON c.id = p.customer_id 
        WHERE p.id = :id 
        LIMIT 1
    ");
    $st->execute([':id' => $id]);
    $row = $st->fetch();
    if ($row) $item = array_merge($item, $row);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    gp_require_csrf();
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) gp_require_project_edit($pdo, $id);

    // Handle offer file upload
    $offerFile = null;
    if (isset($_FILES['offer_file']) && $_FILES['offer_file']['error'] !== UPLOAD_ERR_NO_FILE) {
        $f = $_FILES['offer_file'];
        if ($f['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
            $allowed = ['pdf','doc','docx','xls','xlsx','png','jpg','jpeg'];
            if (in_array($ext, $allowed, true)) {
                $offerFile = 'offer_' . ($id ?: 'new') . '_' . time() . '.' . $ext;
                $destDir = __DIR__ . '/../uploads/project_offers/';
                if (!is_dir($destDir)) mkdir($destDir, 0755, true);
                if (!move_uploaded_file($f['tmp_name'], $destDir . $offerFile)) {
                    $errors[] = 'Could not save offer file.';
                    $offerFile = null;
                }
            } else {
                $errors[] = 'Offer file type not allowed (pdf, doc, docx, xls, xlsx, jpg, png).';
            }
        } else {
            $errors[] = 'Upload error for offer file. Code: ' . $f['error'];
        }
    }

    foreach (array_keys($item) as $k) {
        $item[$k] = trim((string)($_POST[$k] ?? ''));
    }

    if ($item['title'] === '') $errors[] = 'Title is required.';
    if ($item['customer_id'] === '') $errors[] = 'Customer is required.';
    if (!array_key_exists($item['status'], $statuses)) $errors[] = 'Invalid status.';
    if ($item['code'] === '') $item['code'] = 'PRJ-' . date('Ymd-His');

    if (!$errors) {
        $currentUserId = (int)(auth_user()['id'] ?? 0) ?: null;
        $params = [
            ':code' => $item['code'],
            ':title' => $item['title'],
            ':customer_id' => $item['customer_id'],
            ':category_id' => $item['category_id'] !== '' ? $item['category_id'] : null,
            ':status' => $item['status'],
            ':address' => $item['address'] !== '' ? $item['address'] : null,
            ':city' => $item['city'] !== '' ? $item['city'] : null,
            ':start_date' => $item['start_date'] !== '' ? $item['start_date'] : null,
            ':end_date_planned' => $item['end_date_planned'] !== '' ? $item['end_date_planned'] : null,
            ':end_date_actual' => $item['end_date_actual'] !== '' ? $item['end_date_actual'] : null,
            ':budget' => $item['budget'] !== '' ? $item['budget'] : null,
            ':installation_cost' => $item['installation_cost'] !== '' ? $item['installation_cost'] : null,
            ':notes' => $item['notes'] !== '' ? $item['notes'] : null,
            ':distance_km' => $item['distance_km'] !== '' ? $item['distance_km'] : null,
            ':latitude' => $item['latitude'] !== '' ? $item['latitude'] : null,
            ':longitude' => $item['longitude'] !== '' ? $item['longitude'] : null,
            ':manager_id' => $item['manager_id'] !== '' ? $item['manager_id'] : null,
            ':updated_by_user_id' => $currentUserId,
        ];

        if ($id > 0) {
            $sql = "UPDATE projects SET code = :code, title = :title, customer_id = :customer_id, category_id = :category_id, status = :status, address = :address, city = :city, start_date = :start_date, end_date_planned = :end_date_planned, end_date_actual = :end_date_actual, budget = :budget, installation_cost = :installation_cost, notes = :notes, distance_km = :distance_km, latitude = :latitude, longitude = :longitude, manager_id = :manager_id, updated_by_user_id = :updated_by_user_id" . ($offerFile ? ', offer_filename = :offer_filename' : '') . " WHERE id = :id";
            $params[':id'] = $id;
            if ($offerFile) $params[':offer_filename'] = $offerFile;
        } else {
            $params[':created_by_user_id'] = $currentUserId;
            $sql = "INSERT INTO projects (code, title, customer_id, category_id, status, address, city, start_date, end_date_planned, end_date_actual, budget, installation_cost, notes, distance_km, latitude, longitude, manager_id, created_by_user_id, updated_by_user_id" . ($offerFile ? ', offer_filename' : '') . ") VALUES (:code, :title, :customer_id, :category_id, :status, :address, :city, :start_date, :end_date_planned, :end_date_actual, :budget, :installation_cost, :notes, :distance_km, :latitude, :longitude, :manager_id, :created_by_user_id, :updated_by_user_id" . ($offerFile ? ', :offer_filename' : '') . ")";
            if ($offerFile) $params[':offer_filename'] = $offerFile;
        }

        $st = $pdo->prepare($sql);
        $ok = $st->execute($params);

        if (!$ok) {
            $info = $st->errorInfo();
            $errors[] = 'Save failed: ' . ($info[2] ?? 'Unknown database error.');
        } else {
            $isNew = !$id;
            if ($isNew) $id = (int)$pdo->lastInsertId();
            
            if ($isNew) {
                gp_log_action($pdo, 'PROJECT_CREATE', 'project', $id, 'Created ??? ????: ' . $item['title']);
            } else {
                gp_log_action($pdo, 'PROJECT_UPDATE', 'project', $id, 'Updated project details');
            }
            
            header('Location: /gopools/public/projects/edit.php?id=' . $id . '&saved=1');
            exit;
        }
    }
}

$canViewFinancials = function_exists('gp_user_perm') ? gp_user_perm($pdo, 'perm_financials') : gp_is_admin_like();

$summary = [];
if ($id > 0 && $canViewFinancials) {
    $summary = gp_project_financial_summary($pdo, $id);
} else {
    $summary = ['equipment_cost'=>0,'installation_cost'=>0,'partner_cost'=>0,'expense_cost'=>0,'labor_cost'=>0,
        'employee_expense_cost'=>0,'direct_cost'=>0,'payments_in'=>0,'budget'=>0,'margin'=>0,'estimated_revenue'=>0];
}
$customerBalance = (float)($summary['balance'] ?? ((float)$summary['budget'] - (float)$summary['payments_in']));
$profit = (float)($summary['profit'] ?? $summary['margin'] ?? 0);

$projectComments = [];
if ($id > 0) {
    try {
        $stmtC = $pdo->prepare("
            SELECT pc.*, u.username 
            FROM project_comments pc
            LEFT JOIN users u ON u.id = pc.user_id
            WHERE pc.project_id = ?
            ORDER BY pc.created_at DESC
        ");
        $stmtC->execute([$id]);
        $projectComments = $stmtC->fetchAll();
    } catch (Throwable $e) {}
    
    // Project photos moved to photos.php
    
    // Load pool calculator specs
    $poolSpecs = [];
    try {
        $sp = $pdo->prepare("SELECT * FROM pool_calculator_specs WHERE project_id = ? LIMIT 1");
        $sp->execute([$id]);
        $poolSpecs = $sp->fetch() ?: [];
    } catch (Throwable $e) {}
}

$stmt = $pdo->prepare("SELECT * FROM project_visits WHERE project_id = :pid ORDER BY start_date ASC");
$stmt->execute([':pid' => $id]);
$projectVisits = $stmt->fetchAll();

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

<div class="page-header" style="align-items: flex-start;">
  <div class="page-header-title">
    <h1><?php echo $id ? 'Επεξεργασία έργου' : 'Νέο έργο'; ?></h1>
    <?php if ($id > 0): ?>
      <div style="display:flex; gap:8px; margin-top:8px;">
        <a href="/gopools/public/api/qr.php?text=<?php echo urlencode($item['code']); ?>" target="_blank" class="btn btn-sm btn-outline-light">🖨️ Print QR</a>
        <?php if (!empty($item['customer_phone'])): ?>
          <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $item['customer_phone']); ?>" target="_blank" class="btn btn-sm btn-outline-light" style="background: #25D366; color: white; border: none;">📱 WhatsApp</a>
        <?php endif; ?>
        <?php if (!empty($item['customer_email'])): ?>
          <a href="mailto:<?php echo h($item['customer_email']); ?>" class="btn btn-sm btn-outline-light" style="background: #ea4335; color: white; border: none;">✉️ Email</a>
        <?php endif; ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<div class="grid-2">
  <div class="card">
    <?php if ($saved): ?><div class="alert-success">Project saved successfully.</div><?php endif; ?>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>
    <form method="post" enctype="multipart/form-data">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="id" value="<?php echo (int)$id; ?>">
      <div class="form-grid">
        <div class="form-group"><label>Κωδικός (Code)</label><input name="code" value="<?php echo h($item['code']); ?>"></div>
        <div class="form-group"><label>Τίτλος</label><input name="title" value="<?php echo h($item['title']); ?>"></div>
        <div class="form-group">
          <label>Πελάτης</label>
          <select name="customer_id">
            <option value="">Select...</option>
            <?php foreach ($customers as $c): ?><option value="<?php echo (int)$c['id']; ?>" <?php echo ((string)$item['customer_id'] === (string)$c['id']) ? 'selected' : ''; ?>><?php echo h($c['name']); ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Category</label>
          <select name="category_id">
            <option value="">-</option>
            <?php foreach ($cats as $c): ?><option value="<?php echo (int)$c['id']; ?>" <?php echo ((string)$item['category_id'] === (string)$c['id']) ? 'selected' : ''; ?>><?php echo h($c['name']); ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Υπεύθυνος Έργου (Manager)</label>
          <select name="manager_id">
            <option value="">-</option>
            <?php foreach ($managers as $m): ?>
              <?php $name = $m['full_name'] ?: $m['company_name'] ?: $m['username']; ?>
              <option value="<?php echo (int)$m['id']; ?>" <?php echo ((string)$item['manager_id'] === (string)$m['id']) ? 'selected' : ''; ?>><?php echo h($name . ' (' . $m['username'] . ')'); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Status</label>
          <select name="status" id="status-select">
            <?php foreach ($statuses as $key => $label): ?><option value="<?php echo h($key); ?>" <?php echo ($item['status'] === $key) ? 'selected' : ''; ?>><?php echo h($label); ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="form-group"><label>Budget / sold price</label><input name="budget" id="budget-input" value="<?php echo h($item['budget']); ?>"></div>
        <div class="form-group"><label>Installation cost</label><input name="installation_cost" value="<?php echo h($item['installation_cost']); ?>"></div>
        <div class="form-group"><label>Address</label><input name="address" value="<?php echo h($item['address']); ?>"></div>
        <div class="form-group">
          <label>City</label>
          <input name="city" id="project-city" value="<?php echo h($item['city']); ?>" list="city-list">
          <datalist id="city-list"></datalist>
        </div>
        <div class="form-group"><label>Start date</label><input type="date" name="start_date" value="<?php echo h($item['start_date']); ?>"></div>
        <div class="form-group"><label>Planned end</label><input type="date" name="end_date_planned" value="<?php echo h($item['end_date_planned']); ?>"></div>
        <div class="form-group"><label>Πραγματική Λήξη</label><input type="date" name="end_date_actual" value="<?php echo h($item['end_date_actual']); ?>"></div>
        <div class="form-group">
          <label>Χιλιομετρική Απόσταση (km)</label>
          <input type="number" step="0.1" name="distance_km" id="project-distance" value="<?php echo h($item['distance_km'] ?? ''); ?>">
          <input type="hidden" name="latitude" id="project-lat" value="<?php echo h($item['latitude'] ?? ''); ?>">
          <input type="hidden" name="longitude" id="project-lng" value="<?php echo h($item['longitude'] ?? ''); ?>">
        </div>
        <div class="form-group" style="grid-column:1/-1"><label>Σημειώσεις</label><textarea name="notes"><?php echo h($item['notes']); ?></textarea></div>
        <div class="form-group" style="grid-column:1/-1">
          <label>📎 Αρχείο Προσφοράς / Κοστολόγιο</label>
          <?php if (!empty($item['offer_filename'])): ?>
            <div style="margin-bottom:.5rem;padding:.5rem;background:rgba(16,185,129,.08);border-radius:6px;border:1px solid rgba(16,185,129,.3);font-size:.85rem;display:flex;align-items:center;gap:.75rem;">
              <span>📄</span>
              <a href="/gopools/public/uploads/project_offers/<?php echo h($item['offer_filename']); ?>" target="_blank" style="font-weight:600;">Λήψη τρέχουσας προσφοράς</a>
              <span style="color:var(--gp-muted);font-size:.75rem;">Ανεβάστε νέο αρχείο για αντικατάσταση</span>
            </div>
          <?php endif; ?>
          <input type="file" name="offer_file" accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png" style="font-size:.85rem;">
          <small style="color:var(--gp-muted);font-size:.72rem;">PDF, Word, Excel, Εικόνα (max 20MB)</small>
        </div>
      </div>
      <div class="form-actions">
        <button class="btn btn-primary" type="button" id="btn-save-project">Αποθήκευση</button>
        <?php if ($id > 0): ?>
          <button type="button" class="btn btn-secondary" id="openPoolCalcBtn">🧨 ΥΠΟΛΟΓΙΣΜΟΣ ΜΗΧΑΝΟΣΤΑΣΙΟΥ</button>
        <?php endif; ?>
        <a class="btn btn-secondary" href="/gopools/public/projects/index.php">← Πίσω</a>
      </div>
    </form>

<!-- ═══ COMPLETION WARNING MODAL ═══ -->
<div id="completion-warning-modal" style="display:none;position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,.6);backdrop-filter:blur(4px);display:none;align-items:center;justify-content:center;padding:1rem;">
  <div style="background:#fff;border-radius:20px;box-shadow:0 25px 80px rgba(0,0,0,.35);max-width:480px;width:100%;padding:2rem;position:relative;">
    <div style="text-align:center;margin-bottom:1.5rem;">
      <div style="font-size:3rem;margin-bottom:.5rem;">⚠️</div>
      <h2 style="margin:0 0 .5rem;font-size:1.25rem;font-weight:800;color:#b45309;">Ελέγξτε το Κοστολόγιο!</h2>
      <p style="margin:0;color:#6b7280;font-size:.9rem;line-height:1.5;">Πριν ολοκληρώσετε το έργο, βεβαιωθείτε ότι έχετε καταχωρήσει το <strong>κοστολόγιο / τιμή χρέωσης</strong> (Budget) ώστε να είναι δυνατή η είσπραξη της πληρωμής.</p>
    </div>
    <div style="background:rgba(245,158,11,.08);border:1px solid rgba(245,158,11,.3);border-radius:12px;padding:1rem;margin-bottom:1.5rem;">
      <div style="font-size:.8rem;font-weight:700;color:#92400e;margin-bottom:.5rem;">📋 Τρέχουσα κατάσταση:</div>
      <div id="modal-budget-status" style="font-size:.9rem;color:#78350f;font-weight:600;"></div>
    </div>
    <div style="display:flex;gap:.75rem;">
      <button type="button" id="modal-go-back" class="btn btn-secondary" style="flex:1;">← Επιστροφή &amp; Διόρθωση</button>
      <button type="button" id="modal-proceed-anyway" class="btn" style="flex:1;background:#ef4444;color:#fff;border:none;">Ολοκλήρωση Παρ' Όλα Αυτά</button>
    </div>
  </div>
</div>
  </div>

  <?php if ($canViewFinancials): ?>
  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Οικονομική Σύνοψη Έργου</h1><span>Financial Summary</span></div>
    <div class="table-responsive">
      <table class="table">
        <tbody>
          <tr><td>Budget / sold price</td><td>€ <?php echo h(number_format((float)$summary['budget'], 2)); ?></td></tr>
          <tr><td>Payments received</td><td>€ <?php echo h(number_format((float)$summary['payments_in'], 2)); ?></td></tr>
          <tr><td><strong>Customer balance</strong></td><td><strong>€ <?php echo h(number_format($customerBalance, 2)); ?></strong></td></tr>
          <tr><td>Equipment cost</td><td>€ <?php echo h(number_format((float)$summary['equipment_cost'], 2)); ?></td></tr>
          <tr><td>Installation cost</td><td>€ <?php echo h(number_format((float)$summary['installation_cost'], 2)); ?></td></tr>
          <tr><td>Labor cost total</td><td>€ <?php echo h(number_format((float)$summary['labor_cost'], 2)); ?></td></tr>
          <tr><td>Employee expenses</td><td>€ <?php echo h(number_format((float)$summary['employee_expense_cost'], 2)); ?></td></tr>
          <tr><td>External partner cost</td><td>€ <?php echo h(number_format((float)$summary['partner_cost'], 2)); ?></td></tr>
          <tr><td>Project expenses</td><td>€ <?php echo h(number_format((float)$summary['expense_cost'], 2)); ?></td></tr>
          <tr><td><strong>Final project cost</strong></td><td><strong>€ <?php echo h(number_format((float)$summary['direct_cost'], 2)); ?></strong></td></tr>
          <tr><td><strong>Total profit</strong></td><td><strong>€ <?php echo h(number_format($profit, 2)); ?></strong></td></tr>
        </tbody>
      </table>
    </div>
  </div>
  <?php endif; ?>
  
  <?php if ($id > 0): ?>
  <?php if (!empty($poolSpecs)): ?>
  <div class="card" style="grid-column:1/-1">
    <div class="page-header-title" style="margin-bottom:.75rem">
      <h1 style="font-size:1.05rem">🧮 Pool Specifications</h1>
      <button type="button" class="btn btn-sm btn-outline-light" id="openPoolCalcBtn2" style="font-size:.75rem;">Edit Calculator</button>
    </div>
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:.6rem;">
      <?php
        $specItems = [
          ['Μήκος', ($poolSpecs['length'] ?? null), 'm'],
          ['Πλάτος', ($poolSpecs['width'] ?? null), 'm'],
          ['Βάθος Ρηχό', ($poolSpecs['depth_shallow'] ?? null), 'm'],
          ['Βάθος Βαθύ', ($poolSpecs['depth_deep'] ?? null), 'm'],
          ['Όγκος', ($poolSpecs['volume_m3'] ?? null), 'm³'],
          ['Νερό', ($poolSpecs['water_fill_liters'] ?? null) ? number_format((int)$poolSpecs['water_fill_liters']) . ' lt' : null, ''],
          ['Αντλία', ($poolSpecs['pump_flow_m3h'] ?? null), 'm³/h'],
          ['Φίλτρο', ($poolSpecs['filter_diam_mm'] ?? null), 'mm'],
          ['Σκίμερ', ($poolSpecs['skimmer_count'] ?? null), 'τεμ'],
          ['Στόμια Εισ.', ($poolSpecs['inlet_count'] ?? null), 'τεμ'],
          ['Στόμια Επ.', ($poolSpecs['outlet_count'] ?? null), 'τεμ'],
          ['Φρεάτια', ($poolSpecs['main_drain_count'] ?? null), 'τεμ'],
          ['Πρίζα Σκ.', ($poolSpecs['vacuum_point_count'] ?? null), 'τεμ'],
          ['Φωτιστικά', ($poolSpecs['lighting_count'] ?? null), 'τεμ'],
        ];
        foreach ($specItems as [$label, $val, $unit]):
          if ($val === null || $val === '') continue;
      ?>
        <div style="background:var(--gp-card-bg);border:1px solid var(--gp-card-border);border-radius:8px;padding:.5rem .75rem;text-align:center;">
          <div style="font-size:.65rem;text-transform:uppercase;color:var(--gp-muted);margin-bottom:.2rem;"><?php echo h($label); ?></div>
          <div style="font-size:1rem;font-weight:700;color:var(--gp-primary);"><?php echo h($val); ?> <span style="font-size:.65rem;color:var(--gp-muted);"><?php echo h($unit); ?></span></div>
        </div>
      <?php endforeach; ?>
    </div>
    <?php if (!empty($poolSpecs['notes'])): ?>
      <p style="margin-top:.75rem;font-size:.82rem;color:var(--gp-muted);border-top:1px solid var(--gp-card-border);padding-top:.5rem;"><?php echo h($poolSpecs['notes']); ?></p>
    <?php endif; ?>
  </div>
  <?php endif; ?>
  <!-- Project photos section removed; now accessible via photos.php tab -->
  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">💬 Χρονολόγιο & Σχόλια</h1><span>Σημειώσεις και ενέργειες έργου</span></div>
      
      <div style="background:var(--gp-card-bg); border:1px solid var(--gp-card-border); border-radius:12px; padding:12px; margin-bottom:20px;">
          <textarea id="new-comment-text" placeholder="Γράψτε ένα σχόλιο..." style="width:100%; min-height:80px; border:none; background:transparent; resize:vertical; outline:none; font-family:inherit; color:var(--gp-text);"></textarea>
          <div style="display:flex; justify-content:flex-end; margin-top:8px;">
              <button type="button" class="btn btn-sm btn-primary" id="btn-add-comment">Προσθήκη Σχολίου</button>
          </div>
      </div>
      
      <div id="timeline-list">
          <?php foreach ($projectComments as $c): ?>
          <div class="timeline-item" style="display:flex; gap:12px; margin-bottom:16px;">
              <div style="background:rgba(0,0,0,0.02); border:1px solid var(--gp-card-border); padding:10px 14px; border-radius:12px; width:100%;">
                  <div style="display:flex; justify-content:space-between; margin-bottom:4px;">
                      <span style="font-weight:700; font-size:0.85rem;"><?php echo h($c['username'] ?: 'Unknown'); ?></span>
                      <span style="font-size:0.75rem; color:var(--gp-muted);"><?php echo h(gp_date($c['created_at'], true)); ?></span>
                  </div>
                  <div style="font-size:0.9rem; line-height:1.4;"><?php echo nl2br(h($c['comment'])); ?></div>
              </div>
          </div>
          <?php endforeach; ?>
          <?php if (empty($projectComments)): ?>
            <p class="small" id="no-comments-msg">Δεν υπάρχουν σχόλια ακόμα.</p>
          <?php endif; ?>
      </div>
  </div>
  
  <script>
  document.addEventListener('DOMContentLoaded', function(){
      const btn = document.getElementById('btn-add-comment');
      const text = document.getElementById('new-comment-text');
      const list = document.getElementById('timeline-list');
      const noMsg = document.getElementById('no-comments-msg');
      
      if(btn && text) {
          btn.addEventListener('click', function(){
              const val = text.value.trim();
              if(!val) return;
              
              const ogText = btn.innerText;
              btn.innerText = 'Posting...';
              btn.disabled = true;
              
              fetch('/gopools/public/api/project_comment_add.php', {
                  method: 'POST',
                  headers: {'Content-Type': 'application/json'},
                  body: JSON.stringify({
                      project_id: <?php echo $id; ?>,
                      comment: val,
                      csrf_token: window.csrfToken
                  })
              }).then(r => r.json()).then(data => {
                  btn.innerText = ogText;
                  btn.disabled = false;
                  
                  if(data.ok && data.html) {
                      text.value = '';
                      if(noMsg) noMsg.style.display = 'none';
                      list.insertAdjacentHTML('afterbegin', data.html);
                  } else {
                      alert('Error: ' + (data.error || 'Unknown'));
                  }
              }).catch(() => {
                  btn.innerText = ogText;
                  btn.disabled = false;
                  alert('Network error.');
              });
          });
      }
  });
  </script>
  <?php endif; ?>
  
  <!-- ══════════ SCHEDULED WORK & VISITS ══════════ -->
  <div class="card" style="grid-column: 1 / -1; margin-top: 24px;">
    <div class="page-header-title" style="margin-bottom: 20px;">
      <h1 style="font-size: 1.1rem">🗓️ ΠΡΟΓΡΑΜΜΑΤΙΣΜΕΝΕΣ ΕΡΓΑΣΙΕΣ & ΕΠΙΣΚΕΨΕΙΣ</h1>
      <span style="font-size: 0.85rem;">Add extra work periods (e.g. Repairs, Mechanical Room) that show on the calendar.</span>
    </div>

    <!-- Add Visit Form -->
    <div style="background: rgba(0,0,0,0.02); border: 1px solid var(--gp-card-border); padding: 16px; border-radius: 12px; margin-bottom: 20px;">
      <h3 style="font-size: 0.85rem; margin-top: 0; margin-bottom: 12px;">Add New Period / Visit</h3>
      <div style="display: flex; gap: 12px; flex-wrap: wrap; align-items: flex-end;">
        <div class="form-group" style="margin:0; flex: 2; min-width: 200px;">
          <label style="font-size: 0.75rem;">Description / Title</label>
          <input type="text" id="visit-title" placeholder="e.g. Repairs, Installation Step 2" style="font-size: 0.85rem; padding: 6px 10px;">
        </div>
        <div class="form-group" style="margin:0; flex: 1; min-width: 140px;">
          <label style="font-size: 0.75rem;">Start Date</label>
          <input type="date" id="visit-start" style="font-size: 0.85rem; padding: 6px 10px;">
        </div>
        <div class="form-group" style="margin:0; flex: 1; min-width: 140px;">
          <label style="font-size: 0.75rem;">End Date</label>
          <input type="date" id="visit-end" style="font-size: 0.85rem; padding: 6px 10px;">
        </div>
        <button type="button" class="btn btn-primary" id="btn-add-visit" style="padding: 8px 16px;">Add to Calendar</button>
      </div>
    </div>

    <!-- Visits List -->
    <div class="table-responsive">
      <table class="table" style="font-size: 0.88rem;">
        <thead>
          <tr>
            <th>Description</th>
            <th>Start Date</th>
            <th>End Date</th>
            <th style="text-align: right;">Action</th>
          </tr>
        </thead>
        <tbody id="visits-list">
          <?php if (empty($projectVisits)): ?>
            <tr id="no-visits-row"><td colspan="4" class="text-muted" style="text-align: center; padding: 20px;">No extra visits scheduled yet.</td></tr>
          <?php else: foreach ($projectVisits as $v): ?>
            <tr data-visit-id="<?php echo $v['id']; ?>">
              <td style="font-weight: 600;"><?php echo h($v['title']); ?></td>
              <td><?php echo h(gp_date($v['start_date'])); ?></td>
              <td><?php echo h(gp_date($v['end_date'])); ?></td>
              <td style="text-align: right;">
                <button type="button" class="btn btn-sm btn-outline-danger btn-delete-visit" data-id="<?php echo $v['id']; ?>" style="font-size: 0.7rem; padding: 2px 8px;">Delete</button>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>

<!-- ══════════ POOL CALCULATOR MODAL ══════════ -->
<?php if ($id > 0): ?>
<div id="poolCalcModal" style="display:none;position:fixed;inset:0;z-index:9000;background:rgba(0,0,0,.75);overflow-y:auto;padding:2rem 1rem;">
  <div style="max-width:680px;margin:0 auto;background:#ffffff;border-radius:16px;box-shadow:0 30px 90px rgba(0,0,0,.6);padding:2.5rem;border:1px solid #e2e8f0;">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1.5rem;">
      <h2 style="margin:0;font-size:1.2rem;font-weight:800;letter-spacing:0.02em;color:#0f172a;">🧮 ΠΡΟΤΕΙΝΟΜΕΝΟΣ ΥΠΟΛΟΓΙΣΜΟΣ ΜΗΧΑΝΟΣΤΑΣΙΟΥ</h2>
      <button id="closePoolCalcBtn" style="background:none;border:none;font-size:1.8rem;cursor:pointer;color:#64748b;">&times;</button>
    </div>

    <!-- DIMENSIONS -->
    <div style="background:rgba(59,130,246,.08);border-radius:12px;padding:1.2rem;margin-bottom:1.2rem;border:1px solid rgba(59,130,246,0.1);">
      <h3 style="font-size:.85rem;font-weight:800;margin:0 0 1rem;color:#1d4ed8;letter-spacing:0.05em;">📐 ΔΙΑΣΤΑΣΕΙΣ ΠΙΣΙΝΑΣ</h3>
      <div class="form-grid" style="gap:.75rem;">
        <div class="form-group" style="padding:0"><label style="font-size:.7rem;font-weight:700;color:#64748b;">ΜΗΚΟΣ (m)</label><input type="number" border="1" step="0.01" id="pc_length" class="pc-dim" placeholder="e.g. 8" style="background:#fff;border:1px solid #cbd5e1;"></div>
        <div class="form-group" style="padding:0"><label style="font-size:.7rem;font-weight:700;color:#64748b;">ΠΛΑΤΟΣ (m)</label><input type="number" step="0.01" id="pc_width" class="pc-dim" placeholder="e.g. 4" style="background:#fff;border:1px solid #cbd5e1;"></div>
        <div class="form-group" style="padding:0"><label style="font-size:.7rem;font-weight:700;color:#64748b;">ΒΑΘΟΣ ΡΗΧΟ (m)</label><input type="number" step="0.01" id="pc_depth_shallow" class="pc-dim" placeholder="e.g. 1.2" style="background:#fff;border:1px solid #cbd5e1;"></div>
        <div class="form-group" style="padding:0"><label style="font-size:.7rem;font-weight:700;color:#64748b;">ΒΑΘΟΣ ΒΑΘΥ (m)</label><input type="number" step="0.01" id="pc_depth_deep" class="pc-dim" placeholder="e.g. 1.8" style="background:#fff;border:1px solid #cbd5e1;"></div>
      </div>
    </div>

    <!-- CALCULATED / EDITABLE EQUIPMENT -->
    <div style="background:rgba(16,185,129,.08);border-radius:12px;padding:1.2rem;margin-bottom:1.5rem;border:1px solid rgba(16,185,129,0.1);">
      <h3 style="font-size:.85rem;font-weight:800;margin:0 0 1rem;color:#047857;letter-spacing:0.05em;">⚙️ ΥΠΟΛΟΓΙΣΜΟΣ ΕΞΟΠΛΙΣΜΟΥ</h3>
      <div class="form-grid" style="gap:.75rem;">
        <div class="form-group" style="padding:0"><label style="font-size:.7rem;font-weight:700;color:#64748b;">ΟΓΚΟΣ (m³)</label><input type="number" step="0.01" id="pc_volume" placeholder="-" style="background:#f8fafc;border:1px solid #cbd5e1;" readonly></div>
        <div class="form-group" style="padding:0"><label style="font-size:.7rem;font-weight:700;color:#64748b;">ΑΝΤΛΙΑ (m³/h)</label><input type="number" step="0.1" id="pc_pump" placeholder="-" style="background:#fff;border:1px solid #cbd5e1;"></div>
        <div class="form-group" style="padding:0"><label style="font-size:.7rem;font-weight:700;color:#64748b;">ΦΙΛΤΡΟ (∅ mm)</label><input type="number" step="1" id="pc_filter" placeholder="-" style="background:#fff;border:1px solid #cbd5e1;"></div>
        <div class="form-group" style="padding:0"><label style="font-size:.7rem;font-weight:700;color:#64748b;">ΣΚΙΜΕΡ</label><input type="number" step="1" id="pc_skimmer" placeholder="-" style="background:#fff;border:1px solid #cbd5e1;"></div>
        <div class="form-group" style="padding:0"><label style="font-size:.7rem;font-weight:700;color:#64748b;">ΣΤΟΜΙΑ ΕΠΙΣΤΡΟΦΗΣ</label><input type="number" step="1" id="pc_outlets" placeholder="-" style="background:#fff;border:1px solid #cbd5e1;"></div>
        <div class="form-group" style="padding:0"><label style="font-size:.7rem;font-weight:700;color:#64748b;">ΦΡΕΑΤΙΑ ΠΥΘΜΕΝΑ</label><input type="number" step="1" id="pc_drains" placeholder="-" style="background:#fff;border:1px solid #cbd5e1;"></div>
        <div class="form-group" style="padding:0"><label style="font-size:.7rem;font-weight:700;color:#64748b;">ΣΚΟΥΠΑ</label><input type="number" step="1" id="pc_vacuum" placeholder="-" style="background:#fff;border:1px solid #cbd5e1;"></div>
        <div class="form-group" style="padding:0"><label style="font-size:.7rem;font-weight:700;color:#64748b;">ΦΩΤΙΣΤΙΚΑ</label><input type="number" step="1" id="pc_lights" placeholder="-" style="background:#fff;border:1px solid #cbd5e1;"></div>
      </div>
      <div class="form-group" style="margin-top:1rem;padding:0"><label style="font-size:.7rem;font-weight:700;color:#64748b;">ΣΗΜΕΙΩΣΕΙΣ</label><textarea id="pc_notes" rows="2" placeholder="Επιπλέον σημειώσεις..." style="background:#fff;border:1px solid #cbd5e1;font-size:0.85rem;"></textarea></div>
    </div>

    <div id="pc_feedback" style="display:none;margin-bottom:1rem;font-size:.85rem;font-weight:700;text-align:center;"></div>
    
    <div style="display:flex;flex-direction:column;gap:1.5rem;">
      <div style="display:flex;gap:.75rem;">
        <button type="button" id="savePoolSpecsBtn" class="btn btn-primary" style="flex:1;padding:12px;font-weight:700;">💾 ΑΠΟΘΗΚΕΥΣΗ ΥΠΟΛΟΓΙΣΜΟΥ</button>
        <button type="button" id="closePoolCalcBtn2" class="btn btn-secondary" style="padding:12px;">ΑΚΥΡΟ</button>
      </div>

      <div style="display:flex;gap:1rem;padding-top:1rem;border-top:1px solid #f1f5f9;">
        <button type="button" class="btn btn-outline-light" style="flex:1;font-size:0.8rem;opacity:0.6;cursor:not-allowed;" disabled>📦 ΥΛΙΚΑ ΜΗΧΑΝΟΣΤΑΣΙΟΥ</button>
        <button type="button" class="btn btn-outline-light" style="flex:1;font-size:0.8rem;opacity:0.6;cursor:not-allowed;" disabled>📜 ΣΧΕΔΙΟ</button>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  const specs = <?php echo json_encode($poolSpecs ?: new stdClass(), JSON_UNESCAPED_UNICODE); ?>;
  const modal = document.getElementById('poolCalcModal');
  const openBtn = document.getElementById('openPoolCalcBtn');
  const closeBtn = document.getElementById('closePoolCalcBtn');
  const closeBtn2 = document.getElementById('closePoolCalcBtn2');
  const saveBtn = document.getElementById('savePoolSpecsBtn');
  const fb = document.getElementById('pc_feedback');

  // Pre-fill from saved specs
  function prefill() {
    const map = {
      pc_length: 'length', pc_width: 'width',
      pc_depth_shallow: 'depth_shallow', pc_depth_deep: 'depth_deep',
      pc_volume: 'volume_m3',
      pc_pump: 'pump_flow_m3h', pc_filter: 'filter_diam_mm',
      pc_skimmer: 'skimmer_count',
      pc_outlets: 'outlet_count', pc_drains: 'main_drain_count',
      pc_vacuum: 'vacuum_point_count', pc_lights: 'lighting_count',
      pc_notes: 'notes'
    };
    for (const [elId, key] of Object.entries(map)) {
      const el = document.getElementById(elId);
      if (el && specs[key] != null) el.value = specs[key];
    }
  }

  // Auto-calculate when dimensions change
  function calculate() {
    const L = parseFloat(document.getElementById('pc_length').value) || 0;
    const W = parseFloat(document.getElementById('pc_width').value) || 0;
    const Ds = parseFloat(document.getElementById('pc_depth_shallow').value) || 0;
    const Dd = parseFloat(document.getElementById('pc_depth_deep').value) || 0;
    if (!L || !W || !Ds || !Dd) return;

    const avgDepth = (Ds + Dd) / 2;
    const vol = parseFloat((L * W * avgDepth).toFixed(2));
    const pump = parseFloat((vol / 4).toFixed(1));
    // Filter: A = flow/30, d = sqrt(A*4/pi)*1000
    const filterArea = pump / 30;
    const filterDiam = Math.ceil(Math.sqrt(filterArea * 4 / Math.PI) * 1000 / 50) * 50;
    const skimmers = Math.max(1, Math.round(L * W / 30));
    const inlets  = Math.max(2, Math.round(vol / 20));
    const outlets  = Math.max(2, Math.round(vol / 25));
    const lights  = Math.max(1, Math.round(L * W / 20));

    document.getElementById('pc_volume').value  = vol;
    document.getElementById('pc_pump').value    = pump;
    document.getElementById('pc_filter').value  = filterDiam;
    document.getElementById('pc_skimmer').value = skimmers;
    document.getElementById('pc_outlets').value = outlets;
    document.getElementById('pc_drains').value  = 2;
    document.getElementById('pc_vacuum').value  = 1;
    document.getElementById('pc_lights').value  = lights;
  }

  document.querySelectorAll('.pc-dim').forEach(el => el.addEventListener('input', calculate));

  openBtn?.addEventListener('click', () => { prefill(); modal.style.display = 'block'; });
  document.getElementById('openPoolCalcBtn2')?.addEventListener('click', () => { prefill(); modal.style.display = 'block'; });
  closeBtn?.addEventListener('click', () => modal.style.display = 'none');
  closeBtn2?.addEventListener('click', () => modal.style.display = 'none');
  modal?.addEventListener('click', e => { if (e.target === modal) modal.style.display = 'none'; });

  saveBtn?.addEventListener('click', function() {
    const data = new FormData();
    data.append('project_id', <?php echo $id; ?>);
    data.append('csrf_token', window.csrfToken || '');
    const map = {
      length: 'pc_length', width: 'pc_width',
      depth_shallow: 'pc_depth_shallow', depth_deep: 'pc_depth_deep',
      volume_m3: 'pc_volume', 
      pump_flow_m3h: 'pc_pump', filter_diam_mm: 'pc_filter',
      skimmer_count: 'pc_skimmer',
      outlet_count: 'pc_outlets', main_drain_count: 'pc_drains',
      vacuum_point_count: 'pc_vacuum', lighting_count: 'pc_lights',
      notes: 'pc_notes'
    };
    for (const [key, elId] of Object.entries(map)) {
      const el = document.getElementById(elId);
      if (el) data.append(key, el.value || '');
    }
    saveBtn.disabled = true; saveBtn.textContent = 'ΑΠΟΘΗΚΕΥΣΗ...';
    fetch('/gopools/public/api/save_pool_specs.php', { method:'POST', body:data })
      .then(r => r.json()).then(res => {
        fb.style.display = 'block';
        if (res.ok) {
          fb.textContent = '✅ Ο ΥΠΟΛΟΓΙΣΜΟΣ ΑΠΟΘΗΚΕΥΤΗΚΕ!';
          fb.style.color = '#16a34a';
          setTimeout(() => location.reload(), 800);
        } else {
          fb.textContent = '❌ ' + (res.error || 'Σφάλμα');
          fb.style.color = '#dc2626';
          saveBtn.disabled = false; saveBtn.textContent = '💾 ΑΠΟΘΗΚΕΥΣΗ ΥΠΟΛΟΓΙΣΜΟΥ';
        }
      }).catch(() => {
        fb.style.display = 'block';
        fb.textContent = '❌ Network error';
        fb.style.color = '#dc2626';
        saveBtn.disabled = false; saveBtn.textContent = '💾 Save Specs';
      });
  });
})();
</script>
<?php endif; ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
  // ─── CITY SUGGESTIONS ───
  const cityInput = document.getElementById('project-city');
  const cityDatalist = document.getElementById('city-list');
  if (cityInput && cityDatalist) {
    // --- Automated Location & Distance ---
    const cityInput = document.getElementById('project-city');
    const distInput = document.getElementById('project-distance');
    const latInput = document.getElementById('project-lat');
    const lngInput = document.getElementById('project-lng');
    
    if (cityInput && distInput) {
        let cityTimeout;
        cityInput.addEventListener('input', function() {
            clearTimeout(cityTimeout);
            cityTimeout = setTimeout(() => {
                const city = this.value.trim();
                if (city.length < 3) return;
                
                // Show loading state if we want, or just fetch
                fetch('/gopools/public/api/geocode_dist.php?city=' + encodeURIComponent(city))
                .then(r => r.json())
                .then(data => {
                    if (data.ok) {
                        distInput.value = data.distance_km;
                        if (latInput) latInput.value = data.lat;
                        if (lngInput) lngInput.value = data.lng;
                    }
                });
            }, 800);
        });
    }

    fetch('/gopools/public/api/city_suggestions.php')
      .then(r => r.json())
      .then(data => {
        if (data.ok && data.cities) {
          data.cities.forEach(city => {
            const opt = document.createElement('option');
            opt.value = city;
            cityDatalist.appendChild(opt);
          });
        }
      });
  }

  // ─── VISITS MANAGEMENT ───
  const btnAddVisit = document.getElementById('btn-add-visit');
  const visitsList = document.getElementById('visits-list');
  const noVisitsRow = document.getElementById('no-visits-row');

  if (btnAddVisit) {
    btnAddVisit.addEventListener('click', function() {
      const title = document.getElementById('visit-title').value.trim();
      const start = document.getElementById('visit-start').value;
      const end = document.getElementById('visit-end').value;

      if (!title || !start || !end) {
        alert('Please fill all fields for the visit.');
        return;
      }

      btnAddVisit.disabled = true;
      btnAddVisit.innerText = 'Adding...';

      fetch('/gopools/public/api/visit_add.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          project_id: <?php echo (int)$id; ?>,
          title: title,
          start_date: start,
          end_date: end
        })
      })
      .then(r => r.json())
      .then(res => {
        btnAddVisit.disabled = false;
        btnAddVisit.innerText = 'Add to Calendar';
        if (res.ok) {
          if (noVisitsRow) noVisitsRow.remove();
          const tr = document.createElement('tr');
          tr.setAttribute('data-visit-id', res.id);
          const formatDateJS = (s) => { if(!s) return ''; const bits = s.split('-'); return bits[2]+'/'+bits[1]+'/'+bits[0]; };

          tr.innerHTML = `
            <td style="font-weight: 600;">${title}</td>
            <td>${formatDateJS(start)}</td>
            <td>${formatDateJS(end)}</td>
            <td style="text-align: right;">
              <button type="button" class="btn btn-sm btn-outline-danger btn-delete-visit" data-id="${res.id}" style="font-size: 0.7rem; padding: 2px 8px;">Delete</button>
            </td>
          `;
          visitsList.appendChild(tr);
          // Clear inputs
          document.getElementById('visit-title').value = '';
          document.getElementById('visit-start').value = '';
          document.getElementById('visit-end').value = '';
          
          // Re-attach delete listeners (could be more efficient with delegation)
          attachDeleteListeners();
        } else {
          alert('Error: ' + res.error);
        }
      });
    });
  }

  function attachDeleteListeners() {
    document.querySelectorAll('.btn-delete-visit').forEach(btn => {
      btn.onclick = function() {
        if (!confirm('Are you sure you want to delete this scheduled visit?')) return;
        const id = this.getAttribute('data-id');
        fetch('/gopools/public/api/visit_delete.php', {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({ id: id })
        })
        .then(r => r.json())
        .then(res => {
          if (res.ok) {
            document.querySelector(`tr[data-visit-id="${id}"]`).remove();
          } else {
            alert('Error: ' + res.error);
          }
        });
      };
    });
  }
  attachDeleteListeners();
});
</script>

<script>
// ═══ COMPLETION WARNING LOGIC ═══
(function() {
  const saveBtn    = document.getElementById('btn-save-project');
  const statusSel  = document.getElementById('status-select');
  const budgetInp  = document.getElementById('budget-input');
  const modal      = document.getElementById('completion-warning-modal');
  const modalStatus= document.getElementById('modal-budget-status');
  const goBack     = document.getElementById('modal-go-back');
  const proceedBtn = document.getElementById('modal-proceed-anyway');
  const theForm    = saveBtn ? saveBtn.closest('form') : null;

  if (!saveBtn || !theForm) return;

  // Completed status codes (check both common variations)
  const completedCodes = ['completed', 'done', 'ολοκληρωμένο', 'finished'];

  function isCompletedStatus() {
    if (!statusSel) return false;
    return completedCodes.includes((statusSel.value || '').toLowerCase());
  }

  function getBudget() {
    if (!budgetInp) return null;
    const v = budgetInp.value.trim();
    return v === '' ? null : parseFloat(v.replace(',', '.'));
  }

  saveBtn.addEventListener('click', function() {
    const budget = getBudget();

    if (isCompletedStatus() && (budget === null || budget <= 0)) {
      // Show warning modal
      if (modalStatus) {
        if (budget === null || budget === 0) {
          modalStatus.innerHTML = '❌ <span style="color:#dc2626;">Δεν έχει καταχωρηθεί κοστολόγιο (Budget = κενό)</span>';
        } else {
          modalStatus.innerHTML = `⚠️ <span style="color:#d97706;">Budget: €${budget.toFixed(2)}</span>`;
        }
      }
      if (modal) {
        modal.style.display = 'flex';
        // Dark mode support
        const inner = modal.querySelector('div');
        if (inner && document.documentElement.getAttribute('data-theme') === 'dark') {
          inner.style.background = '#1e293b';
          inner.style.color = '#e2e8f0';
          inner.querySelectorAll('h2,p,div').forEach(el => {
            if (!el.style.color) el.style.color = '#e2e8f0';
          });
        }
      }
      return; // Block form submission
    }

    // No issues - submit form
    theForm.submit();
  });

  // Modal: go back
  if (goBack) {
    goBack.addEventListener('click', function() {
      if (modal) modal.style.display = 'none';
      // Focus budget field for easy correction
      if (budgetInp) { budgetInp.focus(); budgetInp.select(); }
    });
  }

  // Modal: proceed anyway
  if (proceedBtn) {
    proceedBtn.addEventListener('click', function() {
      if (modal) modal.style.display = 'none';
      theForm.submit();
    });
  }

  // Close modal on outside click
  if (modal) {
    modal.addEventListener('click', function(e) {
      if (e.target === modal) modal.style.display = 'none';
    });
  }
})();
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
