<?php
/**
 * Template Name: Single Tour - Compatible with main.js
 * Template Post Type: tour
 */
if ( ! defined( 'ABSPATH' ) ) exit;
get_header();

// ---------- Helper functions for post processing metadata ----------
function tom_featured_image_url( $post_id, $size = 'full' ) {
    $id = get_post_thumbnail_id( $post_id );
    return $id ? wp_get_attachment_image_url( $id, $size ) : '';
}
function tom_get_meta_lines( $post_id, $key ) {
    $val = get_post_meta( $post_id, $key, true );
    if ( empty( $val ) ) return array();
    if ( is_array( $val ) ) return $val;
    return array_filter( array_map( 'trim', explode( "\n", $val ) ) );
}
function tom_get_itinerary( $post_id ) {
    $raw = get_post_meta( $post_id, 'tom_itinerary', true );
    if ( is_string( $raw ) ) {
        $decoded = json_decode( $raw, true );
        return is_array( $decoded ) ? $decoded : array();
    }
    return is_array( $raw ) ? $raw : array();
}
?>

<style>
/* --- Leaflet Canvas Framework Frame Reset --- */
#leaflet-route-map,
#tour-map,
#tom-itin-map-canvas,
[data-tom-tour-map],
[data-tom-item-map] {
    width: 100% !important;
    height: 380px !important;
    min-height: 280px !important;
    background-color: #eaeaea !important;
    position: relative;
    z-index: 1;
    border-radius: 12px;
    overflow: hidden;
}

/* --- Map Custom Markers Luxury Resolution --- */
.leaflet-marker-icon.tom-pin-wrap {
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
    overflow: visible !important;
}

.tom-map-marker-luxury {
    width: 32px !important;
    height: 32px !important;
    background: #b8860b !important;
    border: 2px solid #ffffff !important;
    border-radius: 50% 50% 50% 0 !important;
    transform: rotate(-45deg) !important;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -16px;
    margin-top: -16px;
    display: flex !important;
    align-items: center;
    justify-content: center;
    box-shadow: 0 3px 10px rgba(0,0,0,0.3);
    box-sizing: border-box;
    z-index: 500;
}

.tom-map-marker-luxury span {
    transform: rotate(45deg) !important;
    display: block;
    width: 100%;
    color: #ffffff !important;
    font-weight: 700 !important;
    font-size: 12px !important;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
    text-align: center;
    line-height: 1;
}

/* ================================================================
   FIXED: FORCE TWO-COLUMN FLEX LAYOUT (sidebar to the right)
   ================================================================ */
.tom-flex-layout {
    display: flex !important;
    flex-wrap: nowrap !important;    /* prevents sidebar from wrapping */
    gap: 2.5rem !important;
    justify-content: space-between !important;
    align-items: flex-start !important;
    max-width: 1200px !important;
    margin: 2rem auto !important;
    width: 100% !important;
    padding: 0 1.5rem !important;
    box-sizing: border-box !important;
}

.tom-main-content {
    flex: 1 1 0 !important;          /* allows main to shrink if needed */
    min-width: 0 !important;
    overflow: hidden !important;     /* prevents overflow from breaking layout */
    box-sizing: border-box !important;
    line-height: 1.7;
    color: #333;
}

.tom-main-content h1 {
    font-size: 2.4rem;
    color: #1e5631;
    margin: 0 0 0.75rem 0;
    font-weight: 700;
}

.tom-sidebar-column {
    flex: 0 0 340px !important;
    width: 340px !important;
    max-width: 100% !important;
    min-width: 340px !important;     /* prevents shrinking */
    position: sticky !important;
    top: 20px !important;
    align-self: flex-start !important;
    box-sizing: border-box !important;
}

.tom-sidebar-column .card {
    margin-bottom: 1.5rem;
    background: #fff;
    padding: 1.5rem;
    border-radius: 20px;
    border: 1px solid #ebdccb;
    box-shadow: 0 10px 25px rgba(0,0,0,0.05);
    box-sizing: border-box;
    width: 100%;
}

