<?php
/**
 * SoberList.org - Directory Page View
 * 
 * This file contains only the content for the directory page.
 * It will be inserted into the layout template by the BaseController.
 */

// Debug information display (if available)
if (isset($debug_info)): ?>
<div style="background: #f8f9fa; padding: 20px; margin: 20px 0; border-radius: 5px; font-family: monospace; font-size: 14px;">
    <h2 style="margin-top: 0;">SoberList Diagnostics</h2>
    <ul style="padding-left: 20px; line-height: 1.6;">
        <?php foreach($debug_info as $info): ?>
            <li><?php echo htmlspecialchars($info); ?></li>
        <?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>

<!-- Hero Section with Search 

<section class="directory-hero" aria-labelledby="directoryTitle">
    <div class="hero-bg">
        <div class="container">
            <div class="hero-content">
                <h1 id="directoryTitle" class="text-center mb-2">Find Your Path to Recovery</h1>
                <p class="lead text-center mb-5" id="lcp-element">Connect with compassionate care tailored to your journey</p>
                
                <!-- Search Form Card -->
				<h1>This is a test</h1>
                <div class="search-card">
                    <form action="/directory" method="get" id="directorySearchForm">
                        <input type="hidden" name="view" value="<?php echo htmlspecialchars($view); ?>">
                        
                        <div class="search-form-main">
                            <div class="search-row">
                                <div class="search-location">
                                    <div class="search-input-wrapper">
                                        <i class="bi bi-geo-alt search-icon"></i>
                                        <input type="text" name="location" placeholder="Enter city, state or zip" 
                                               value="<?php echo htmlspecialchars($location); ?>" 
                                               class="form-control" aria-label="Location">
                                    </div>
                                </div>
                                
                                <div class="search-type">
                                    <select name="type" class="form-select" aria-label="Resource type">
                                        <option value="">All Resource Types</option>
                                        <option value="HH" <?php echo $facility_type === 'HH' ? 'selected' : ''; ?>>Sober Living Homes</option>
                                        <option value="SA" <?php echo $facility_type === 'SA' ? 'selected' : ''; ?>>Treatment Centers</option>
                                        <option value="DT" <?php echo $facility_type === 'DT' ? 'selected' : ''; ?>>Detox Facilities</option>
                                        <option value="MH" <?php echo $facility_type === 'MH' ? 'selected' : ''; ?>>Mental Health</option>
                                        <option value="SUMH" <?php echo $facility_type === 'SUMH' ? 'selected' : ''; ?>>Co-occurring Disorders</option>
                                    </select>
                                </div>
                                
                                <button type="submit" class="btn btn-primary search-btn">
                                    <i class="bi bi-search me-2"></i>Find Resources
                                </button>
                            </div>
                        </div>
                        
                        <div class="advanced-filters-toggle">
                            <button type="button" class="btn btn-text" data-bs-toggle="collapse" data-bs-target="#advancedFilters">
                                <i class="bi bi-sliders me-1"></i>Advanced Filters
                            </button>
                        </div>
                        
                        <div class="collapse" id="advancedFilters">
                            <div class="advanced-filters-content">
                                <div class="filters-grid">
                                    <div class="filter-group">
                                        <label for="radius-filter">Within Distance</label>
                                        <select id="radius-filter" name="radius" class="form-select">
                                            <option value="5" <?php echo $radius === 5 ? 'selected' : ''; ?>>5 miles</option>
                                            <option value="10" <?php echo $radius === 10 ? 'selected' : ''; ?>>10 miles</option>
                                            <option value="25" <?php echo $radius === 25 ? 'selected' : ''; ?>>25 miles</option>
                                            <option value="50" <?php echo $radius === 50 ? 'selected' : ''; ?>>50 miles</option>
                                            <option value="100" <?php echo $radius === 100 ? 'selected' : ''; ?>>100 miles</option>
                                        </select>
                                    </div>
                                    
                                    <div class="filter-group">
                                        <label for="state-filter">State</label>
                                        <select id="state-filter" name="state" class="form-select">
                                            <option value="">All States</option>
                                            <?php foreach ($states as $state): ?>
                                                <option value="<?php echo htmlspecialchars($state['state_code']); ?>" 
                                                        <?php echo $state_code === $state['state_code'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($state['state_name']); ?> 
                                                    (<?php echo number_format($state['facility_count']); ?>)
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="filter-group">
                                        <label for="gender-filter">Gender Specific</label>
                                        <select id="gender-filter" name="gender" class="form-select">
                                            <option value="">All Genders</option>
                                            <option value="Men Only" <?php echo $gender === 'Men Only' ? 'selected' : ''; ?>>Men Only</option>
                                            <option value="Women Only" <?php echo $gender === 'Women Only' ? 'selected' : ''; ?>>Women Only</option>
                                            <option value="Co-Ed" <?php echo $gender === 'Co-Ed' ? 'selected' : ''; ?>>Co-Ed</option>
                                        </select>
                                    </div>
                                    
                                    <div class="filter-group">
                                        <label for="payment-filter">Payment Options</label>
                                        <select id="payment-filter" name="payment" class="form-select">
                                            <option value="">All Payment Types</option>
                                            <?php foreach ($payment_options as $option): ?>
                                                <option value="<?php echo htmlspecialchars($option['code']); ?>" 
                                                        <?php echo $payment_option === $option['code'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($option['name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="filter-group">
                                        <label for="sort-filter">Sort By</label>
                                        <select id="sort-filter" name="sort" class="form-select">
                                            <option value="rating" <?php echo $sort === 'rating' ? 'selected' : ''; ?>>Highest Rated</option>
                                            <option value="reviews" <?php echo $sort === 'reviews' ? 'selected' : ''; ?>>Most Reviewed</option>
                                            <option value="name_asc" <?php echo $sort === 'name_asc' ? 'selected' : ''; ?>>Name (A-Z)</option>
                                            <option value="name_desc" <?php echo $sort === 'name_desc' ? 'selected' : ''; ?>>Name (Z-A)</option>
                                            <?php if (!empty($location)): ?>
                                            <option value="distance" <?php echo $sort === 'distance' ? 'selected' : ''; ?>>Distance</option>
                                            <?php endif; ?>
                                            <?php if (!empty($query)): ?>
                                            <option value="relevance" <?php echo $sort === 'relevance' ? 'selected' : ''; ?>>Relevance</option>
                                            <?php endif; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="filter-group filter-actions">
                                        <button type="submit" class="btn btn-primary apply-filters-btn">
                                            <i class="bi bi-funnel me-2"></i>Apply Filters
                                        </button>
                                        <a href="/directory" class="btn btn-outline-secondary clear-filters-btn">
                                            <i class="bi bi-x-circle me-2"></i>Clear All
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Results Section -->
<section class="directory-results">
    <div class="container">
        <div class="results-header">
            <div class="results-info">
                <h2><?php echo htmlspecialchars($dynamic_title); ?></h2>
                <p class="results-count"><?php echo number_format($total_count); ?> resources found</p>
            </div>
            
            <div class="view-toggle">
                <div class="btn-group" role="group" aria-label="View toggle">
                    <button type="button" class="btn <?php echo $view !== 'map' ? 'btn-primary' : 'btn-outline-primary'; ?>" id="listViewBtn">
                        <i class="bi bi-list-ul me-1"></i>List
                    </button>
                    <button type="button" class="btn <?php echo $view === 'map' ? 'btn-primary' : 'btn-outline-primary'; ?>" id="mapViewBtn">
                        <i class="bi bi-geo-alt me-1"></i>Map
                    </button>
                </div>
            </div>
        </div>
        
        <!-- List View -->
        <div id="listView" class="<?php echo $view === 'map' ? 'd-none' : ''; ?>">
            <?php if (count($facilities) > 0): ?>
                <div class="facilities-grid">
                    <?php foreach ($facilities as $facility): ?>
                        <div class="facility-card">
                            <div class="facility-image">
                                <img src="<?php echo $getFacilityTypeImage($facility); ?>" 
                                     alt="<?php echo htmlspecialchars($facility['name']); ?>" loading="lazy">
                                
                                <?php if (!empty($facility['is_verified'])): ?>
                                    <div class="facility-verified" title="Verified Facility">
                                        <i class="bi bi-patch-check-fill"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="facility-content">
                                <h3 class="facility-name">
                                    <a href="/facility/<?php echo $getFacilitySlug($facility); ?>">
                                        <?php echo htmlspecialchars($facility['name']); ?>
                                    </a>
                                </h3>
                                
                                <p class="facility-location">
                                    <i class="bi bi-geo-alt"></i>
                                    <?php echo htmlspecialchars($facility['city'] . ', ' . $facility['state_code']); ?>
                                    
                                    <?php if (!empty($facility['distance'])): ?>
                                        <span class="facility-distance"><?php echo number_format($facility['distance'], 1); ?> miles</span>
                                    <?php endif; ?>
                                </p>
                                
                                <?php if (!empty($facility['avg_rating'])): ?>
                                    <div class="facility-rating">
                                        <div class="stars">
                                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                                <?php if ($i <= floor($facility['avg_rating'])): ?>
                                                    <i class="bi bi-star-fill"></i>
                                                <?php elseif ($i - 0.5 <= $facility['avg_rating']): ?>
                                                    <i class="bi bi-star-half"></i>
                                                <?php else: ?>
                                                    <i class="bi bi-star"></i>
                                                <?php endif; ?>
                                            <?php endfor; ?>
                                        </div>
                                        <span class="rating-count">
                                            <?php echo number_format($facility['avg_rating'], 1); ?> 
                                            (<?php echo number_format($facility['total_reviews'] ?? 0); ?>)
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if (!empty($facility['facility_types'])): ?>
                                    <div class="facility-tags">
                                        <?php $types = explode(',', $facility['facility_types']); ?>
                                        <?php foreach (array_slice($types, 0, 3) as $type): ?>
                                            <span class="badge <?php echo $getBadgeClass($type); ?>">
                                                <?php echo htmlspecialchars(trim($type)); ?>
                                            </span>
                                        <?php endforeach; ?>
                                        
                                        <?php if (count($types) > 3): ?>
                                            <span class="badge bg-secondary">+<?php echo count($types) - 3; ?> more</span>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if (!empty($facility['description'])): ?>
                                    <p class="facility-description">
                                        <?php echo htmlspecialchars(substr(strip_tags($facility['description']), 0, 120)) . '...'; ?>
                                    </p>
                                <?php endif; ?>
                                
                                <div class="facility-actions">
                                    <a href="/facility/<?php echo $getFacilitySlug($facility); ?>" class="btn btn-primary btn-details">
                                        View Details
                                    </a>
                                    
                                    <?php if (!empty($facility['phone'])): ?>
                                        <a href="tel:<?php echo preg_replace('/[^0-9]/', '', $facility['phone']); ?>" class="btn btn-success btn-call">
                                            <i class="bi bi-telephone-fill"></i> Call Now
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <div class="pagination-container">
                        <nav aria-label="Directory pagination">
                            <ul class="pagination">
                                <?php if ($page > 1): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="/directory?<?php echo http_build_query(array_merge($search_params, ['page' => $page - 1])); ?>" aria-label="Previous">
                                            <i class="bi bi-chevron-left"></i>
                                        </a>
                                    </li>
                                <?php else: ?>
                                    <li class="page-item disabled">
                                        <span class="page-link"><i class="bi bi-chevron-left"></i></span>
                                    </li>
                                <?php endif; ?>
                                
                                <?php
                                $start_page = max(1, $page - 2);
                                $end_page = min($total_pages, $page + 2);
                                
                                if ($start_page > 1) {
                                    echo '<li class="page-item"><a class="page-link" href="/directory?' . 
                                         http_build_query(array_merge($search_params, ['page' => 1])) . 
                                         '">1</a></li>';
                                    
                                    if ($start_page > 2) {
                                        echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                                    }
                                }
                                
                                for ($i = $start_page; $i <= $end_page; $i++) {
                                    if ($i == $page) {
                                        echo '<li class="page-item active"><span class="page-link">' . $i . '</span></li>';
                                    } else {
                                        echo '<li class="page-item"><a class="page-link" href="/directory?' . 
                                             http_build_query(array_merge($search_params, ['page' => $i])) . 
                                             '">' . $i . '</a></li>';
                                    }
                                }
                                
                                if ($end_page < $total_pages) {
                                    if ($end_page < $total_pages - 1) {
                                        echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                                    }
                                    
                                    echo '<li class="page-item"><a class="page-link" href="/directory?' . 
                                         http_build_query(array_merge($search_params, ['page' => $total_pages])) . 
                                         '">' . $total_pages . '</a></li>';
                                }
                                ?>
                                
                                <?php if ($page < $total_pages): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="/directory?<?php echo http_build_query(array_merge($search_params, ['page' => $page + 1])); ?>" aria-label="Next">
                                            <i class="bi bi-chevron-right"></i>
                                        </a>
                                    </li>
                                <?php else: ?>
                                    <li class="page-item disabled">
                                        <span class="page-link"><i class="bi bi-chevron-right"></i></span>
                                    </li>
                                <?php endif; ?>
                            </ul>
                        </nav>
                    </div>
                <?php endif; ?>
                
            <?php else: ?>
                <!-- No Results Found -->
                <div class="no-results">
                    <div class="no-results-icon">
                        <i class="bi bi-search"></i>
                    </div>
                    <h3>No Results Found</h3>
                    <p>We couldn't find any facilities matching your search criteria.</p>
                    <div class="no-results-actions">
                        <a href="/directory" class="btn btn-primary">Reset Filters</a>
                        <a href="/contact" class="btn btn-outline-primary">Contact Us for Help</a>
                    </div>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Map View -->
        <div id="mapView" class="<?php echo $view !== 'map' ? 'd-none' : ''; ?>">
            <div class="map-container">
                <div id="facilitiesMap"></div>
            </div>
            
            <div class="map-list">
                <h3>Resources on Map</h3>
                <div class="map-facilities-list">
                    <?php if (count($map_facilities) > 0): ?>
                        <?php foreach ($map_facilities as $facility): ?>
                            <?php if (!empty($facility['latitude']) && !empty($facility['longitude'])): ?>
                                <div class="map-facility-item" data-lat="<?php echo htmlspecialchars($facility['latitude']); ?>" data-lng="<?php echo htmlspecialchars($facility['longitude']); ?>">
                                    <h4><?php echo htmlspecialchars($facility['name']); ?></h4>
                                    <p>
                                        <i class="bi bi-geo-alt"></i>
                                        <?php echo htmlspecialchars($facility['city'] . ', ' . $facility['state_code']); ?>
                                    </p>
                                    <?php if (!empty($facility['facility_types'])): ?>
                                        <div class="map-facility-tags">
                                            <?php $types = explode(',', $facility['facility_types']); ?>
                                            <?php foreach (array_slice($types, 0, 2) as $type): ?>
                                                <span class="badge <?php echo $getBadgeClass($type); ?>">
                                                    <?php echo htmlspecialchars(trim($type)); ?>
                                                </span>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>
                                    <a href="/facility/<?php echo $getFacilitySlug($facility); ?>" class="btn btn-sm btn-primary">View Details</a>
                                </div>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="map-no-results">No facilities found with location data.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Resource Guide Section -->
<section class="resource-guide">
    <div class="container">
        <h2>Finding the Right Recovery Support</h2>
        <p class="guide-intro">Recovery is a personal journey with many paths. Here's how to find the best fit for your needs:</p>
        
        <div class="guide-grid">
            <div class="guide-card">
                <div class="guide-icon">
                    <i class="bi bi-building"></i>
                </div>
                <h3>Treatment Settings</h3>
                <p>From residential programs to outpatient care, different settings offer varying levels of structure and support.</p>
                <ul>
                    <li>Residential: 24/7 structured environment</li>
                    <li>Outpatient: Flexible programs while living at home</li>
                    <li>Sober Living: Supportive housing during transition</li>
                </ul>
            </div>
            
            <div class="guide-card">
                <div class="guide-icon">
                    <i class="bi bi-stars"></i>
                </div>
                <h3>Effective Approaches</h3>
                <p>Evidence-based therapy approaches have been proven effective for lasting recovery:</p>
                <ul>
                    <li>Cognitive Behavioral Therapy (CBT)</li>
                    <li>Motivational Enhancement</li>
                    <li>Family Systems Therapy</li>
                    <li>12-Step Facilitation</li>
                </ul>
            </div>
            
            <div class="guide-card">
                <div class="guide-icon">
                    <i class="bi bi-shield-check"></i>
                </div>
                <h3>Quality Indicators</h3>
                <p>Look for these signs of quality care when evaluating options:</p>
                <ul>
                    <li>Licensed, credentialed staff</li>
                    <li>Accreditation by recognized organizations</li>
                    <li>Personalized treatment planning</li>
                    <li>Aftercare support and relapse prevention</li>
                </ul>
            </div>
            
            <div class="guide-card">
                <div class="guide-icon">
                    <i class="bi bi-credit-card"></i>
                </div>
                <h3>Payment Options</h3>
                <p>Understanding financial options helps remove barriers to care:</p>
                <ul>
                    <li>Insurance coverage verification</li>
                    <li>Sliding scale fee structures</li>
                    <li>Payment plans and financing</li>
                    <li>Scholarship programs</li>
                </ul>
            </div>
        </div>
    </div>
</section>

<!-- Contact CTA Section -->
<section class="contact-cta">
    <div class="container">
        <div class="cta-content">
            <h2>Need Help Finding the Right Resource?</h2>
            <p>Our treatment specialists can guide you through your options and help match you with the best care for your needs.</p>
            <div class="cta-buttons">
                <a href="tel:8885017071" class="btn btn-light">
                    <i class="bi bi-telephone-fill me-2"></i>Call (888) 501-7071
                </a>
                <a href="/contact" class="btn btn-outline-light">
                    <i class="bi bi-chat-text-fill me-2"></i>Contact Us
                </a>
            </div>
        </div>
    </div>
</section>

<!-- Map Initialization Script for Map View -->
<?php if ($view === 'map'): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // View toggle functionality
    const listViewBtn = document.getElementById('listViewBtn');
    const mapViewBtn = document.getElementById('mapViewBtn');
    const listView = document.getElementById('listView');
    const mapView = document.getElementById('mapView');
    
    if (listViewBtn && mapViewBtn) {
        listViewBtn.addEventListener('click', function() {
            listView.classList.remove('d-none');
            mapView.classList.add('d-none');
            listViewBtn.classList.add('btn-primary');
            listViewBtn.classList.remove('btn-outline-primary');
            mapViewBtn.classList.remove('btn-primary');
            mapViewBtn.classList.add('btn-outline-primary');
            
            // Update form to maintain view state
            const viewInput = document.querySelector('input[name="view"]');
            if (viewInput) viewInput.value = 'list';
            
            // Update URL without reloading
            updateUrlParam('view', 'list');
        });
        
        mapViewBtn.addEventListener('click', function() {
            listView.classList.add('d-none');
            mapView.classList.remove('d-none');
            mapViewBtn.classList.add('btn-primary');
            mapViewBtn.classList.remove('btn-outline-primary');
            listViewBtn.classList.remove('btn-primary');
            listViewBtn.classList.add('btn-outline-primary');
            
            // Update form to maintain view state
            const viewInput = document.querySelector('input[name="view"]');
            if (viewInput) viewInput.value = 'map';
            
            // Update URL without reloading
            updateUrlParam('view', 'map');
            
            // Initialize map if needed
            initMap();
        });
    }
    
    // Helper function to update URL parameters
    function updateUrlParam(key, value) {
        const url = new URL(window.location.href);
        url.searchParams.set(key, value);
        window.history.replaceState({}, '', url);
    }
    
    // Map initialization
    function initMap() {
        const mapContainer = document.getElementById('facilitiesMap');
        if (!mapContainer) return;
        
        // Check if map is already initialized
        if (window.facilitiesMap) return;
        
        // Create map with default center (US)
        const map = new google.maps.Map(mapContainer, {
            center: { lat: 39.8283, lng: -98.5795 },
            zoom: 4,
            mapTypeControl: true,
            fullscreenControl: true,
            streetViewControl: false,
            zoomControl: true,
            styles: [
                {
                    "featureType": "administrative",
                    "elementType": "geometry",
                    "stylers": [{"visibility": "simplified"}]
                },
                {
                    "featureType": "landscape",
                    "stylers": [{"color": "#f8f9fa"}]
                },
                {
                    "featureType": "poi",
                    "stylers": [{"visibility": "simplified"}]
                },
                {
                    "featureType": "road",
                    "stylers": [{"visibility": "simplified"}]
                },
                {
                    "featureType": "water",
                    "stylers": [{"color": "#d1e5f9"}]
                }
            ]
        });
        
        // Store map reference
        window.facilitiesMap = map;
        
        // Setup for markers
        const markers = [];
        const bounds = new google.maps.LatLngBounds();
        const infoWindow = new google.maps.InfoWindow();
        let hasMarkers = false;
        
        // Process facility items for map
        const facilityItems = document.querySelectorAll('.map-facility-item');
        facilityItems.forEach(item => {
            const lat = parseFloat(item.dataset.lat);
            const lng = parseFloat(item.dataset.lng);
            
            if (!isNaN(lat) && !isNaN(lng)) {
                hasMarkers = true;
                const position = { lat, lng };
                
                // Create marker with animation
                const marker = new google.maps.Marker({
                    position: position,
                    map: map,
                    title: item.querySelector('h4')?.textContent || 'Facility',
                    animation: google.maps.Animation.DROP
                });
                
                // Create info window content from facility item
                marker.addListener('click', () => {
                    const name = item.querySelector('h4')?.textContent;
                    const address = item.querySelector('p')?.textContent;
                    const link = item.querySelector('a')?.href;
                    
                    const content = `
                        <div class="map-info-window">
                            <h4>${name || 'Facility'}</h4>
                            <p>${address || ''}</p>
                            ${link ? `<a href="${link}" class="btn btn-sm btn-primary">View Details</a>` : ''}
                        </div>
                    `;
                    
                    infoWindow.setContent(content);
                    infoWindow.open(map, marker);
                    
                    // Highlight corresponding item in list
                    document.querySelectorAll('.map-facility-item.active').forEach(el => el.classList.remove('active'));
                    item.classList.add('active');
                    item.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                });
                
                markers.push(marker);