"""
Main Routes Blueprint
Contains basic page routes like index, grids, and detail pages
"""
from flask import Blueprint, render_template, session
import os

# Create Blueprint
main_bp = Blueprint('main', __name__)

@main_bp.route('/')
def index():
    """Main landing page for users"""
    # Check if user is logged in
    user_id = session.get('user_id')
    user_name = session.get('user_name', '')
    is_admin = session.get('is_admin', False)
    user_photo = session.get('user_photo', '')
    
    # Debug session variables
    print(f"Session variables in index route:")
    print(f"  user_id: {user_id}")
    print(f"  user_name: {user_name}")
    print(f"  is_admin: {is_admin}")
    print(f"  user_photo: {user_photo}")
    
    # Additional debug: Check if session has the key
    print(f"Session keys: {list(session.keys())}")
    print(f"'is_admin' in session: {'is_admin' in session}")
    
    return render_template('index.html', 
                         user_id=user_id,
                         user_name=user_name,
                         is_admin=is_admin,
                         user_photo=user_photo)

@main_bp.route('/restaurants')
def restaurants_grid():
    """All restaurants grid page for users"""
    return render_template('restaurants-grid.html')

@main_bp.route('/restaurant/<restaurant_id>')
def restaurant_detail(restaurant_id):
    """Individual restaurant detail page for users"""
    return render_template('restaurant-detail.html', 
                         restaurant_id=restaurant_id,
                         google_maps_key=os.getenv('GOOGLE_MAPS_API_KEY', 'your-google-maps-api-key'))

@main_bp.route('/restaurant/<restaurant_id>/menu')
def restaurant_menu(restaurant_id):
    """Restaurant menu page with categories and items"""
    return render_template('restaurant-menu.html', 
                         restaurant_id=restaurant_id)

@main_bp.route('/beaches-grid')
def beaches_grid():
    """All beaches grid page for users"""
    return render_template('beaches-grid.html')

@main_bp.route('/beach/<beach_id>')
def beach_detail(beach_id):
    """Individual beach detail page for users"""
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        from config import ADMIN_CONFIG
        import os
        
        # Database connection
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Get beach details with company, country information
        beach_result = db.execute(text("""
            SELECT bp.*, c.company_name, co.country_name, bt.terrain_name
            FROM beach_places bp
            LEFT JOIN companies c ON bp.company_id = c.company_id
            LEFT JOIN countries co ON bp.country_id = co.country_id
            LEFT JOIN beach_terrain_types bt ON bp.terrain_type_id = bt.terrain_type_id
            WHERE bp.beach_place_id = :beach_id AND bp.enable_beach = true
        """), {"beach_id": beach_id}).fetchone()
        
        if not beach_result:
            from flask import flash, redirect, url_for
            flash('Beach not found or not available', 'error')
            return redirect(url_for('main.beaches_grid'))
        
        # Get beach photos
        photos_result = db.execute(text("""
            SELECT photo_path, photo_primary as is_primary
            FROM beach_places_photos 
            WHERE beach_place_id = :beach_id
            ORDER BY photo_primary DESC, sort_order ASC
        """), {"beach_id": beach_id}).fetchall()
        
        # Convert beach result to dict for template
        beach = {
            'beach_place_id': beach_result.beach_place_id,
            'name': beach_result.beach_name,
            'beach_information': getattr(beach_result, 'beach_information', ''),
            'city': beach_result.city,
            'address': beach_result.address,
            'latitude': beach_result.latitude or 37.975334,
            'longitude': beach_result.longitude or 23.734151,
            'max_seats': getattr(beach_result, 'max_seats', 0),
            'company_name': beach_result.company_name,
            'country_name': beach_result.country_name,
            'terrain_name': beach_result.terrain_name,
            'contact_phone': getattr(beach_result, 'contact_phone', None),
            'starttime': getattr(beach_result, 'starttime', None),
            'endtime': getattr(beach_result, 'endtime', None),
            'opendays': getattr(beach_result, 'opendays', '1234567'),
            # Service/amenity fields with safe defaults
            'has_sea': getattr(beach_result, 'has_sea', False),
            'has_umbrella': getattr(beach_result, 'has_umbrella', False),
            'has_showers': getattr(beach_result, 'has_showers', False),
            'has_lockers': getattr(beach_result, 'has_lockers', False),
            'has_market': getattr(beach_result, 'has_market', False),
            'has_restaurant': getattr(beach_result, 'has_restaurant', False),
            'has_swimming_pool': getattr(beach_result, 'has_swimming_pool', False),
            'has_parking': getattr(beach_result, 'has_parking', False),
            'has_toilets': getattr(beach_result, 'has_toilets', False),
            'has_free_wifi': getattr(beach_result, 'has_free_wifi', False),
            'has_music': getattr(beach_result, 'has_music', False),
            'has_safety_box': getattr(beach_result, 'has_safety_box', False),
            'has_access_wheelchair': getattr(beach_result, 'has_access_wheelchair', False),
            'has_lockers_for_baby': getattr(beach_result, 'has_lockers_for_baby', False),
            'has_beach_volley': getattr(beach_result, 'has_beach_volley', False),
            'has_tennis': getattr(beach_result, 'has_tennis', False),
            'has_spa': getattr(beach_result, 'has_spa', False),
            'has_medical': getattr(beach_result, 'has_medical', False),
            'has_lifeguard': getattr(beach_result, 'has_lifeguard', False),
            'pet_allow': getattr(beach_result, 'pet_allow', False),
            'sea_location': getattr(beach_result, 'sea_location', ''),
            'background_photo': getattr(beach_result, 'background_photo', ''),
            'photos': [{'path': photo.photo_path, 'is_primary': photo.is_primary} for photo in photos_result],
            'reviews': [],  # Empty for now
            'average_rating': 0
        }
        
        db.close()
        
        return render_template('beach-detail.html',
                             beach=beach,
                             google_maps_key=os.getenv('GOOGLE_MAPS_API_KEY', 'your-google-maps-api-key'))
        
    except Exception as e:
        from flask import flash, redirect, url_for
        print(f'Error loading beach details for ID {beach_id}: {str(e)}')
        flash(f'Error loading beach details: {str(e)}', 'error')
        return redirect(url_for('main.beaches_grid'))