/* --- Itinerary Accordion Sheets --- */
.itin-card-v2 {
    background: #ffffff;
    border: 1px solid #ebdccb;
    border-radius: 16px;
    margin-bottom: 1rem;
    overflow: hidden;
    transition: box-shadow 0.25s ease;
}

.itin-card-header-v2 {
    width: 100%;
    background: none;
    border: none;
    padding: 1.2rem 1.5rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    text-align: left;
    outline: none;
}

.itin-stop-v2 {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s cubic-bezier(0, 0, 0.2, 1);
    padding: 0 1.5rem;
}

.itin-stop-v2.is-open {
    max-height: 2000px;
    padding-bottom: 1.5rem;
}

.tom-timeline-track {
    position: relative;
    padding-left: 2rem;
    border-left: 2px solid #e2dcd5;
    margin-left: 1rem;
}

.itin-dot-v2 {
    position: absolute;
    left: -6px;
    top: 6px;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: #2c6e3c;
    border: 2px solid #ffffff;
}

/* --- Global Utilities, Notice, and FAB Overlays --- */
.tom-notice { padding: 1rem; border-radius: 8px; margin-bottom: 1rem; font-size: 0.9rem; font-weight: 500; }
.tom-notice-error { background: #fdf2f2; color: #9b1c1c; border: 1px solid #fbd5d5; }
.tom-notice-success { background: #f3faf7; color: #03543f; border: 1px solid #def7ec; }

#tom-fc-fab {
    position: fixed; bottom: 25px; right: 25px; background: #1e5631; color: #fff;
    border: none; width: 56px; height: 56px; border-radius: 50%;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3); cursor: pointer; z-index: 2000;
    display: flex; align-items: center; justify-content: center; font-size: 1.5rem;
}

#tom-fc-modal {
    position: fixed; top: 0; left: 0; width: 100%; height: 100%;
    background: rgba(0,0,0,0.5); display: none; align-items: center; justify-content: center; z-index: 2001;
}
#tom-fc-modal.open { display: flex; }
.tom-fc-modal-content { background: #fff; border-radius: 20px; padding: 2rem; width: 100%; max-width: 450px; position: relative; }

/* --- Responsive Media Viewport Breaks --- */
html { scroll-behavior: smooth; scroll-padding-top: 110px; }

@media (max-width: 1024px) {
    .tom-flex-layout {
        flex-wrap: wrap !important;   /* allow wrapping on mobile */
        flex-direction: column !important;
        gap: 2rem !important;
    }
    .tom-main-content {
        width: 100% !important;
        flex: 1 1 auto !important;
    }
    .tom-sidebar-column {
        flex: 1 1 100% !important;
        width: 100% !important;
        min-width: 0 !important;
        position: static !important;
        display: grid !important;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)) !important;
        gap: 1.2rem !important;
        align-self: stretch !important;
    }
    .tom-sidebar-column .card {
        margin: 0 !important;
    }
}
</style>

