<?php
require __DIR__ . '/../_boot.php';
require __DIR__ . '/../partials/nav.php';
require __DIR__ . '/../partials/map_settings.php';
$canEditRoutes = $user && \App\Core\Auth::hasPermission('routes.manage', $user);
$canDeleteRoutes = $user && \App\Core\Auth::hasPermission('routes.delete', $user);
if (!$user || (!$canEditRoutes && !$canDeleteRoutes)) { header('Location: dashboard.php'); exit; }
$mapContext = pyrk_map_context();
$mapProvider = $mapContext['provider'];
$mapsKey = $mapContext['google_key'];
$center = $mapContext['center'];
$osmTileUrl = $mapContext['osm_tile_url'];
$osmAttribution = $mapContext['osm_attribution'];
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Routes</title>
  <link rel="stylesheet" href="../assets/css/app.css">
  <link rel="stylesheet" href="../assets/css/permissions_delete_actions.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_wide_pages.css">
  <link rel="stylesheet" href="../assets/css/admin_route_points_drag.css?v=2-smart-nav">
  <link rel="stylesheet" href="../assets/css/google_map_search.css?v=1">
  <link rel="stylesheet" href="../assets/css/admin_routes_duplicate_pro.css?v=1">
  <?php if ($mapProvider === 'osm'): ?><link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIINfQFuHMwOTZpQdXStT2Pv8bBTaFslN8=" crossorigin=""><?php endif; ?>
</head>
<body>
<?php pyrk_render_nav('admin'); ?>
<main class="container admin-wide-page route-admin-page">
  <section class="page-hero admin-hero">
    <div>
      <p class="eyebrow"><?= $mapProvider === 'osm' ? 'Free OpenStreetMap route builder' : 'Google Maps route builder' ?></p>
      <h1>Routes library</h1>
      <p class="muted">Create, edit, and display walking routes with start points, checkpoints, water stations, medical points, and finish points.</p>
    </div>
    <?php if ($canEditRoutes): ?><a class="btn" href="#routeEditor">Create route</a><?php endif; ?>
  </section>

  <?php if ($mapProvider !== 'osm' && !$mapsKey): ?><p class="notice bad">Google Maps browser key is missing. Add it in <code>config/app.php</code> or switch <code>maps.provider</code> to <code>osm</code>.</p><?php endif; ?>
  <?php if ($mapProvider === 'osm'): ?><p class="notice good">Free test mode active: OpenStreetMap + Leaflet. No Google key required.</p><?php endif; ?>

  <section class="route-library-panel panel">
    <div class="section-head">
      <div>
        <p class="eyebrow">Saved routes</p>
        <h2>Beautiful route cards</h2>
      </div>
      <div class="inline-controls search-controls">
        <input id="routeSearch" placeholder="Search routes">
        <select id="difficultyFilter"><option value="">All difficulty</option><option value="easy">Easy</option><option value="medium">Medium</option><option value="hard">Hard</option></select>
      </div>
    </div>
    <div id="routesList" class="route-card-grid"></div>
  </section>

  <section class="panel route-editor-panel" id="routeEditor">
    <div class="section-head">
      <div>
        <p class="eyebrow">Route editor</p>
        <h2 id="routeFormTitle">Create route</h2>
      </div>
      <div class="inline-controls">
        <button class="btn btn-light btn-small" id="newRouteBtn" type="button">New route</button>
        <button class="btn btn-small" id="resetRouteBtn" type="button">Reset points</button>
      </div>
    </div>

    <div class="route-builder-grid">
      <form id="routeForm" class="route-form stack-form">
        <input type="hidden" name="id" id="routeId">
        <div class="form-grid two">
          <label>Route name<input name="route_name" id="routeName" placeholder="Route name" required></label>
          <label>Difficulty<select name="difficulty" id="difficulty"><option value="easy">Easy</option><option value="medium">Medium</option><option value="hard">Hard</option></select></label>
          <label>Start point<input name="start_address" id="startAddress" placeholder="Start point / address" required></label>
          <label>Finish point<input name="end_address" id="endAddress" placeholder="Finish point / address" required></label>
          <label>Total KM<input name="total_km" id="totalKm" type="number" step="0.01" placeholder="Total KM" required></label>
          <label>Expected duration<input name="expected_duration_minutes" id="durationMinutes" type="number" placeholder="Minutes" value="60"></label>
          <label>Status<select name="status" id="routeStatus"><option value="active">Active</option><option value="inactive">Inactive</option><option value="archived">Archived</option></select></label>
        </div>
        <label>Description<textarea name="description" id="routeDescription" placeholder="Description"></textarea></label>
        <input type="hidden" name="google_polyline" id="googlePolyline">
        <input type="hidden" name="map_bounds_json" id="mapBoundsJson">
        <label class="field-label">Route points JSON</label>
        <textarea name="points_json" id="pointsJson" class="codebox">[]</textarea>
        <div class="inline-controls"><button class="btn btn-secondary" id="calculateRouteBtn" type="button">Calculate distance</button><button class="btn" type="submit" id="saveRouteBtn">Save route</button></div>
        <p id="routeMsg" class="notice"></p>
      </form>

      <div>
        <div class="map-toolbar">
          <button class="btn btn-small" data-point-type="start" type="button">Add start</button>
          <button class="btn btn-small" data-point-type="checkpoint" type="button">Add checkpoint</button>
          <button class="btn btn-small" data-point-type="water_station" type="button">Add water</button>
          <button class="btn btn-small" data-point-type="medical_station" type="button">Add medical</button>
          <button class="btn btn-small" data-point-type="rest_station" type="button">Add rest</button>
          <button class="btn btn-small" data-point-type="end" type="button">Add finish</button>
        </div>
        <?php if ($mapProvider !== 'osm'): ?>
        <div class="google-map-search-bar">
          <input id="routeMapSearch" type="search" placeholder="Search address, café, landmark...">
          <button class="btn btn-light btn-small" id="addSearchedPlacePointBtn" type="button" disabled>Add searched place as selected point</button>
        </div>
        <?php endif; ?>
        <div id="routeBuilderMap" class="map-canvas"></div>
        <p class="muted small">Click a point type, then click the map. Drag markers to adjust. Use “Calculate distance” before saving.</p>
        <div id="routePointsList" class="route-points-list"></div>
      </div>
    </div>
  </section>