@main_bp.route('/adventures-grid')
def adventures_grid():
    """All adventures grid page for users"""
    return render_template('adventures-grid.html')

@main_bp.route('/adventure/<adventure_id>')
def adventure_detail(adventure_id):
    """Individual adventure detail page for users"""
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        from config import ADMIN_CONFIG
        import os
        
        # Database connection
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Get adventure details
        adventure_result = db.execute(text("""
            SELECT a.*, c.company_name, co.country_name
            FROM adventures a
            LEFT JOIN companies c ON a.company_id = c.company_id
            LEFT JOIN countries co ON a.country_id = co.country_id
            WHERE a.adventure_id = :adventure_id
        """), {"adventure_id": adventure_id}).fetchone()
        
        if not adventure_result:
            from flask import flash, redirect, url_for
            flash('Adventure not found', 'error')
            return redirect(url_for('main.adventures_grid'))
        
        # Get adventure photos
        photos_result = db.execute(text("""
            SELECT photo_path
            FROM adventure_photos 
            WHERE adventure_id = :adventure_id
            ORDER BY created_at ASC
        """), {"adventure_id": adventure_id}).fetchall()
        
        # Convert to dict for template
        adventure = {
            'adventure_id': adventure_result.adventure_id,
            'adventure_name': adventure_result.adventure_name,
            'name': adventure_result.adventure_name,
            'description': getattr(adventure_result, 'description', ''),
            'city': adventure_result.city,
            'address': adventure_result.address,
            'latitude': adventure_result.latitude or 37.975334,
            'longitude': adventure_result.longitude or 23.734151,
            'duration_minutes': getattr(adventure_result, 'duration_minutes', 0),
            'max_participants': getattr(adventure_result, 'max_participants', 0),
            'min_participants': getattr(adventure_result, 'min_participants', 1),
            'price': getattr(adventure_result, 'price', 0),
            'phone': getattr(adventure_result, 'phone', ''),
            'email': getattr(adventure_result, 'email', ''),
            'website': getattr(adventure_result, 'website', ''),
            'company_name': adventure_result.company_name,
            'country_name': adventure_result.country_name,
            'photos': [{'path': photo.photo_path} for photo in photos_result]
        }
        
        db.close()
        
        return render_template('adventure-detail.html',
                             adventure=adventure,
                             google_maps_key=os.getenv('GOOGLE_MAPS_API_KEY', 'your-google-maps-api-key'))
        
    except Exception as e:
        from flask import flash, redirect, url_for
        print(f'Error loading adventure details for ID {adventure_id}: {str(e)}')
        flash(f'Error loading adventure details: {str(e)}', 'error')
        return redirect(url_for('main.adventures_grid'))

@main_bp.route('/markets-grid')
def markets_grid():
    """All markets grid page for users"""
    return render_template('markets-grid.html')