<div class="tom-flex-layout">
    <main class="tom-main-content">
        <h1><?php the_title(); ?></h1>
        
        <div id="tour-map" data-tom-tour-map="true"></div>
        
        <?php 
        $pins_data = get_post_meta(get_the_ID(), 'tom_map_pins', true); 
        $fallback_json = '[{"lat":-18.8792,"lng":47.5079,"day":1,"title":"Antananarivo Arrival"},{"lat":-20.2251,"lng":44.3124,"day":2,"title":"Morondava Baobabs"}]';
        ?>
        <script type="application/json" id="tom-tour-map-data">
        <?php echo !empty($pins_data) ? $pins_data : $fallback_json; ?>
        </script>

        <div class="tom-timeline-track" style="margin-top: 2rem;">
            <div class="itin-stop-v2">
                <button class="itin-card-header-v2" aria-expanded="false">
                    <h3>Day 1: Welcome to Madagascar Adventure</h3>
                    <span class="itin-dot-v2"></span>
                </button>
                <div class="itin-card-v2">
                    <p style="padding: 1rem 1.5rem;">Touch down on local soil. Meet your dedicated luxury handling representative, load equipment vehicles, and check smoothly into your private capital villa suite ecosystem.</p>
                </div>
            </div>
            <div class="itin-stop-v2">
                <button class="itin-card-header-v2" aria-expanded="false">
                    <h3>Day 2: Flight Path to West Coast Horizons</h3>
                    <span class="itin-dot-v2"></span>
                </button>
                <div class="itin-card-v2">
                    <p style="padding: 1rem 1.5rem;">Board your charter route heading west towards limestone reserves. Traverse standard avenues to trace dynamic visual frames surrounding century-old baobab paths during magic sunset hour peaks.</p>
                </div>
            </div>
        </div>
    </main>

    <aside class="tom-sidebar-column">
        <div class="card">
            <h4>Booking & Inquiries</h4>
            <p>Tailor your custom private charter path tracking rare wildlife ecosystems along custom Malagasy tracks.</p>
            <form id="tom-itin-form">
                <div id="tom-form-msg"></div>
                <button type="submit" class="tom-notice-success" style="width:100%; border:none; padding:10px; cursor:pointer; border-radius:8px;">Plan This Journey</button>
            </form>
        </div>
    </aside>
</div>

<button id="tom-fc-fab" aria-label="Contact Channel">✉</button>
<div id="tom-fc-modal" aria-hidden="true">
    <div class="tom-fc-modal-content">
        <button style="position:absolute; top:10px; right:15px; background:none; border:none; font-size:20px; cursor:pointer;" data-fc-close>&times;</button>
        <h3>Direct Assistance</h3>
        <form class="tom-quick-contact">
            <div class="tom-quick-contact-msg"></div>
            <input type="text" name="qc_name" placeholder="Your Name" required style="width:100%; margin-bottom:10px; padding:8px;"><br>
            <textarea name="qc_message" placeholder="Message details..." style="width:100%; height:8px; margin-bottom:10px; padding:8px; height:80px;"></textarea><br>
            <button type="submit" style="background:#1e5631; color:#fff; border:none; padding:10px 20px; border-radius:5px; cursor:pointer;">Transmit Request</button>
        </form>
    </div>
</div>

