<?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.');
gp_require_project_edit($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') {
    $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.';

    if (!$errors) {
        $stmt = $pdo->prepare("
            UPDATE projects
            SET address = :address,
                city = :city,
                latitude = :latitude,
                longitude = :longitude
            WHERE id = :id
        ");
        $stmt->execute([
            ':address' => $address !== '' ? $address : null,
            ':city' => $city !== '' ? $city : null,
            ':latitude' => $lat !== '' ? $lat : null,
            ':longitude' => $lng !== '' ? $lng : 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';
?>
<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="/public/projects/edit.php?id=<?php echo (int)$projectId; ?>">Back to project</a>
  </div>
</div>

<?php gp_render_project_menu($pdo, $projectId); ?>

<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>

    <form method="post">
      <div class="form-grid">
        <div class="form-group">
          <label>Address</label>
          <input type="text" name="address" value="<?php echo h($project['address']); ?>" placeholder="Street, number">
        </div>
        <div class="form-group">
          <label>City</label>
          <input type="text" name="city" value="<?php echo h($project['city']); ?>" placeholder="City">
        </div>
        <div class="form-group">
          <label>Latitude</label>
          <input type="text" name="latitude" value="<?php echo h($project['latitude']); ?>" placeholder="37.983810">
        </div>
        <div class="form-group">
          <label>Longitude</label>
          <input type="text" name="longitude" value="<?php echo h($project['longitude']); ?>" placeholder="23.727539">
        </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>

    <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>

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