@main_bp.route('/market/<market_id>')
def market_detail(market_id):
    """Individual market detail page for users"""
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        from config import ADMIN_CONFIG
        import os
        
        # Database connection
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Get market details
        market_result = db.execute(text("""
            SELECT m.*, c.company_name, co.country_name
            FROM markets m
            LEFT JOIN companies c ON m.company_id = c.company_id
            LEFT JOIN countries co ON m.country_id = co.country_id
            WHERE m.market_id = :market_id
        """), {"market_id": market_id}).fetchone()
        
        if not market_result:
            from flask import flash, redirect, url_for
            flash('Market not found', 'error')
            return redirect(url_for('main.markets_grid'))
        
        # Get market photos
        photos_result = db.execute(text("""
            SELECT photo_path
            FROM market_photos 
            WHERE market_id = :market_id
            ORDER BY created_at ASC
        """), {"market_id": market_id}).fetchall()
        
        # Convert to dict for template
        market = {
            'market_id': market_result.market_id,
            'market_name': market_result.market_name,
            'name': market_result.market_name,
            'description': getattr(market_result, 'description', ''),
            'city': market_result.city,
            'address': market_result.address,
            'latitude': market_result.latitude or 37.975334,
            'longitude': market_result.longitude or 23.734151,
            'phone': getattr(market_result, 'phone', ''),
            'email': getattr(market_result, 'email', ''),
            'website': getattr(market_result, 'website', ''),
            'company_name': market_result.company_name,
            'country_name': market_result.country_name,
            'photos': [{'path': photo.photo_path} for photo in photos_result]
        }
        
        db.close()
        
        return render_template('market-detail.html',
                             market=market,
                             google_maps_key=os.getenv('GOOGLE_MAPS_API_KEY', 'your-google-maps-api-key'))
        
    except Exception as e:
        from flask import flash, redirect, url_for
        print(f'Error loading market details for ID {market_id}: {str(e)}')
        flash(f'Error loading market details: {str(e)}', 'error')
        return redirect(url_for('main.markets_grid'))

@main_bp.route('/profile')
def profile():
    """User profile page"""
    # Check if user is logged in
    if not session.get('user_id'):
        from flask import redirect, url_for
        return redirect(url_for('auth.login'))
    
    # Debug session variables
    print(f"Session variables in profile route:")
    print(f"  user_id: {session.get('user_id')}")
    print(f"  user_name: {session.get('user_name', '')}")
    print(f"  is_admin: {session.get('is_admin', False)}")
    print(f"  user_photo: {session.get('user_photo', '')}")
    
    # Fetch user data from the database
    from config import ADMIN_CONFIG
    from sqlalchemy import create_engine, text
    from sqlalchemy.orm import sessionmaker
    
    # Database connection
    DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
    engine = create_engine(DATABASE_URL)
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    
    db = SessionLocal()
    
    try:
        # Get user details
        user_result = db.execute(text("""
            SELECT first_name, last_name, email, profile_photo_path
            FROM users 
            WHERE user_id = :user_id AND is_active = true
        """), {'user_id': session['user_id']}).fetchone()
        
        if not user_result:
            from flask import redirect, url_for
            return redirect(url_for('auth.login'))
        
        # Update session with latest user data
        session['user_name'] = f"{user_result.first_name} {user_result.last_name}"
        session['user_email'] = user_result.email
        if user_result.profile_photo_path:
            session['user_photo'] = user_result.profile_photo_path
        
        # Prepare user data for template
        user_data = {
            'name': session['user_name'],
            'email': user_result.email,
            'profile_photo': user_result.profile_photo_path
        }
        
        return render_template('profile.html', user_data=user_data)
    except Exception as e:
        from flask import flash
        flash(f'Error loading profile: {str(e)}', 'error')
        user_data = {
            'name': session.get('user_name', ''),
            'email': session.get('user_email', '')
        }
        return render_template('profile.html', user_data=user_data)
    finally:
        db.close()

@main_bp.route('/test-session')
def test_session():
    """Test route to check session variables"""
    from flask import session, jsonify
    return jsonify(dict(session))

@main_bp.route('/test-session-keys')
def test_session_keys():
    """Test route to check all session keys"""
    from flask import session, jsonify
    session_keys = list(session.keys())
    session_data = {}
    for key in session_keys:
        session_data[key] = session.get(key)
    print(f"All session keys and values: {session_data}")
    return jsonify(session_data)

@main_bp.route('/test-set-session')
def test_set_session():
    """Test route to manually set session variables"""
    from flask import session, redirect, url_for
    session['user_id'] = 'test-user-id'
    session['user_name'] = 'Test User'
    session['is_admin'] = True
    session['user_photo'] = ''
    print(f"Manually set session variables:")
    print(f"  user_id: {session.get('user_id')}")
    print(f"  user_name: {session.get('user_name')}")
    print(f"  is_admin: {session.get('is_admin')}")
    print(f"  user_photo: {session.get('user_photo')}")
    return redirect(url_for('main.index'))

@main_bp.route('/test-session-template')
def test_session_template():
    """Test route to check session variables in template"""
    from flask import session, render_template
    print(f"Template test - Session variables:")
    print(f"  is_admin: {session.get('is_admin')}")
    print(f"  user_id: {session.get('user_id')}")
    print(f"  user_name: {session.get('user_name')}")
    return render_template('test_session.html')

@main_bp.route('/debug-session')
def debug_session():
    """Debug route to check session variables"""
    from flask import session, jsonify
    session_vars = {
        'user_id': session.get('user_id'),
        'user_name': session.get('user_name'),
        'is_admin': session.get('is_admin'),
        'user_photo': session.get('user_photo')
    }
    print(f"Debug session route - Session variables: {session_vars}")
    return jsonify(session_vars)