<script>
(function(){
  'use strict';
  const STORAGE = 'tom_itinerary_v2';

  function load() { try { return JSON.parse(localStorage.getItem(STORAGE) || '[]'); } catch(e){return [];} }
  function clear() { localStorage.setItem(STORAGE, '[]'); render(); }

  function render() {
    const arr = load();
    document.querySelectorAll('[data-tom-count]').forEach(el => el.textContent = arr.length);
  }

  /* --- Fixed Asynchronous Form Handler With Clean String Escape Actions --- */
  const form = document.getElementById('tom-itin-form');
  if (form) {
    form.addEventListener('submit', async function(e){
      e.preventDefault();
      const msg = document.getElementById('tom-form-msg');
      msg.innerHTML = '<div class="tom-notice">Sending...</div>';
      const fd = new FormData(form);
      fd.append('action', 'tom_itinerary');
      const ajax_url = (typeof TOM !== 'undefined' && TOM.ajax_url) || '/wp-admin/admin-ajax.php';
      try {
        const r = await fetch(ajax_url, { method: 'POST', body: fd });
        const j = await r.json();
        if (j.success) {
          msg.innerHTML = '<div class="tom-notice tom-notice-success">' + j.data.message + '</div>';
          form.reset(); clear();
        } else {
          msg.innerHTML = '<div class="tom-notice tom-notice-error">' + (j.data?.message || 'Submission failed.') + '</div>';
        }
      } catch (err) {
        msg.innerHTML = '<div class="tom-notice tom-notice-error">Network error. Please try again.</div>';
      }
    });
  }

  /* --- Accordion System Initialization Logic Hooks --- */
  function initItineraryAccordion() {
    const headers = document.querySelectorAll('.itin-card-header-v2');
    if (!headers.length) return;
    
    headers.forEach(header => {
      if (header._tomAccordionInit) return;
      header._tomAccordionInit = true;
      
      header.addEventListener('click', () => {
        const stop = header.closest('.itin-stop-v2');
        if (!stop) return;
        
        const isOpen = stop.classList.contains('is-open');
        
        document.querySelectorAll('.itin-stop-v2').forEach(s => {
          s.classList.remove('is-open');
          const h = s.querySelector('.itin-card-header-v2');
          if (h) h.setAttribute('aria-expanded', 'false');
        });
        
        if (!isOpen) {
          stop.classList.add('is-open');
          header.setAttribute('aria-expanded', 'true');
          
          setTimeout(() => {
            const rect = stop.getBoundingClientRect();
            const offset = 100;
            if (rect.top < offset || rect.bottom > window.innerHeight) {
              stop.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
          }, 100);
        }
      });
    });

    const firstStop = document.querySelector('.itin-stop-v2');
    if (firstStop && !firstStop.classList.contains('is-open')) {
      firstStop.classList.add('is-open');
      const firstHeader = firstStop.querySelector('.itin-card-header-v2');
      if (firstHeader) firstHeader.setAttribute('aria-expanded', 'true');
    }
  }
  
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initItineraryAccordion);
  } else {
    initItineraryAccordion();
  }

  /* --- Fixed Leaflet Mapping Engine Injection System --- */
  function initTourMap(el, points) {
    if (!window.L || !el || el._tomInit) return;
    el._tomInit = true;
    
    const valid = points
      .filter(p => p.lat != null && p.lng != null && !isNaN(parseFloat(p.lat)) && !isNaN(parseFloat(p.lng)))
      .map((p, i) => {
        const parsedDay = parseInt(p.day, 10);
        return {
          ...p,
          _seq: i,
          dayNum: Number.isFinite(parsedDay) ? parsedDay : (i + 1),
          lat: parseFloat(p.lat),
          lng: parseFloat(p.lng)
        };
      })
      .sort((a, b) => a.dayNum === b.dayNum ? a._seq - b._seq : a.dayNum - b.dayNum);

    if (!valid.length) return;

    const grouped = [];
    valid.forEach(p => {
      const last = grouped[grouped.length - 1];
      const samePlace = last && Math.abs(last.lat - p.lat) < 0.001 && Math.abs(last.lng - p.lng) < 0.001;
      if (samePlace) { last.days.push(p); } else { grouped.push({ lat: p.lat, lng: p.lng, days: [p] }); }
    });

    const lats = grouped.map(g => g.lat);
    const lngs = grouped.map(g => g.lng);
    const bounds = L.latLngBounds([[Math.min(...lats), Math.min(...lngs)], [Math.max(...lats), Math.max(...lngs)]]);
    
    const map = L.map(el, { scrollWheelZoom: false });
    el._tomLeaflet = map;
    
    L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', {
      attribution: '© OpenStreetMap © CARTO', subdomains: 'abcd', maxZoom: 19
    }).addTo(map);
    
    map.fitBounds(bounds, { padding: [50, 50] });

    const markers = [];
    const allLatLngs = [];
    
    grouped.forEach((g, idx) => {
      const dayNum = g.days[0].dayNum || idx + 1;
      
      const customIcon = L.divIcon({
        html: `<div class="tom-map-marker-luxury"><span>${dayNum}</span></div>`,
        iconSize: [32, 32], iconAnchor: [16, 32], popupAnchor: [0, -32]
      });
      
      const m = L.marker([g.lat, g.lng], { icon: customIcon }).addTo(map);
      const popupHtml = g.days.map(p => `<div><strong>${p.title || 'Stop ' + (p.dayNum || '')}</strong></div>`).join('<hr>');
      
      m.bindPopup(popupHtml, { maxWidth: 250 });
      markers.push(m);
      allLatLngs.push([g.lat, g.lng]);
    });

    if (allLatLngs.length > 1) {
      L.polyline(allLatLngs, { color: '#b8860b', weight: 3, opacity: 0.8, dashArray: '8, 6' }).addTo(map);
    }
    
    const fitRoute = () => {
      if (!el.isConnected || el.clientWidth === 0 || el.clientHeight === 0) return;
      map.invalidateSize({ pan: false, animate: false });
      if (allLatLngs.length > 1) { map.fitBounds(L.latLngBounds(allLatLngs), { padding: [50, 50], animate: false }); }
    };

    el._tomSync = fitRoute;
    map.whenReady(() => setTimeout(fitRoute, 100));

    if (window.ResizeObserver) {
      const ro = new ResizeObserver(() => fitRoute());
      ro.observe(el);
    }
  }

  // Auto Boot up sequences
  const tourMap = document.querySelector('[data-tom-tour-map]');
  const tourData = document.getElementById('tom-tour-map-data');
  
  function tryInitTourMap() {
    if (!tourMap || !tourData || tourMap.clientWidth === 0) return;
    if (tourMap._tomInit) { if (tourMap._tomSync) tourMap._tomSync(); return; }
    try { initTourMap(tourMap, JSON.parse(tourData.textContent || '[]')); } catch(e){}
  }

  if (tourMap && tourData) {
    tryInitTourMap();
    window.addEventListener('load', () => setTimeout(tryInitTourMap, 150));
  }

  render();
})();

