<?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 = 'Project map';

$projectId = (int)($_GET['project_id'] ?? 0);
if ($projectId <= 0) die('Missing project_id.');

// Όλοι οι logged-in χρήστες μπορούν να δουν τον χάρτη.
// Μόνο αυτοί με edit rights μπορούν να αποθηκεύσουν αλλαγές.
$canEditMap = gp_can_edit_project($pdo, $projectId);

$stmt = $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
");
$stmt->execute([':id' => $projectId]);
$project = $stmt->fetch();
if (!$project) die('Project not found.');

$errors = [];
$ok = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $canEditMap) {
    gp_require_csrf();
    $address = trim((string)($_POST['address'] ?? ''));
    $city = trim((string)($_POST['city'] ?? ''));
    $lat = trim((string)($_POST['latitude'] ?? ''));
    $lng = trim((string)($_POST['longitude'] ?? ''));

    if ($lat !== '' && !is_numeric($lat)) $errors[] = 'Latitude must be numeric.';
    if ($lng !== '' && !is_numeric($lng)) $errors[] = 'Longitude must be numeric.';
    $distanceKm = trim((string)($_POST['distance_km'] ?? ''));
    if ($distanceKm !== '' && !is_numeric($distanceKm)) $errors[] = 'Distance must be numeric.';

    if (!$errors) {
        $stmt = $pdo->prepare("
            UPDATE projects
            SET address = :address,
                city = :city,
                latitude = :latitude,
                longitude = :longitude,
                distance_km = :distance_km
            WHERE id = :id
        ");
        $stmt->execute([
            ':address' => $address !== '' ? $address : null,
            ':city' => $city !== '' ? $city : null,
            ':latitude' => $lat !== '' ? $lat : null,
            ':longitude' => $lng !== '' ? $lng : null,
            ':distance_km' => $distanceKm !== '' ? $distanceKm : null,
            ':id' => $projectId,
        ]);

        $stmt = $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
        ");
        $stmt->execute([':id' => $projectId]);
        $project = $stmt->fetch();
        $ok = 'Location updated.';
    }
}

$addressParts = array_filter([
    (string)($project['address'] ?? ''),
    (string)($project['city'] ?? ''),
]);
$addressQuery = trim(implode(', ', $addressParts));

$mapsUrl = '';
$embedUrl = '';
if (!empty($project['latitude']) && !empty($project['longitude'])) {
    $coords = $project['latitude'] . ',' . $project['longitude'];
    $mapsUrl = 'https://www.google.com/maps?q=' . rawurlencode($coords);
    $embedUrl = 'https://www.google.com/maps?q=' . rawurlencode($coords) . '&z=15&output=embed';
} elseif ($addressQuery !== '') {
    $mapsUrl = 'https://www.google.com/maps/search/?api=1&query=' . rawurlencode($addressQuery);
    $embedUrl = 'https://www.google.com/maps?q=' . rawurlencode($addressQuery) . '&z=15&output=embed';
}

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

<div class="page-header">
  <div class="page-header-title">
    <h1>Project map</h1>
    <span><?php echo h($project['code'] . ' · ' . $project['title']); ?></span>
  </div>
  <div class="page-header-actions">
    <a class="btn btn-secondary btn-sm" href="/gopools/public/projects/edit.php?id=<?php echo (int)$projectId; ?>">? ??s? st? ????</a>
  </div>
</div>

<div class="grid-2">
  <div class="card">
    <?php if ($ok): ?>
      <div class="alert-danger" style="background:rgba(22,163,74,.15);color:#bbf7d0;border-color:rgba(22,163,74,.35)"><?php echo h($ok); ?></div>
    <?php endif; ?>
    <?php if ($errors): ?>
      <div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div>
    <?php endif; ?>

    <div class="page-header-title">
      <h1 style="font-size:1.05rem">Location details</h1>
      <span>Address, coordinates, navigation</span>
    </div>

    <?php if ($canEditMap): ?>
    <form method="post">
      <?php echo csrf_field(); ?>
      <div class="form-grid">
        <div class="form-group">
          <label>Address</label>
          <input type="text" name="address" id="map-address" value="<?php echo h($project['address']); ?>" placeholder="Street, number">
        </div>
        <div class="form-group">
          <label>City</label>
          <input type="text" name="city" id="map-city" value="<?php echo h($project['city']); ?>" placeholder="City">
        </div>
        <div class="form-group">
          <label>Latitude</label>
          <input type="text" name="latitude" id="map-lat" value="<?php echo h($project['latitude']); ?>" placeholder="37.983810">
        </div>
        <div class="form-group">
          <label>Longitude</label>
          <input type="text" name="longitude" id="map-lng" value="<?php echo h($project['longitude']); ?>" placeholder="23.727539">
        </div>
        <div class="form-group">
          <label>Kilometric Distance (km)</label>
          <input type="number" step="0.1" name="distance_km" id="map-distance" value="<?php echo h($project['distance_km']); ?>" placeholder="e.g. 15.5">
          <small style="color:var(--gp-muted); font-size:0.75rem;">Calculated from: Grevenon 56, Ano Liosia</small>
        </div>
      </div>
      <div class="form-actions">
        <button class="btn btn-primary" type="submit">Save location</button>
        <?php if ($mapsUrl): ?>
          <a class="btn btn-secondary" href="<?php echo h($mapsUrl); ?>" target="_blank" rel="noopener">Open in Google Maps</a>
        <?php endif; ?>
      </div>
    </form>
    <?php else: ?>
    <div style="padding:10px 0;">
      <div style="font-size:.85rem;color:var(--gp-muted);margin-bottom:6px;">📍 Διεύθυνση: <strong style="color:var(--gp-text);"><?php echo h(trim(($project['address'] ?? '') . ' ' . ($project['city'] ?? ''))); ?></strong></div>
      <?php if ($project['latitude'] && $project['longitude']): ?>
      <div style="font-size:.8rem;color:var(--gp-muted);">
        Συντεταγμένες: <?php echo h($project['latitude']); ?>, <?php echo h($project['longitude']); ?>
      </div>
      <?php endif; ?>
      <?php if ($mapsUrl): ?>
        <a class="btn btn-secondary btn-sm" href="<?php echo h($mapsUrl); ?>" target="_blank" rel="noopener" style="margin-top:12px;">🗺️ Άνοιγμα στο Google Maps</a>
      <?php endif; ?>
    </div>
    <?php endif; ?>

    <div style="margin-top:14px">
      <div class="small">Customer</div>
      <div><?php echo h($project['customer_name']); ?></div>
      <div class="small" style="margin-top:8px">Phone</div>
      <div><?php echo h($project['customer_phone']); ?></div>
      <div class="small" style="margin-top:8px">Email</div>
      <div><?php echo h($project['customer_email']); ?></div>
    </div>
  </div>

  <div class="card">
    <div class="page-header-title">
      <h1 style="font-size:1.05rem">Map preview</h1>
      <span>Embedded location view</span>
    </div>

    <?php if ($embedUrl): ?>
      <div style="margin-bottom:12px">
        <iframe
          src="<?php echo h($embedUrl); ?>"
          style="width:100%;height:420px;border:0;border-radius:14px"
          loading="lazy"
          referrerpolicy="no-referrer-when-downgrade"></iframe>
      </div>
      <div class="form-actions">
        <a class="btn btn-primary btn-sm" href="<?php echo h($mapsUrl); ?>" target="_blank" rel="noopener">Navigate</a>
      </div>
    <?php else: ?>
      <p class="small">Add address or coordinates to show the map.</p>
    <?php endif; ?>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const cityInput = document.getElementById('map-city');
    const distInput = document.getElementById('map-distance');
    const latInput = document.getElementById('map-lat');
    const lngInput = document.getElementById('map-lng');
    
    if (cityInput && distInput) {
        let cityTimeout;
        cityInput.addEventListener('input', function() {
            clearTimeout(cityTimeout);
            cityTimeout = setTimeout(() => {
                const city = this.value.trim();
                if (city.length < 3) return;
                
                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);
        });
    }
});
</script>

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