</main>

<div class="modal-backdrop route-duplicate-backdrop" id="routeDuplicateModal" hidden>
  <div class="modal-card route-duplicate-modal" role="dialog" aria-modal="true" aria-labelledby="routeDuplicateTitle">
    <div class="modal-head">
      <div>
        <p class="eyebrow">Safe route copy</p>
        <h2 id="routeDuplicateTitle">Duplicate route</h2>
        <p class="muted">Create a complete editable copy without changing the original route.</p>
      </div>
      <button class="icon-btn" id="closeRouteDuplicateBtn" type="button" aria-label="Close duplicate route dialog">×</button>
    </div>

    <form id="routeDuplicateForm" class="stack-form">
      <input type="hidden" id="routeDuplicateSourceId" value="">

      <div class="route-duplicate-source-card">
        <span class="route-duplicate-icon" aria-hidden="true">⧉</span>
        <div>
          <small>Copying from</small>
          <strong id="routeDuplicateSourceName">Route</strong>
          <span id="routeDuplicateSourceMeta">Full route details and points will be copied.</span>
        </div>
      </div>

      <label>New route name
        <input id="routeDuplicateName" maxlength="180" autocomplete="off" required>
      </label>

      <div class="route-duplicate-safety-grid">
        <div><strong>Complete copy</strong><span>Map path, addresses, distance, duration, difficulty, checkpoints, stations, and QR settings.</span></div>
        <div><strong>No walk links</strong><span>Existing scheduled walks remain connected only to the original route.</span></div>
        <div><strong>Starts inactive</strong><span>The copy cannot be used accidentally until you review and activate it.</span></div>
      </div>

      <p id="routeDuplicateMsg" class="notice" hidden></p>
      <div class="modal-actions">
        <button class="btn btn-light" id="cancelRouteDuplicateBtn" type="button">Cancel</button>
        <button class="btn" id="confirmRouteDuplicateBtn" type="submit">Duplicate &amp; edit</button>
      </div>
    </form>
  </div>
</div>

<script>window.PYRK_API_BASE='../../api'; window.PYRK_CSRF='<?= htmlspecialchars($csrf) ?>'; window.PYRK_MAP_CENTER=<?= json_encode($center) ?>; window.PYRK_MAP_PROVIDER='<?= htmlspecialchars($mapProvider) ?>'; window.PYRK_OSM_TILE_URL=<?= json_encode($osmTileUrl) ?>; window.PYRK_OSM_ATTRIBUTION=<?= json_encode($osmAttribution) ?>; window.PYRK_CAN_EDIT_ROUTES=<?= $canEditRoutes ? 'true' : 'false' ?>; window.PYRK_CAN_DELETE_ROUTES=<?= $canDeleteRoutes ? 'true' : 'false' ?>;</script>
<script src="../assets/js/api.js"></script>
<?php if ($mapProvider === 'osm'): ?>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<?php endif; ?>
<script src="../assets/js/admin_routes.js?v=route-duplicate-pro-v1"></script>
<?php if ($mapProvider !== 'osm' && $mapsKey): ?>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=<?= urlencode($mapsKey) ?>&loading=async&libraries=geometry,marker,places&callback=initPyrkRouteBuilder"></script>
<?php endif; ?>
</body>
</html>