/* --- Floating Modal Widget Interactions Block --- */
(function(){
  const fab = document.getElementById('tom-fc-fab');
  const modal = document.getElementById('tom-fc-modal');
  if (!fab || !modal) return;
  
  fab.addEventListener('click', () => { modal.classList.add('open'); modal.setAttribute('aria-hidden','false'); });
  modal.addEventListener('click', e => { if (e.target.closest('[data-fc-close]') || e.target === modal) { modal.classList.remove('open'); modal.setAttribute('aria-hidden','true'); } });
  
  document.addEventListener('submit', async function(e){
    const f = e.target.closest('.tom-quick-contact');
    if (!f) return;
    e.preventDefault();
    const msgEl = f.querySelector('.tom-quick-contact-msg');
    msgEl.textContent = 'Sending…';
    const fd = new FormData(f);
    fd.append('action', 'tom_quick_contact');
    try {
      const r = await fetch((window.TOM && TOM.ajax_url) || '/wp-admin/admin-ajax.php', { method:'POST', body: fd });
      const j = await r.json();
      if (j && j.success) {
        msgEl.className = 'tom-quick-contact-msg success';
        msgEl.textContent = j.data.message;
        f.reset();
        setTimeout(() => { modal.classList.remove('open'); }, 1500);
      } else {
        msgEl.textContent = 'Submission Failed.';
      }
    } catch(err) {
      msgEl.textContent = 'Network error experienced.';
    }
  });
})();
</script>

<?php 
// FIXED: Removed trailing standalone bracket structural syntax bug completely
// Dans footer.php, juste avant les liens
global $tom_current_lang;

// Si la langue est définie, on la force
if (isset($tom_current_lang) && $tom_current_lang !== 'en') {
    // Forcer la langue Polylang
    if (function_exists('pll_current_language')) {
        pll_current_language($tom_current_lang);
    }
}
/* ==========================================================================
   PREMIUM 4-COLUMN FOOTER SYSTEM
   ========================================================================== */
.site-footer {
    background-color: #111111;
    color: #e5e5e5;
    padding: 80px 0 0 0;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    font-size: 14px;
    letter-spacing: 0.2px;
}

/* Master Grid Layout */
.footer-top-grid {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 25px 50px 25px;
    display: grid;
    grid-template-columns: 1.2fr 1fr 1fr 1fr;
    gap: 50px;
}

@media (max-width: 991px) {
    .footer-top-grid {
        grid-template-columns: 1fr 1fr;
        gap: 40px;
    }
}

@media (max-width: 576px) {
    .footer-top-grid {
        grid-template-columns: 1fr;
        gap: 35px;
    }
}

/* Column Titles & Typography */
.footer-widget-title {
    color: #ffffff;
    font-size: 15px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 1px;
    margin: 0 0 25px 0;
    position: relative;
}

.footer-widget-title::after {
    content: '';
    display: block;
    width: 30px;
    height: 2px;
    background: #ff6b00; /* Theme brand accent color */
    margin-top: 8px;
}

.brand-identity .footer-brand-title {
    font-size: 20px;
    font-weight: 800;
    color: #ffffff;
    margin: 0 0 15px 0;
}

.brand-identity .footer-bio {
    color: #a3a3a3;
    font-size: 13px;
    line-height: 1.6;
    margin-bottom: 25px;
}

/* Footer Navigation Menus */
.footer-menu-links {
    list-style: none;
    padding: 0;
    margin: 0;
}

.footer-menu-links li {
    margin-bottom: 12px;
}

.footer-menu-links a {
    color: #a3a3a3;
    text-decoration: none;
    transition: all 0.2s ease;
    display: inline-block;
}

.footer-menu-links a:hover {
    color: #ffffff;
    transform: translateX(4px);
}

/* TripAdvisor Badge Branding */
.tripadvisor-badge-wrap {
    margin-top: 15px;
}

.ta-badge-link {
    display: inline-flex;
    align-items: center;
    background: #1a1a1a;
    border: 1px solid #2a2a2a;
    padding: 10px 14px;
    border-radius: 6px;
    text-decoration: none;
    color: #ffffff;
    transition: border-color 0.2s ease;
}

.ta-badge-link:hover {
    border-color: #34e0a1; /* TripAdvisor signature green */
}

.ta-icon-box {
    font-size: 24px;
    color: #34e0a1;
    margin-right: 12px;
}

.ta-meta {
    display: flex;
    flex-direction: column;
}

.ta-label {
    font-size: 10px;
    color: #a3a3a3;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    line-height: 1;
}

.ta-brand {
    font-size: 13px;
    font-weight: 700;
    line-height: 1.3;
}

.ta-stars {
    color: #34e0a1;
    font-size: 8px;
    display: flex;
    gap: 2px;
    margin-top: 2px;
}

/* Contact Coordinates Bar */
.footer-utility-bar {
    border-top: 1px solid #222222;
    border-bottom: 1px solid #222222;
    background-color: #161616;
    padding: 20px 0;
}

.utility-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 25px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;
}

.utility-item {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 13px;
    color: #cccccc;
}

.utility-item a {
    color: inherit;
    text-decoration: none;
    transition: color 0.2s ease;
}

.utility-item a:hover {
    color: #ffffff;
}

.utility-item i {
    color: #ff6b00;
}

.utility-item i.whatsapp-color {
    color: #25d366;
}

@media (max-width: 768px) {
    .utility-container {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }
}

/* Bottom Fine Print Footer Base */
.footer-bottom-base {
    padding: 30px 0;
    background-color: #111111;
    font-size: 12px;
    color: #737373;
}

.bottom-base-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 25px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.footer-social-row {
    display: flex;
    gap: 16px;
}

.footer-social-row a {
    color: #737373;
    font-size: 15px;
    transition: color 0.2s ease;
}

.footer-social-row a:hover {
    color: #ffffff;
}

@media (max-width: 576px) {
    .bottom-base-container {
        flex-direction: column-reverse;
        gap: 15px;
        text-align: center;
    }
}
get_footer(); 
?>