#!/usr/bin/env python3
"""
BookBeach Admin Interface
A simple Flask-based admin panel for managing the BookBeach application
"""

from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify, send_from_directory
from flask_cors import CORS
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
import os
import sys
from datetime import datetime, timedelta
import json
import secrets
from email_service import email_service

# Add the parent directory to the Python path so we can import from the main app
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# Import environment variables
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Try to import encryption utilities
try:
    sys.path.append(os.path.dirname(os.path.abspath(__file__)))
    from app.utils.encryption import decrypt_password, is_encrypted
except ImportError:
    # Fallback functions if encryption module is not available
    def decrypt_password(password, key='babagamma'):
        return password
    def is_encrypted(password, key='babagamma'):
        return False

def get_decrypted_env_var(var_name, default=''):
    """Get an environment variable and decrypt it if necessary"""
    value = os.getenv(var_name, default)
    if value and is_encrypted(value):
        try:
            return decrypt_password(value, 'babagamma')
        except Exception:
            return value
    return value

# Try to import terrain service
try:
    from terrain_service import TerrainTypeService, save_uploaded_file
except ImportError:
    print("Warning: Could not import terrain service")
    TerrainTypeService = None
    save_uploaded_file = None

# Try to import companies service
try:
    from companies_service import CompanyService, save_company_logo
except ImportError:
    print("Warning: Could not import companies service")
    CompanyService = None
    save_company_logo = None

from urllib.parse import quote_plus

# Admin configuration using environment variables
ADMIN_CONFIG = {
    'SECRET_KEY': os.getenv('SECRET_KEY', 'admin-secret-key-change-this-in-production'),
    'ADMIN_USERNAME': 'admin',
    'ADMIN_PASSWORD': get_decrypted_env_var('ADMIN_PASSWORD', 'AdminPassword123!'),
    'DATABASE_URL': f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(get_decrypted_env_var('DATABASE_PASSWORD'))}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
}

app = Flask(__name__, 
           template_folder='templates',
           static_folder='static')
app.config['SECRET_KEY'] = ADMIN_CONFIG['SECRET_KEY']
CORS(app, origins=["http://localhost:8001", "http://127.0.0.1:8001", "http://localhost:8080", "http://127.0.0.1:8080"])
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024  # 10MB max file size
app.config['UPLOAD_FOLDER'] = 'static/uploads'

# Flask-Login setup
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

class AdminUser(UserMixin):
    def __init__(self, username):
        self.id = username
        self.username = username

@login_manager.user_loader
def load_user(user_id):
    # Check if it's the hardcoded admin
    if user_id == ADMIN_CONFIG['ADMIN_USERNAME']:
        return AdminUser(user_id)
    
    # Check if it's a database user
    try:
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Look for user by first_name or email
        user_result = db.execute(text("""
            SELECT u.user_id, u.email, u.first_name, ur.role_name
            FROM users u
            JOIN user_roles ur ON u.role_id = ur.role_id
            WHERE (u.first_name = :user_id OR u.email = :user_id)
            AND u.is_active = true
            AND ur.role_name = 'admin'
        """), {"user_id": user_id}).fetchone()
        
        db.close()
        
        if user_result:
            return AdminUser(user_id)
    except:
        pass
    
    return None

# Routes
@app.route('/restaurant_photos/<path:filename>')
def serve_restaurant_photo(filename):
    """Serve restaurant photos from the restaurant_photos directory"""
    try:
        return send_from_directory('static/uploads/restaurant_photos', filename)
    except FileNotFoundError:
        # Return a default image if the photo doesn't exist
        return send_from_directory('static/img', 'tour_1.jpg')

@app.route('/')
def index():
    """Main landing page for users"""
    return render_template('index.html')

@app.route('/restaurants')
def restaurants_grid():
    """All restaurants grid page for users"""
    return render_template('restaurants-grid.html')

@app.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'))

@app.route('/beaches-grid')
def beaches_grid():
    """All beaches grid page for users"""
    return render_template('beaches-grid.html')

@app.route('/adventures-grid')
def adventures_grid():
    """All adventures grid page for users"""
    return render_template('adventures-grid.html')

@app.route('/markets-grid')
def markets_grid():
    """All markets grid page for users"""
    return render_template('markets-grid.html')

@app.route('/api/beaches-grid')
def get_beaches_grid():
    """Get beaches data for the grid page with filtering and pagination"""
    try:
        # Get request parameters - support both page and offset based pagination
        page = int(request.args.get('page', 1))
        offset = int(request.args.get('offset', 0))  # New offset parameter
        per_page = int(request.args.get('per_page', 12))
        filter_type = request.args.get('filter', 'all')
        search = request.args.get('search', '')
        country = request.args.get('country', '')
        city = request.args.get('city', '')
        category = request.args.get('category', '')
        
        # Use offset if provided, otherwise calculate from page
        if offset > 0:
            actual_offset = offset
        else:
            actual_offset = (page - 1) * per_page
        
        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()
        
        # Check if required tables exist
        beach_places_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'beach_places'
            )
        """)).fetchone()[0]
        
        beaches_data = []
        has_more = False
        
        if beach_places_exists:
            # Build the base query
            base_query = """
                SELECT bp.beach_place_id, bp.beach_name, bp.address, bp.city,
                       c.company_name, co.country_name,
                       COALESCE(booking_counts.booking_count, 0) as popularity,
                       bpp.photo_path,
                       bps.price, cur.currency_code,
                       bp.created_at, bp.updated_at
                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 (
                    SELECT beach_place_id, COUNT(*) as booking_count
                    FROM bookings 
                    WHERE status IN ('confirmed', 'completed')
                    GROUP BY beach_place_id
                ) booking_counts ON bp.beach_place_id = booking_counts.beach_place_id
                LEFT JOIN (
                    SELECT DISTINCT ON (beach_place_id) 
                           beach_place_id, photo_path
                    FROM beach_places_photos 
                    WHERE photo_primary = true
                    ORDER BY beach_place_id, sort_order
                ) bpp ON bp.beach_place_id = bpp.beach_place_id
                LEFT JOIN (
                    SELECT DISTINCT ON (beach_place_id)
                           beach_place_id, price, currency_id
                    FROM beach_places_schedules
                    WHERE from_date <= CURRENT_DATE AND to_date >= CURRENT_DATE
                    ORDER BY beach_place_id, from_date
                ) bps ON bp.beach_place_id = bps.beach_place_id
                LEFT JOIN currencies cur ON bps.currency_id = cur.currency_id
                WHERE bp.enable_beach = true
            """
            
            # Build WHERE conditions
            conditions = []
            params = {}
            
            if search:
                conditions.append("(bp.beach_name ILIKE :search OR bp.address ILIKE :search OR bp.city ILIKE :search OR c.company_name ILIKE :search)")
                params['search'] = f'%{search}%'
            
            if country:
                conditions.append("co.country_name ILIKE :country")
                params['country'] = f'%{country}%'
            
            if city:
                conditions.append("bp.city ILIKE :city")
                params['city'] = f'%{city}%'
            
            # Add filter conditions
            if filter_type == 'popular':
                conditions.append("COALESCE(booking_counts.booking_count, 0) >= 5")
            elif filter_type == 'latest':
                conditions.append("bp.created_at >= CURRENT_DATE - INTERVAL '30 days'")
            elif filter_type == 'tropical':
                conditions.append("(co.country_name IN ('Maldives', 'Thailand', 'Indonesia', 'Philippines') OR bp.address ILIKE '%tropical%')")
            elif filter_type == 'mediterranean':
                conditions.append("(co.country_name IN ('Greece', 'Italy', 'Spain', 'Turkey', 'Cyprus') OR bp.address ILIKE '%mediterranean%')")
            
            # Add conditions to query
            if conditions:
                base_query += " AND " + " AND ".join(conditions)
            
            # Add ordering
            if filter_type == 'popular':
                base_query += " ORDER BY popularity DESC, bp.beach_name"
            elif filter_type == 'latest':
                base_query += " ORDER BY bp.created_at DESC, bp.beach_name"
            else:
                base_query += " ORDER BY popularity DESC, bp.beach_name"
            
            # Get total count for pagination
            count_query = f"SELECT COUNT(*) FROM ({base_query}) as count_query"
            total_count = db.execute(text(count_query), params).fetchone()[0]
            
            # Add pagination
            paginated_query = base_query + f" LIMIT {per_page} OFFSET {actual_offset}"
            
            # Execute query
            beaches = db.execute(text(paginated_query), params).fetchall()
            
            # Check if there are more pages
            has_more = (actual_offset + per_page) < total_count
            
            # Format the results - use real data only
            for beach in beaches:
                # Build location string from real data
                location_parts = []
                if beach.city:
                    location_parts.append(beach.city)
                if beach.country_name:
                    location_parts.append(beach.country_name)
                location = ', '.join(location_parts) if location_parts else (beach.address or '')
                
                beach_data = {
                    'id': str(beach.beach_place_id),
                    'name': beach.beach_name or 'Beach',
                    'description': beach.beach_name or 'Beautiful beach location',  # Use beach name as description
                    'location': location,
                    'company': beach.company_name or '',
                    'country': beach.country_name or '',
                    'popularity': beach.popularity or 0,
                    'image': beach.photo_path or '/static/img/tour_1.jpg',
                    'price': float(beach.price) if beach.price else 0,
                    'currency': beach.currency_code or 'USD',
                    'rating': 0,  # Use real rating data when available
                    'review_count': 0,  # Use real review count when available
                    'view_count': 0,  # Use real view count when available
                    'created_at': beach.created_at.isoformat() if beach.created_at else None
                }
                beaches_data.append(beach_data)
        
        db.close()
        
        # If no beaches from database, return empty result
        if not beaches_data:
            return {'success': True, 'beaches': [], 'has_more': False}
        
        return {'success': True, 'beaches': beaches_data, 'has_more': has_more}
        
    except Exception as e:
        print(f"Error getting beaches grid: {e}")
        # Return empty result on error - no fake data
        return {'success': True, 'beaches': [], 'has_more': False}

@app.route('/api/adventures-grid')
def get_adventures_grid():
    """Get adventures data for the grid page with filtering and pagination"""
    try:
        # Get request parameters
        page = int(request.args.get('page', 1))
        offset = int(request.args.get('offset', 0))
        per_page = int(request.args.get('per_page', 12))
        filter_type = request.args.get('filter', 'all')
        search = request.args.get('search', '')
        country = request.args.get('country', '')
        city = request.args.get('city', '')
        
        # Use offset if provided, otherwise calculate from page
        if offset > 0:
            actual_offset = offset
        else:
            actual_offset = (page - 1) * per_page
        
        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()
        
        # Check if adventures table exists
        adventures_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'adventures'
            )
        """)).fetchone()[0]
        
        adventures_data = []
        has_more = False
        
        if adventures_exists:
            # Build the base query
            base_query = """
                SELECT a.adventure_id, a.adventure_name, a.description, a.address, a.city,
                       a.duration_minutes, a.max_participants, a.min_participants, a.price,
                       c.company_name, co.country_name, a.latitude, a.longitude,
                       a.phone, a.email, a.website, a.created_at, a.updated_at,
                       ap.photo_path
                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
                LEFT JOIN (
                    SELECT DISTINCT ON (adventure_id) 
                           adventure_id, photo_path
                    FROM adventure_photos 
                    ORDER BY adventure_id, created_at ASC
                ) ap ON a.adventure_id = ap.adventure_id
                WHERE 1=1
            """
            
            # Build WHERE conditions
            conditions = []
            params = {}
            
            if search:
                conditions.append("(a.name ILIKE :search OR a.description ILIKE :search OR a.city ILIKE :search OR c.company_name ILIKE :search)")
                params['search'] = f'%{search}%'
            
            if country:
                conditions.append("co.country_name ILIKE :country")
                params['country'] = f'%{country}%'
            
            if city:
                conditions.append("a.city ILIKE :city")
                params['city'] = f'%{city}%'
            
            # Add filter conditions
            if filter_type == 'popular':
                conditions.append("a.min_price IS NOT NULL AND a.min_price > 0")
            elif filter_type == 'latest':
                conditions.append("a.created_at >= CURRENT_DATE - INTERVAL '30 days'")
            
            # Add conditions to query
            if conditions:
                base_query += " AND " + " AND ".join(conditions)
            
            # Add ordering
            if filter_type == 'popular':
                base_query += " ORDER BY a.min_price DESC, a.name"
            elif filter_type == 'latest':
                base_query += " ORDER BY a.created_at DESC, a.name"
            else:
                base_query += " ORDER BY a.name"
            
            # Get total count for pagination
            count_query = f"SELECT COUNT(*) FROM ({base_query}) as count_query"
            total_count = db.execute(text(count_query), params).fetchone()[0]
            
            # Add pagination
            paginated_query = base_query + f" LIMIT {per_page} OFFSET {actual_offset}"
            
            # Execute query
            adventures = db.execute(text(paginated_query), params).fetchall()
            
            # Check if there are more pages
            has_more = (actual_offset + per_page) < total_count
            
            # Format the results
            for adventure in adventures:
                location_parts = []
                if adventure.city:
                    location_parts.append(adventure.city)
                if adventure.country_name:
                    location_parts.append(adventure.country_name)
                location = ', '.join(location_parts) if location_parts else (adventure.address or '')
                
                adventure_data = {
                    'id': str(adventure.adventure_id),
                    'adventure_id': str(adventure.adventure_id),
                    'adventure_name': adventure.adventure_name or 'Adventure',
                    'name': adventure.adventure_name or 'Adventure',
                    'description': adventure.description or 'Exciting adventure experience',
                    'location': location,
                    'company': adventure.company_name or '',
                    'country': adventure.country_name or '',
                    'city': adventure.city or '',
                    'address': adventure.address or '',
                    'duration_minutes': adventure.duration_minutes or 0,
                    'max_participants': adventure.max_participants or 0,
                    'min_participants': adventure.min_participants or 1,
                    'photo_path': adventure.photo_path or '/static/img/tour_default.jpg',
                    'image': adventure.photo_path or '/static/img/tour_default.jpg',
                    'price': float(adventure.price) if adventure.price else 0,
                    'currency': 'EUR',
                    'rating': 0,
                    'review_count': 0,
                    'view_count': 0,
                    'phone': adventure.phone or '',
                    'email': adventure.email or '',
                    'website': adventure.website or '',
                    'latitude': float(adventure.latitude) if adventure.latitude else None,
                    'longitude': float(adventure.longitude) if adventure.longitude else None,
                    'created_at': adventure.created_at.isoformat() if adventure.created_at else None,
                    'updated_at': adventure.updated_at.isoformat() if adventure.updated_at else None
                }
                adventures_data.append(adventure_data)
        
        db.close()
        
        return {'success': True, 'adventures': adventures_data, 'has_more': has_more}
        
    except Exception as e:
        print(f"Error getting adventures grid: {e}")
        return {'success': True, 'adventures': [], 'has_more': False}

@app.route('/api/markets-grid')
def get_markets_grid():
    """Get markets data for the grid page with filtering and pagination"""
    try:
        # Get request parameters
        page = int(request.args.get('page', 1))
        offset = int(request.args.get('offset', 0))
        per_page = int(request.args.get('per_page', 12))
        filter_type = request.args.get('filter', 'all')
        search = request.args.get('search', '')
        country = request.args.get('country', '')
        city = request.args.get('city', '')
        
        # Use offset if provided, otherwise calculate from page
        if offset > 0:
            actual_offset = offset
        else:
            actual_offset = (page - 1) * per_page
        
        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()
        
        # Check if markets table exists
        markets_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'markets'
            )
        """)).fetchone()[0]
        
        markets_data = []
        has_more = False
        
        if markets_exists:
            # Build the base query
            base_query = """
                SELECT m.market_id, m.market_name as name, m.description, m.address, m.city,
                       m.home_delivery, m.delivery_fee, m.min_order_amount, m.free_delivery_from,
                       m.opentime, m.closetime, m.opendays,
                       c.company_name, co.country_name, m.latitude, m.longitude,
                       m.phone, m.email, m.website, m.created_at, m.updated_at,
                       mp.path as photo_path
                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
                LEFT JOIN (
                    SELECT DISTINCT ON (market_id) 
                           market_id, path
                    FROM market_photos 
                    ORDER BY market_id, created_at ASC
                ) mp ON m.market_id = mp.market_id
                WHERE 1=1
            """
            
            # Build WHERE conditions
            conditions = []
            params = {}
            
            if search:
                conditions.append("(m.market_name ILIKE :search OR m.description ILIKE :search OR m.city ILIKE :search OR c.company_name ILIKE :search)")
                params['search'] = f'%{search}%'
            
            if country:
                conditions.append("co.country_name ILIKE :country")
                params['country'] = f'%{country}%'
            
            if city:
                conditions.append("m.city ILIKE :city")
                params['city'] = f'%{city}%'
            
            # Add filter conditions
            if filter_type == 'popular':
                conditions.append("m.home_delivery = true")
            elif filter_type == 'latest':
                conditions.append("m.created_at >= CURRENT_DATE - INTERVAL '30 days'")
            
            # Add conditions to query
            if conditions:
                base_query += " AND " + " AND ".join(conditions)
            
            # Add ordering
            if filter_type == 'popular':
                base_query += " ORDER BY m.home_delivery DESC, m.market_name"
            elif filter_type == 'latest':
                base_query += " ORDER BY m.created_at DESC, m.market_name"
            else:
                base_query += " ORDER BY m.market_name"
            
            # Get total count for pagination
            count_query = f"SELECT COUNT(*) FROM ({base_query}) as count_query"
            total_count = db.execute(text(count_query), params).fetchone()[0]
            
            # Add pagination
            paginated_query = base_query + f" LIMIT {per_page} OFFSET {actual_offset}"
            
            # Execute query
            markets = db.execute(text(paginated_query), params).fetchall()
            
            # Check if there are more pages
            has_more = (actual_offset + per_page) < total_count
            
            # Format the results
            for market in markets:
                location_parts = []
                if market.city:
                    location_parts.append(market.city)
                if market.country_name:
                    location_parts.append(market.country_name)
                location = ', '.join(location_parts) if location_parts else (market.address or '')
                
                market_data = {
                    'id': str(market.market_id),
                    'name': market.name or 'Market',
                    'description': market.description or 'Fresh local products and specialties',
                    'location': location,
                    'company': market.company_name or '',
                    'country': market.country_name or '',
                    'home_delivery': market.home_delivery or False,
                    'delivery_fee': float(market.delivery_fee) if market.delivery_fee else 0,
                    'min_order_amount': float(market.min_order_amount) if market.min_order_amount else 0,
                    'free_delivery_from': float(market.free_delivery_from) if market.free_delivery_from else 0,
                    'opening_hours': f"{market.opentime} - {market.closetime}" if market.opentime and market.closetime else '',
                    'image': market.photo_path or '/static/img/tour_default.jpg',
                    'currency': 'EUR',
                    'rating': 0,
                    'review_count': 0,
                    'created_at': market.created_at.isoformat() if market.created_at else None
                }
                markets_data.append(market_data)
        
        db.close()
        
        return {'success': True, 'markets': markets_data, 'has_more': has_more}
        
    except Exception as e:
        print(f"Error getting markets grid: {e}")
        return {'success': True, 'markets': [], 'has_more': False}

@app.route('/api/restaurants')
def get_restaurants():
    """Get restaurants data for the grid page with filtering and pagination"""
    try:
        # Get request parameters
        page = int(request.args.get('page', 1))
        offset = int(request.args.get('offset', 0))
        per_page = int(request.args.get('per_page', 12))
        filter_type = request.args.get('filter', 'all')
        search = request.args.get('search', '')  
        country = request.args.get('country', '')
        city = request.args.get('city', '')
        category = request.args.get('category', '')
        
        # Use offset if provided, otherwise calculate from page
        if offset > 0:
            actual_offset = offset
        else:
            actual_offset = (page - 1) * per_page
        
        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()
        
        # Check if required tables exist
        restaurants_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'restaurants'
            )
        """)).fetchone()[0]
        
        restaurants_data = []
        has_more = False
        
        if restaurants_exists:
            print(f"DEBUG: Restaurants table exists, checking structure...")
            
            # First, let's see what columns exist in the restaurants table
            columns_query = """
                SELECT column_name, data_type 
                FROM information_schema.columns 
                WHERE table_schema = 'public' AND table_name = 'restaurants'
                ORDER BY ordinal_position
            """
            columns = db.execute(text(columns_query)).fetchall()
            print(f"DEBUG: Restaurant table columns: {[(col.column_name, col.data_type) for col in columns]}")
            
            # Simple count check
            count_result = db.execute(text("SELECT COUNT(*) FROM restaurants")).fetchone()
            total_restaurants = count_result[0] if count_result else 0
            print(f"DEBUG: Total restaurants in table: {total_restaurants}")
            
            active_result = db.execute(text("SELECT COUNT(*) FROM restaurants WHERE is_active = true")).fetchone()
            active_restaurants = active_result[0] if active_result else 0
            print(f"DEBUG: Active restaurants: {active_restaurants}")
            
            # Check restaurant_photos table structure too
            if db.execute(text("""
                SELECT EXISTS (
                    SELECT FROM information_schema.tables 
                    WHERE table_schema = 'public' 
                    AND table_name = 'restaurant_photos'
                )
            """)).fetchone()[0]:
                photo_columns = db.execute(text("""
                    SELECT column_name, data_type 
                    FROM information_schema.columns 
                    WHERE table_schema = 'public' AND table_name = 'restaurant_photos'
                    ORDER BY ordinal_position
                """)).fetchall()
                print(f"DEBUG: Restaurant_photos table columns: {[(col.column_name, col.data_type) for col in photo_columns]}")
            
            # Build the base query with photos from restaurant_photos table
            base_query = """
                SELECT r.restaurant_id, r.restaurant_name as name, r.address, r.city, r.country_id,
                       co.country_name, r.latitude, r.longitude, r.cuisine_type,
                       r.description, r.created_at, r.phone, r.email, r.website, r.updated_at,
                       0 as popularity,
                       rp.photo_path
                FROM restaurants r
                LEFT JOIN countries co ON r.country_id = co.country_id
                LEFT JOIN (
                    SELECT DISTINCT ON (restaurant_id) 
                           restaurant_id, photo_path
                    FROM restaurant_photos 
                    WHERE is_primary = true
                    ORDER BY restaurant_id, created_at ASC
                ) rp ON r.restaurant_id = rp.restaurant_id
                WHERE r.is_active = true
            """
            
            # Build WHERE conditions
            conditions = []
            params = {}
            
            if search:
                conditions.append("(r.restaurant_name ILIKE :search OR r.address ILIKE :search OR r.city ILIKE :search OR r.cuisine_type ILIKE :search)")
                params['search'] = f'%{search}%'
            
            if country:
                conditions.append("co.country_name ILIKE :country")
                params['country'] = f'%{country}%'
            
            if city:
                conditions.append("r.city ILIKE :city")
                params['city'] = f'%{city}%'
            
            if category:
                conditions.append("r.cuisine_type ILIKE :category")
                params['category'] = f'%{category}%'
            
            # Add filter conditions
            if filter_type == 'popular':
                conditions.append("COALESCE(booking_counts.booking_count, 0) >= 5")
            elif filter_type == 'latest':
                conditions.append("r.created_at >= CURRENT_DATE - INTERVAL '30 days'")
            elif filter_type == 'top_rated':
                # For now, use popularity as proxy for rating
                conditions.append("COALESCE(booking_counts.booking_count, 0) >= 3")
            
            # Add conditions to query
            if conditions:
                base_query += " AND " + " AND ".join(conditions)
            
            # Add ordering
            if filter_type == 'popular':
                base_query += " ORDER BY popularity DESC, r.restaurant_name"
            elif filter_type == 'latest':
                base_query += " ORDER BY r.created_at DESC, r.restaurant_name"
            else:
                base_query += " ORDER BY popularity DESC, r.restaurant_name"
            
            print(f"DEBUG: Final query: {base_query}")
            print(f"DEBUG: Query params: {params}")
            
            # Get total count for pagination
            count_query = f"SELECT COUNT(*) FROM ({base_query}) as count_query"
            total_result = db.execute(text(count_query), params).fetchone()
            total_count = total_result[0] if total_result else 0
            print(f"DEBUG: Total count found: {total_count}")
            
            # Add pagination
            paginated_query = base_query + f" LIMIT {per_page} OFFSET {actual_offset}"
            
            # Execute query
            restaurants = db.execute(text(paginated_query), params).fetchall()
            
            # Check if there are more pages
            has_more = (actual_offset + per_page) < total_count
            
            # Format the results
            for restaurant in restaurants:
                # Build location string
                location_parts = []
                if restaurant.city:
                    location_parts.append(restaurant.city)
                if restaurant.country_name:
                    location_parts.append(restaurant.country_name)
                location = ', '.join(location_parts) if location_parts else (restaurant.address or '')
                
                restaurant_data = {
                    'id': str(restaurant.restaurant_id),
                    'name': restaurant.name or 'Restaurant',
                    'description': restaurant.description or f'Delicious {restaurant.cuisine_type or ""}  cuisine',
                    'location': location,
                    'address': restaurant.address or '',
                    'city': restaurant.city or '',
                    'country': restaurant.country_name or '',
                    'cuisine_type': restaurant.cuisine_type or '',
                    'phone': restaurant.phone or '',
                    'email': restaurant.email or '',
                    'website': restaurant.website or '',
                    'latitude': float(restaurant.latitude) if restaurant.latitude else None,
                    'longitude': float(restaurant.longitude) if restaurant.longitude else None,
                    'popularity': restaurant.popularity or 0,
                    'image': ('/' + restaurant.photo_path.replace('\\', '/')) if restaurant.photo_path else '/static/img/restaurant_default.jpg',
                    'rating': 4.2,  # Use real rating data when available
                    'review_count': 12,  # Use real review count when available
                    'price_range': '$$',  # Add price range when available
                    'created_at': restaurant.created_at.isoformat() if restaurant.created_at else None,
                    'updated_at': restaurant.updated_at.isoformat() if hasattr(restaurant, 'updated_at') and restaurant.updated_at else None
                }
                restaurants_data.append(restaurant_data)
        
        db.close()
        
        return {'success': True, 'restaurants': restaurants_data, 'has_more': has_more}
        
    except Exception as e:
        print(f"Error getting restaurants: {e}")
        return {'success': True, 'restaurants': [], 'has_more': False}

@app.route('/api/restaurants/<restaurant_id>')
def get_restaurant_detail(restaurant_id):
    """Get detailed restaurant information"""
    try:
        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()
        
        # Get restaurant details with photos
        restaurant_query = """
            SELECT r.restaurant_id, r.restaurant_name as name, r.description, r.address, r.city, r.country_id,
                   co.country_name, r.latitude, r.longitude, r.cuisine_type,
                   r.phone, r.email, r.website, 
                   CONCAT(r.opening_time::text, ' - ', r.closing_time::text) as opening_hours,
                   r.created_at, r.updated_at,
                   0 as popularity
            FROM restaurants r
            LEFT JOIN countries co ON r.country_id = co.country_id
            WHERE r.restaurant_id = :restaurant_id
        """
        
        restaurant = db.execute(text(restaurant_query), {"restaurant_id": restaurant_id}).fetchone()
        
        if not restaurant:
            return {'success': False, 'message': 'Restaurant not found'}, 404
        
        # Get restaurant photos
        photos_query = """
            SELECT photo_path, is_primary, created_at
            FROM restaurant_photos 
            WHERE restaurant_id = :restaurant_id
            ORDER BY is_primary DESC, created_at ASC
        """
        
        photos = db.execute(text(photos_query), {"restaurant_id": restaurant_id}).fetchall()
        
        # Get restaurant categories
        categories_query = """
            SELECT rc.category_id, rc.category_name, rc.description, rc.sort_order
            FROM restaurant_categories rc
            WHERE rc.restaurant_id = :restaurant_id
            ORDER BY rc.sort_order, rc.category_name
        """
        
        categories = db.execute(text(categories_query), {"restaurant_id": restaurant_id}).fetchall()
        
        # Get restaurant menu items grouped by category
        menu_items_query = """
            SELECT ri.item_id, ri.item_name, ri.description, ri.price, ri.currency_id,
                   ri.photo_path, ri.is_available, ri.preparation_time, ri.allergens,
                   ri.is_vegetarian, ri.is_vegan, rc.category_name, cur.currency_code
            FROM restaurant_items ri
            LEFT JOIN restaurant_categories rc ON ri.category_id = rc.category_id
            LEFT JOIN currencies cur ON ri.currency_id = cur.currency_id
            WHERE ri.restaurant_id = :restaurant_id AND ri.is_available = true
            ORDER BY rc.sort_order, rc.category_name, ri.item_name
        """
        
        menu_items = db.execute(text(menu_items_query), {"restaurant_id": restaurant_id}).fetchall()
        
        db.close()
        
        # Build location string
        location_parts = []
        if restaurant.city:
            location_parts.append(restaurant.city)
        if restaurant.country_name:
            location_parts.append(restaurant.country_name)
        location = ', '.join(location_parts) if location_parts else (restaurant.address or '')
        
        # Format photos
        photo_list = []
        for photo in photos:
            photo_list.append({
                'url': ('/' + photo.photo_path.replace('\\', '/')) if photo.photo_path else '/static/img/restaurant_default.jpg',
                'is_primary': photo.is_primary,
                'created_at': photo.created_at.isoformat() if photo.created_at else None
            })
        
        # If no photos, add default
        if not photo_list:
            photo_list.append({
                'url': '/static/img/restaurant_default.jpg',
                'is_primary': True,
                'created_at': None
            })
        
        # Format categories
        categories_list = []
        for category in categories:
            categories_list.append({
                'id': category.category_id,
                'name': category.category_name,
                'description': category.description or '',
                'sort_order': category.sort_order or 0
            })
        
        # Format menu items
        menu_items_list = []
        for item in menu_items:
            menu_items_list.append({
                'id': str(item.item_id),
                'name': item.item_name,
                'description': item.description or '',
                'price': float(item.price) if item.price else 0.0,
                'currency_code': item.currency_code or 'EUR',
                'photo_path': ('/' + item.photo_path.replace('\\', '/')) if item.photo_path else None,
                'is_available': item.is_available,
                'preparation_time': item.preparation_time,
                'allergens': item.allergens or '',
                'is_vegetarian': item.is_vegetarian or False,
                'is_vegan': item.is_vegan or False,
                'category_name': item.category_name or 'General'
            })
        
        restaurant_data = {
            'id': str(restaurant.restaurant_id),
            'name': restaurant.name or 'Restaurant',
            'description': restaurant.description or f'Delicious {restaurant.cuisine_type or ""} cuisine',
            'location': location,
            'address': restaurant.address or '',
            'city': restaurant.city or '',
            'country': restaurant.country_name or '',
            'cuisine_type': restaurant.cuisine_type or '',
            'phone': restaurant.phone or '',
            'email': restaurant.email or '',
            'website': restaurant.website or '',
            'opening_hours': restaurant.opening_hours or '',
            'latitude': float(restaurant.latitude) if restaurant.latitude else None,
            'longitude': float(restaurant.longitude) if restaurant.longitude else None,
            'popularity': restaurant.popularity or 0,
            'photos': photo_list,
            'categories': categories_list,
            'menu_items': menu_items_list,
            'rating': 4.2,  # Use real rating when available
            'review_count': restaurant.popularity * 8 if restaurant.popularity else 12,
            'price_range': '$$',  # Add price range when available
            'created_at': restaurant.created_at.isoformat() if restaurant.created_at else None,
            'updated_at': restaurant.updated_at.isoformat() if hasattr(restaurant, 'updated_at') and restaurant.updated_at else None
        }
        
        return {'success': True, 'restaurant': restaurant_data}
        
    except Exception as e:
        print(f"Error getting restaurant detail: {e}")
        return {'success': False, 'message': 'Error loading restaurant details'}, 500

@app.route('/api/popular-restaurants')
def get_popular_restaurants():
    """Get popular restaurants based on location and bookings"""
    try:
        # Get country from request parameter
        user_country = request.args.get('country', '')
        
        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()
        
        # Check if required tables exist
        restaurants_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'restaurants'
            )
        """)).fetchone()[0]
        
        popular_restaurants = []
        
        if restaurants_exists:
            # Base query for restaurants with popularity data
            base_query = """
                SELECT r.restaurant_id, r.name, r.address, r.city, r.country_id,
                       co.country_name, r.cuisine_type, r.description,
                       COALESCE(booking_counts.booking_count, 0) as popularity,
                       rp.photo_path
                FROM restaurants r
                LEFT JOIN countries co ON r.country_id = co.country_id
                LEFT JOIN (
                    SELECT restaurant_id, COUNT(*) as booking_count
                    FROM bookings 
                    WHERE status IN ('confirmed', 'completed')
                    GROUP BY restaurant_id
                ) booking_counts ON r.restaurant_id = booking_counts.restaurant_id
                LEFT JOIN (
                    SELECT DISTINCT ON (restaurant_id) 
                           restaurant_id, photo_path
                    FROM restaurant_photos 
                    WHERE is_primary = true
                    ORDER BY restaurant_id, created_at ASC
                ) rp ON r.restaurant_id = rp.restaurant_id
                WHERE 1=1
            """
            
            if user_country:
                # Try to get restaurants from user's country first
                country_restaurants = db.execute(text(base_query + """
                    AND co.country_name = :country
                    ORDER BY popularity DESC, r.name
                    LIMIT 10
                """), {"country": user_country}).fetchall()
                
                popular_restaurants = list(country_restaurants)
            
            # If we don't have 10 restaurants from user's country, fill with popular restaurants from anywhere
            if len(popular_restaurants) < 10:
                remaining_needed = 10 - len(popular_restaurants)
                existing_ids = [str(r.restaurant_id) for r in popular_restaurants]
                
                additional_query = base_query
                if existing_ids:
                    placeholders = ','.join(['%s'] * len(existing_ids))
                    additional_query += f" AND r.restaurant_id NOT IN ({placeholders})"
                additional_query += " ORDER BY popularity DESC, r.name LIMIT :limit"
                
                params = {"limit": remaining_needed}
                if existing_ids:
                    additional_restaurants = db.execute(text(additional_query), 
                                                      existing_ids + [remaining_needed]).fetchall()
                else:
                    additional_restaurants = db.execute(text(additional_query), params).fetchall()
                
                popular_restaurants.extend(additional_restaurants)
            
            # If still not enough restaurants, get random ones
            if len(popular_restaurants) < 10:
                remaining_needed = 10 - len(popular_restaurants)
                existing_ids = [str(r.restaurant_id) for r in popular_restaurants]
                
                random_query = base_query
                if existing_ids:
                    placeholders = ','.join(['%s'] * len(existing_ids))
                    random_query += f" AND r.restaurant_id NOT IN ({placeholders})"
                random_query += " ORDER BY RANDOM() LIMIT :limit"
                
                params = {"limit": remaining_needed}
                if existing_ids:
                    random_restaurants = db.execute(text(random_query), 
                                                  existing_ids + [remaining_needed]).fetchall()
                else:
                    random_restaurants = db.execute(text(random_query), params).fetchall()
                
                popular_restaurants.extend(random_restaurants)
        
        db.close()
        
        # Format the response
        restaurants_data = []
        for restaurant in popular_restaurants:
            location_parts = []
            if restaurant.city:
                location_parts.append(restaurant.city)
            if restaurant.country_name:
                location_parts.append(restaurant.country_name)
            location = ', '.join(location_parts) if location_parts else (restaurant.address or 'Great Location')
            
            restaurant_data = {
                'id': str(restaurant.restaurant_id),
                'name': restaurant.name,
                'location': location,
                'cuisine_type': restaurant.cuisine_type or 'International',
                'popularity': restaurant.popularity or 0,
                'image': restaurant.photo_path or '/static/img/restaurant_default.jpg',
                'rating': round(4.0 + (restaurant.popularity * 0.1), 1) if restaurant.popularity else 4.2,
                'reviews': restaurant.popularity * 8 if restaurant.popularity else 12,
                'description': restaurant.description or f'Delicious {restaurant.cuisine_type or ""} cuisine'
            }
            restaurants_data.append(restaurant_data)
        
        return {'success': True, 'restaurants': restaurants_data}
        
    except Exception as e:
        print(f"Error getting popular restaurants: {e}")
        return {'success': True, 'restaurants': []}

@app.route('/api/popular-beaches')
def get_popular_beaches():
    """Get popular beaches based on location and bookings"""
    try:
        # Get country from request parameter (sent from frontend)
        user_country = request.args.get('country', '')
        
        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()
        
        # Check if required tables exist
        beach_places_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'beach_places'
            )
        """)).fetchone()[0]
        
        bookings_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'bookings'
            )
        """)).fetchone()[0]
        
        countries_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'countries'
            )
        """)).fetchone()[0]
        
        popular_beaches = []
        
        if beach_places_exists:
            # First try to get beaches from the user's country ordered by booking popularity
            country_beaches_query = """
                SELECT bp.beach_place_id, bp.beach_name, bp.address, bp.city,
                       c.company_name, co.country_name,
                       COALESCE(booking_counts.booking_count, 0) as popularity,
                       bpp.photo_path,
                       bps.price, cur.currency_code
                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 (
                    SELECT beach_place_id, COUNT(*) as booking_count
                    FROM bookings 
                    WHERE status IN ('confirmed', 'completed')
                    GROUP BY beach_place_id
                ) booking_counts ON bp.beach_place_id = booking_counts.beach_place_id
                LEFT JOIN (
                    SELECT DISTINCT ON (beach_place_id) 
                           beach_place_id, photo_path
                    FROM beach_places_photos 
                    WHERE photo_primary = true
                    ORDER BY beach_place_id, sort_order
                ) bpp ON bp.beach_place_id = bpp.beach_place_id
                LEFT JOIN (
                    SELECT DISTINCT ON (beach_place_id)
                           beach_place_id, price, currency_id
                    FROM beach_places_schedules
                    WHERE from_date <= CURRENT_DATE AND to_date >= CURRENT_DATE
                    ORDER BY beach_place_id, from_date
                ) bps ON bp.beach_place_id = bps.beach_place_id
                LEFT JOIN currencies cur ON bps.currency_id = cur.currency_id
                WHERE bp.enable_beach = true
            """
            
            if user_country and countries_exists:
                # Try to get beaches from user's country first
                country_beaches = db.execute(text(country_beaches_query + """
                    AND co.country_name = :country
                    ORDER BY popularity DESC, bp.beach_name
                    LIMIT 10
                """), {"country": user_country}).fetchall()
                
                popular_beaches = list(country_beaches)
            
            # If we don't have 10 beaches from user's country, fill with popular beaches from anywhere
            if len(popular_beaches) < 10:
                remaining_needed = 10 - len(popular_beaches)
                existing_ids = [str(beach.beach_place_id) for beach in popular_beaches]
                
                additional_beaches_query = country_beaches_query
                if existing_ids:
                    additional_beaches_query += f" AND bp.beach_place_id NOT IN ({','.join(['%s'] * len(existing_ids))})"
                additional_beaches_query += " ORDER BY popularity DESC, bp.beach_name LIMIT :limit"
                
                params = {"limit": remaining_needed}
                if existing_ids:
                    additional_beaches = db.execute(text(additional_beaches_query), 
                                                  existing_ids + [remaining_needed]).fetchall()
                else:
                    additional_beaches = db.execute(text(additional_beaches_query), params).fetchall()
                
                popular_beaches.extend(additional_beaches)
            
            # If still not enough beaches, get random ones
            if len(popular_beaches) < 10:
                remaining_needed = 10 - len(popular_beaches)
                existing_ids = [str(beach.beach_place_id) for beach in popular_beaches]
                
                random_beaches_query = country_beaches_query
                if existing_ids:
                    random_beaches_query += f" AND bp.beach_place_id NOT IN ({','.join(['%s'] * len(existing_ids))})"
                random_beaches_query += " ORDER BY RANDOM() LIMIT :limit"
                
                params = {"limit": remaining_needed}
                if existing_ids:
                    random_beaches = db.execute(text(random_beaches_query), 
                                              existing_ids + [remaining_needed]).fetchall()
                else:
                    random_beaches = db.execute(text(random_beaches_query), params).fetchall()
                
                popular_beaches.extend(random_beaches)
        
        db.close()
        
        # Format the response
        beaches_data = []
        for beach in popular_beaches:
            beach_data = {
                'id': str(beach.beach_place_id),
                'name': beach.beach_name,
                'location': f"{beach.city}, {beach.country_name}" if beach.city and beach.country_name else beach.address or 'Beautiful Location',
                'company': beach.company_name or 'Premium Beach',
                'popularity': beach.popularity or 0,
                'image': beach.photo_path or '/static/img/tour_1.jpg',
                'price': float(beach.price) if beach.price else 25.0,
                'currency': beach.currency_code or 'USD',
                'rating': round(4.5 + (beach.popularity * 0.1), 1) if beach.popularity else 4.5,
                'reviews': beach.popularity * 10 if beach.popularity else 50
            }
            beaches_data.append(beach_data)
        
        return {'success': True, 'beaches': beaches_data}
        
    except Exception as e:
        print(f"Error getting popular beaches: {e}")
        # Return empty result on error - no fake data
        return {'success': True, 'beaches': []}

@app.route('/admin')
@login_required
def dashboard():
    """Admin dashboard"""
    # Get real statistics from database
    stats = {
        'total_users': 0,
        'total_companies': 0,
        'total_beaches': 0,
        'total_bookings': 0,
        'pending_companies': 0,
        'active_bookings': 0
    }
    recent_activities = []
    
    try:
        # Database connection
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        # Use a fresh connection for each query to avoid transaction issues
        connection = engine.connect()
        
        # Count total users
        try:
            result = connection.execute(text("SELECT COUNT(*) as count FROM users")).fetchone()
            if result:
                stats['total_users'] = result[0]
        except Exception as e:
            print(f"Error counting users: {e}")
        
        # Count total companies (if table exists)
        try:
            table_check = connection.execute(text("""
                SELECT EXISTS (
                    SELECT FROM information_schema.tables 
                    WHERE table_schema = 'public' AND table_name = 'companies'
                )
            """)).fetchone()
            
            if table_check and table_check[0]:
                result = connection.execute(text("SELECT COUNT(*) as count FROM companies")).fetchone()
                if result:
                    stats['total_companies'] = result[0]
                
                # Count pending companies
                result = connection.execute(text("""
                    SELECT COUNT(*) as count FROM companies 
                    WHERE company_status = 'pending'
                """)).fetchone()
                if result:
                    stats['pending_companies'] = result[0]
        except Exception as e:
            print(f"Error counting companies: {e}")
        
        # Count total beaches (using beach_places table)
        try:
            table_check = connection.execute(text("""
                SELECT EXISTS (
                    SELECT FROM information_schema.tables 
                    WHERE table_schema = 'public' AND table_name = 'beach_places'
                )
            """)).fetchone()
            
            if table_check and table_check[0]:
                result = connection.execute(text("SELECT COUNT(*) as count FROM beach_places")).fetchone()
                if result:
                    stats['total_beaches'] = result[0]
        except Exception as e:
            print(f"Error counting beach places: {e}")
        
        # Count total bookings (if table exists)
        try:
            table_check = connection.execute(text("""
                SELECT EXISTS (
                    SELECT FROM information_schema.tables 
                    WHERE table_schema = 'public' AND table_name = 'bookings'
                )
            """)).fetchone()
            
            if table_check and table_check[0]:
                result = connection.execute(text("SELECT COUNT(*) as count FROM bookings")).fetchone()
                if result:
                    stats['total_bookings'] = result[0]
                
                # Count active bookings
                result = connection.execute(text("""
                    SELECT COUNT(*) as count FROM bookings 
                    WHERE status IN ('confirmed', 'active')
                    AND booking_date >= CURRENT_DATE
                """)).fetchone()
                if result:
                    stats['active_bookings'] = result[0]
        except Exception as e:
            print(f"Error counting bookings: {e}")
        
        # Get recent activity from database
        try:
            # Use a fresh connection for activities to avoid transaction errors
            with engine.connect() as activity_conn:
                # Recent user registrations
                user_activities = activity_conn.execute(text("""
                    SELECT u.email, u.first_name, u.created_at, 'user_registered' as activity_type
                    FROM users u
                    WHERE u.created_at >= NOW() - INTERVAL '7 days'
                    ORDER BY u.created_at DESC
                    LIMIT 3
                """)).fetchall()
            
                for activity in user_activities:
                    recent_activities.append({
                        'icon': 'fas fa-user-plus text-success',
                        'title': 'New user registered',
                        'description': f"{activity[0]} joined BookBeach",
                        'time': activity[2]
                    })
                
                # Recent company applications (if table exists)
                try:
                    company_activities = activity_conn.execute(text("""
                        SELECT company_name, create_date, company_status, 'company_application' as activity_type
                        FROM companies
                        WHERE create_date >= NOW() - INTERVAL '7 days'
                        ORDER BY create_date DESC
                        LIMIT 3
                    """)).fetchall()
                    
                    for activity in company_activities:
                        status_text = 'awaiting review' if activity[2] == 'pending' else f'status: {activity[2]}'
                        recent_activities.append({
                            'icon': 'fas fa-building text-primary',
                            'title': 'Company application',
                            'description': f"{activity[0]} {status_text}",
                            'time': activity[1]
                        })
                except Exception:
                    pass  # Companies table might not exist
                
                # Recent bookings (if table exists)
                try:
                    booking_activities = activity_conn.execute(text("""
                        SELECT b.booking_id, b.created_at, b.status as booking_status, 
                               bp.beach_name, 'booking_created' as activity_type
                        FROM bookings b
                        LEFT JOIN beach_places bp ON b.beach_place_id = bp.beach_place_id
                        WHERE b.created_at >= NOW() - INTERVAL '7 days'
                        ORDER BY b.created_at DESC
                        LIMIT 3
                    """)).fetchall()
                    
                    for activity in booking_activities:
                        beach_name = activity[3] or 'Unknown Beach'
                        status_icon = 'fas fa-calendar-check text-success' if activity[2] == 'confirmed' else 'fas fa-calendar text-warning'
                        recent_activities.append({
                            'icon': status_icon,
                            'title': f'Booking {activity[2]}',
                            'description': f"{beach_name} - Booking #{activity[0]}",
                            'time': activity[1]
                        })
                except Exception:
                    pass  # Bookings table might not exist
                    
                # Recent beach additions (using beach_places table)
                try:
                    beach_activities = activity_conn.execute(text("""
                        SELECT bp.beach_name, bp.created_at, c.company_name, 'beach_added' as activity_type
                        FROM beach_places bp
                        LEFT JOIN companies c ON bp.company_id = c.company_id
                        WHERE bp.created_at >= NOW() - INTERVAL '7 days'
                        ORDER BY bp.created_at DESC
                        LIMIT 2
                    """)).fetchall()
                    
                    for activity in beach_activities:
                        company_name = activity[2] or 'Unknown Company'
                        recent_activities.append({
                            'icon': 'fas fa-umbrella-beach text-info',
                            'title': 'New beach location added',
                            'description': f"{activity[0]} added by {company_name}",
                            'time': activity[1]
                        })
                except Exception:
                    pass  # Beach places table might not exist
                
        except Exception as e:
            print(f"Error loading recent activities: {e}")
        
        # Sort activities by time and limit to 5 most recent
        recent_activities.sort(key=lambda x: x['time'] if x['time'] else datetime.min, reverse=True)
        recent_activities = recent_activities[:5]
        
        # Format relative times
        for activity in recent_activities:
            if activity['time']:
                time_diff = datetime.now() - activity['time'].replace(tzinfo=None)
                if time_diff.days > 0:
                    activity['time_ago'] = f"{time_diff.days} day{'s' if time_diff.days > 1 else ''} ago"
                elif time_diff.seconds > 3600:
                    hours = time_diff.seconds // 3600
                    activity['time_ago'] = f"{hours} hour{'s' if hours > 1 else ''} ago"
                else:
                    minutes = max(1, time_diff.seconds // 60)
                    activity['time_ago'] = f"{minutes} minute{'s' if minutes > 1 else ''} ago"
            else:
                activity['time_ago'] = 'Unknown'
        
        connection.close()
        
    except Exception as e:
        flash(f'Error loading dashboard statistics: {str(e)}', 'warning')
        print(f"Dashboard error: {e}")
    
    return render_template('dashboard.html', stats=stats, recent_activities=recent_activities)

@app.route('/register')
def register():
    """User registration page using BookBeach template"""
    return render_template('auth_register.html')

# Route removed - redirecting users to home page instead

@app.route('/admin/login', methods=['GET', 'POST'])
def admin_login():
    """Admin login"""
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        # First check hardcoded admin credentials
        if (username == ADMIN_CONFIG['ADMIN_USERNAME'] and 
            password == ADMIN_CONFIG['ADMIN_PASSWORD']):
            user = AdminUser(username)
            login_user(user)
            next_page = request.args.get('next')
            return redirect(next_page) if next_page else redirect(url_for('dashboard'))
        
        # Then check database users with admin role
        try:
            # Use passlib for password checking (consistent with user creation)
            from passlib.context import CryptContext
            pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
            
            # Database connection
            DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
            engine = create_engine(DATABASE_URL)
            SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
            
            db = SessionLocal()
            
            # Look for user by email or first_name (username)
            user_result = db.execute(text("""
                SELECT u.user_id, u.email, u.password_hash, u.first_name, ur.role_name
                FROM users u
                JOIN user_roles ur ON u.role_id = ur.role_id
                WHERE (u.email = :username OR u.first_name = :username)
                AND u.is_active = true
                AND ur.role_name = 'admin'
            """), {"username": username}).fetchone()
            
            if user_result and pwd_context.verify(password, user_result.password_hash):
                # Login successful with database user
                user = AdminUser(user_result.first_name or user_result.email)
                login_user(user)
                flash(f'Welcome {user_result.first_name}!', 'success')
                next_page = request.args.get('next')
                return redirect(next_page) if next_page else redirect(url_for('dashboard'))
            
            db.close()
            
        except Exception as e:
            print(f"Database login error: {e}")
            pass
        
        flash('Invalid username or password', 'error')
    
    return render_template('login.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    """User login using BookBeach template"""
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        # Check database users
        try:
            from passlib.context import CryptContext
            pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
            
            DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
            engine = create_engine(DATABASE_URL)
            SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
            
            db = SessionLocal()
            
            # Look for user by email or first_name (username)
            user_result = db.execute(text("""
                SELECT u.user_id, u.email, u.password_hash, u.first_name, ur.role_name
                FROM users u
                JOIN user_roles ur ON u.role_id = ur.role_id
                WHERE (u.email = :username OR u.first_name = :username)
                AND u.is_active = true
            """), {"username": username}).fetchone()
            
            if user_result and pwd_context.verify(password, user_result.password_hash):
                # Check if admin - redirect to admin dashboard
                if user_result.role_name == 'admin':
                    user = AdminUser(user_result.first_name or user_result.email)
                    login_user(user)
                    flash(f'Welcome {user_result.first_name}!', 'success')
                    return redirect(url_for('dashboard'))
                else:
                    # Regular user - redirect to main page
                    flash(f'Welcome {user_result.first_name}!', 'success')
                    return redirect(url_for('index'))
            
            db.close()
            
        except Exception as e:
            print(f"Database login error: {e}")
            pass
        
        flash('Invalid username or password', 'error')
    
    return render_template('auth_login.html')

@app.route('/forgot-password', methods=['GET'])
def forgot_password():
    """Display forgot password page"""
    return render_template('auth_forgot_password.html')

# API Routes for Registration Process
@app.route('/api/send-verification', methods=['POST'])
def api_send_verification():
    """Send email verification code"""
    try:
        data = request.get_json()
        email = data.get('email')
        
        if not email:
            return jsonify({'success': False, 'message': 'Email is required'}), 400
        
        # Check if email already exists
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        existing_user = db.execute(text(
            "SELECT user_id FROM users WHERE email = :email"
        ), {"email": email}).fetchone()
        
        db.close()
        
        if existing_user:
            return jsonify({'success': False, 'message': 'Email already registered'}), 400
        
        # Generate verification code
        import random
        verification_code = f"{random.randint(100000, 999999)}"
        
        # Store in session for now (in production, use Redis or database)
        session[f'verification_code_{email}'] = verification_code
        
        # Send email using the new email service
        first_name = data.get('first_name', 'User')
        success = email_service.send_verification_email(
            to_email=email,
            first_name=first_name,
            verification_code=verification_code,
            expiry_minutes=15
        )
        
        if success:
            return jsonify({'success': True, 'message': 'Verification code sent to your email'})
        else:
            return jsonify({'success': False, 'message': 'Failed to send verification email'}), 500
        
    except Exception as e:
        print(f"Send verification error: {e}")
        return jsonify({'success': False, 'message': 'Failed to send verification code'}), 500

@app.route('/api/verify-email', methods=['POST'])
def api_verify_email():
    """Verify email with code"""
    try:
        data = request.get_json()
        email = data.get('email')
        code = data.get('code')
        
        if not email or not code:
            return jsonify({'success': False, 'message': 'Email and code are required'}), 400
        
        # Check verification code
        stored_code = session.get(f'verification_code_{email}')
        
        if not stored_code or stored_code != code:
            return jsonify({'success': False, 'message': 'Invalid verification code'}), 400
        
        # Mark email as verified
        session[f'email_verified_{email}'] = True
        
        return jsonify({'success': True, 'message': 'Email verified successfully'})
        
    except Exception as e:
        print(f"Verify email error: {e}")
        return jsonify({'success': False, 'message': 'Failed to verify email'}), 500

@app.route('/api/complete-registration', methods=['POST'])
def api_complete_registration_legacy():
    """Complete user registration - Legacy version for older templates"""
    try:
        data = request.get_json()
        email = data.get('email')
        
        # Check if email was verified
        if not session.get(f'email_verified_{email}'):
            return jsonify({'success': False, 'message': 'Email not verified'}), 400
        
        # Hash password
        from passlib.context import CryptContext
        pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
        password_hash = pwd_context.hash(data.get('password'))
        
        # Database connection
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Get customer role (default for regular users)
        role_result = db.execute(text(
            "SELECT role_id FROM user_roles WHERE role_name = 'customer' LIMIT 1"
        )).fetchone()
        
        if not role_result:
            # Create customer role if it doesn't exist
            db.execute(text(
                "INSERT INTO user_roles (role_name, description) VALUES ('customer', 'Regular customer user') RETURNING role_id"
            ))
            role_result = db.execute(text(
                "SELECT role_id FROM user_roles WHERE role_name = 'customer' LIMIT 1"
            )).fetchone()
        
        role_id = role_result.role_id
        
        # Insert user
        result = db.execute(text("""
            INSERT INTO users (
                email, password_hash, first_name, last_name, phone, country_id,
                role_id, is_active, is_email_verified, created_at, updated_at
            ) VALUES (
                :email, :password_hash, :first_name, :last_name, :phone, :country_id,
                :role_id, true, true, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
            ) RETURNING user_id
        """), {
            "email": email,
            "password_hash": password_hash,
            "first_name": data.get('first_name'),
            "last_name": data.get('last_name'),
            "phone": data.get('phone'),
            "country_id": data.get('country_id'),
            "role_id": role_id
        })
        
        user_id = result.fetchone().user_id
        
        # Handle business registration
        if data.get('user_type') == 'business':
            # Insert company with all required fields
            # Provide default values for required fields that are not sent by the frontend
            db.execute(text("""
                INSERT INTO companies (
                    company_name, address, country_id, province, city, postal_code,
                    phone, email, registration_number, website, company_status, create_date
                ) VALUES (
                    :company_name, :address, :country_id, :province, :city, :postal_code,
                    :phone, :email, :registration_number, :website, 'pending', CURRENT_TIMESTAMP
                )
            """), {
                "company_name": data.get('company_name'),
                "address": data.get('address'),
                "country_id": int(data.get('country_id')),  # Use the same country_id as user
                "province": "N/A",  # Default value for required field
                "city": "N/A",      # Default value for required field
                "postal_code": "N/A",  # Default value for required field
                "phone": data.get('phone', '') or data.get('mobile', '') or email,  # Use phone, mobile, or email as fallback
                "email": email,  # Use the same email as user
                "registration_number": data.get('registration_number', ''),  # Optional field
                "website": data.get('website', '')  # Optional field
            })
        
        db.commit()
        db.close()
        
        # Clear verification data
        session.pop(f'verification_code_{email}', None)
        session.pop(f'email_verified_{email}', None)
        
        # Send welcome email
        email_service.send_welcome_email(
            to_email=email,
            first_name=data.get('first_name', 'User')
        )
        
        return jsonify({
            'success': True, 
            'message': 'Registration completed successfully!',
            'redirect_url': url_for('index')
        })
        
    except Exception as e:
        print(f"Complete registration error: {e}")
        return jsonify({'success': False, 'message': 'Failed to complete registration'}), 500

# API Routes for Forgot Password Process
@app.route('/api/forgot-password', methods=['POST'])
def api_forgot_password():
    """Send password reset email"""
    try:
        data = request.get_json()
        email = data.get('email')
        
        if not email:
            return jsonify({'success': False, 'message': 'Email is required'}), 400
        
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Check if email exists
        user_result = db.execute(text("""
            SELECT user_id, email, first_name FROM users 
            WHERE email = :email AND is_active = true
        """), {"email": email}).fetchone()
        
        db.close()
        
        if user_result:
            # Generate reset token
            reset_token = secrets.token_urlsafe(32)
            
            # Store token in session for now (in production, use database with expiry)
            session[f'reset_token_{reset_token}'] = {
                'email': email,
                'user_id': user_result.user_id,
                'expires': datetime.now() + timedelta(hours=24)
            }
            
            # Send password reset email
            reset_url = f"{request.url_root}forgot-password?token={reset_token}"
            email_service.send_password_reset_email(
                to_email=email,
                first_name=user_result.first_name or 'User',
                reset_url=reset_url,
                expiry_hours=24
            )
        
        # Always return success message for security (don't reveal if email exists)
        return jsonify({'success': True, 'message': 'If an account with that email exists, we have sent you a password reset link.'})
        
    except Exception as e:
        print(f"Forgot password API error: {e}")
        return jsonify({'success': False, 'message': 'Failed to send reset email'}), 500

@app.route('/api/reset-password', methods=['POST'])
def api_reset_password():
    """Reset password with token"""
    try:
        data = request.get_json()
        token = data.get('token')
        password = data.get('password')
        confirm_password = data.get('confirm_password')
        
        if not all([token, password, confirm_password]):
            return jsonify({'success': False, 'message': 'All fields are required'}), 400
        
        if password != confirm_password:
            return jsonify({'success': False, 'message': 'Passwords do not match'}), 400
        
        # Check token
        token_data = session.get(f'reset_token_{token}')
        if not token_data:
            return jsonify({'success': False, 'message': 'Invalid or expired reset token'}), 400
        
        # Check if token is expired
        if datetime.now() > token_data['expires']:
            session.pop(f'reset_token_{token}', None)
            return jsonify({'success': False, 'message': 'Reset token has expired'}), 400
        
        # Hash new password
        from passlib.context import CryptContext
        pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
        password_hash = pwd_context.hash(password)
        
        # Update password in database
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        result = db.execute(text("""
            UPDATE users 
            SET password_hash = :password_hash, updated_at = CURRENT_TIMESTAMP
            WHERE user_id = :user_id AND is_active = true
        """), {
            "password_hash": password_hash,
            "user_id": token_data['user_id']
        })
        
        db.commit()
        db.close()
        
        # Clear the token
        session.pop(f'reset_token_{token}', None)
        
        return jsonify({'success': True, 'message': 'Password updated successfully!'})
        
    except Exception as e:
        print(f"Reset password API error: {e}")
        return jsonify({'success': False, 'message': 'Failed to reset password'}), 500

@app.route('/logout')
@login_required
def logout():
    """Admin logout"""
    logout_user()
    return redirect(url_for('login'))

@app.route('/users')
@login_required
def users():
    """Manage users"""
    # Get real users from database
    try:
        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()
        
        # Get all users with their roles
        users_result = db.execute(text("""
            SELECT u.user_id, u.email, u.first_name, u.last_name, 
                   ur.role_name, u.is_active, u.created_at,
                   u.is_email_verified, u.phone
            FROM users u
            LEFT JOIN user_roles ur ON u.role_id = ur.role_id
            ORDER BY u.created_at DESC
        """)).fetchall()
        
        users_data = []
        for user in users_result:
            users_data.append({
                'id': user.user_id,
                'email': user.email,
                'name': f"{user.first_name or ''} {user.last_name or ''}".strip(),
                'role': user.role_name or 'No Role',
                'status': 'Active' if user.is_active else 'Inactive',
                'created_at': user.created_at.strftime('%Y-%m-%d') if user.created_at else 'N/A',
                'phone': user.phone or 'N/A',
                'email_verified': user.is_email_verified
            })
        
        db.close()
        
    except Exception as e:
        flash(f'Error loading users: {str(e)}', 'error')
        users_data = []
    
    return render_template('users.html', users=users_data)

@app.route('/users/add', methods=['GET', 'POST'])
@login_required
def add_user():
    """Add new user"""
    if request.method == 'POST':
        try:
            from sqlalchemy import create_engine, text
            from sqlalchemy.orm import sessionmaker
            from passlib.context import CryptContext
            import os
            from werkzeug.utils import secure_filename
            
            # Password hashing context
            pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
            
            # Database connection
            DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
            engine = create_engine(DATABASE_URL)
            SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
            
            db = SessionLocal()
            
            # Get form data
            first_name = request.form.get('first_name')
            last_name = request.form.get('last_name')
            email = request.form.get('email')
            phone = request.form.get('phone')
            date_of_birth = request.form.get('date_of_birth') or None
            password = request.form.get('password')
            confirm_password = request.form.get('confirm_password')
            role_id = request.form.get('role_id')
            preferred_language_id = request.form.get('preferred_language_id') or None
            preferred_currency_id = request.form.get('preferred_currency_id') or None
            is_active = 'is_active' in request.form
            is_email_verified = 'is_email_verified' in request.form
            
            # Validation
            if not all([first_name, last_name, email, password, role_id]):
                flash('Please fill in all required fields', 'error')
                return redirect(url_for('add_user'))
            
            if password != confirm_password:
                flash('Passwords do not match', 'error')
                return redirect(url_for('add_user'))
            
            # Check if email already exists
            existing_user = db.execute(text(
                "SELECT user_id FROM users WHERE email = :email"
            ), {"email": email}).fetchone()
            
            if existing_user:
                flash('Email already exists', 'error')
                return redirect(url_for('add_user'))
            
            # Handle file upload
            profile_photo_path = None
            if 'profile_photo' in request.files:
                file = request.files['profile_photo']
                if file and file.filename != '':
                    filename = secure_filename(file.filename)
                    # Create uploads directory if it doesn't exist
                    upload_dir = os.path.join('static', 'uploads', 'profiles')
                    os.makedirs(upload_dir, exist_ok=True)
                    
                    # Save file with unique name
                    import uuid
                    file_ext = filename.rsplit('.', 1)[1].lower()
                    unique_filename = f"{uuid.uuid4().hex}.{file_ext}"
                    file_path = os.path.join(upload_dir, unique_filename)
                    file.save(file_path)
                    profile_photo_path = f"/static/uploads/profiles/{unique_filename}"
            
            # Hash password
            password_hash = pwd_context.hash(password)
            
            # Insert user
            result = db.execute(text("""
                INSERT INTO users (
                    email, password_hash, first_name, last_name, phone, 
                    date_of_birth, profile_photo_path, role_id, 
                    preferred_language_id, preferred_currency_id,
                    is_active, is_email_verified, created_at, updated_at
                ) VALUES (
                    :email, :password_hash, :first_name, :last_name, :phone,
                    :date_of_birth, :profile_photo_path, :role_id,
                    :preferred_language_id, :preferred_currency_id,
                    :is_active, :is_email_verified, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
                ) RETURNING user_id
            """), {
                "email": email,
                "password_hash": password_hash,
                "first_name": first_name,
                "last_name": last_name,
                "phone": phone,
                "date_of_birth": date_of_birth,
                "profile_photo_path": profile_photo_path,
                "role_id": int(role_id),
                "preferred_language_id": int(preferred_language_id) if preferred_language_id else None,
                "preferred_currency_id": int(preferred_currency_id) if preferred_currency_id else None,
                "is_active": is_active,
                "is_email_verified": is_email_verified
            })
            
            user_id = result.fetchone().user_id
            db.commit()
            db.close()
            
            flash(f'User "{first_name} {last_name}" created successfully!', 'success')
            return redirect(url_for('users'))
            
        except Exception as e:
            flash(f'Error creating user: {str(e)}', 'error')
            return redirect(url_for('add_user'))
    
    # GET request - show form
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Get roles
        roles_result = db.execute(text("SELECT role_id, role_name FROM user_roles ORDER BY role_name")).fetchall()
        roles = [{'role_id': r.role_id, 'role_name': r.role_name} for r in roles_result]
        
        # Get languages
        languages_result = db.execute(text("SELECT language_id, language_name FROM languages WHERE is_active = true ORDER BY language_name")).fetchall()
        languages = [{'language_id': l.language_id, 'language_name': l.language_name} for l in languages_result]
        
        # Get currencies
        currencies_result = db.execute(text("SELECT currency_id, currency_name, currency_symbol FROM currencies WHERE is_active = true ORDER BY currency_name")).fetchall()
        currencies = [{'currency_id': c.currency_id, 'currency_name': c.currency_name, 'currency_symbol': c.currency_symbol} for c in currencies_result]
        
        db.close()
        
    except Exception as e:
        flash(f'Error loading form data: {str(e)}', 'error')
        roles = []
        languages = []
        currencies = []
    
    return render_template('add_user.html', roles=roles, languages=languages, currencies=currencies)


@app.route('/api/v1/registration/complete', methods=['POST'])
def api_complete_registration_v2():
    """Complete user registration"""
    try:
        data = request.get_json()
        user_id = data.get('user_id')
        password = data.get('password')
        confirm_password = data.get('confirm_password')
        
        if not user_id or not password or not confirm_password:
            return jsonify({'success': False, 'message': 'All fields are required'}), 400
        
        if password != confirm_password:
            return jsonify({'success': False, 'message': 'Passwords do not match'}), 400
        
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        from passlib.context import CryptContext
        
        # Password hashing context
        pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
        
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Hash the password
        password_hash = pwd_context.hash(password)
        
        # Update user's password, country_id and set is_email_verified to True
        db.execute(text("""
            UPDATE users
            SET password_hash = :password_hash,
                country_id = :country_id,
                is_email_verified = TRUE
            WHERE user_id = :user_id
        """), {
            "password_hash": password_hash,
            "country_id": data.get('country_id'),
            "user_id": user_id
        })
        
        db.commit()
        db.close()
        
        return jsonify({
            'success': True, 
            'message': 'Registration completed successfully!',
            'redirect_url': url_for('index')
        })
        
    except Exception as e:
        print(f"Complete registration error: {e}")
        return jsonify({'success': False, 'message': 'Failed to complete registration'}), 500


@app.route('/api/v1/registration/countries')
def api_get_countries():
    """Get list of countries for registration form"""
    try:
        from companies_service import CompanyService
        with CompanyService() as service:
            countries = service.get_countries()
            return jsonify(countries)
    except Exception as e:
        print(f"Error getting countries: {e}")
        return jsonify([]), 500


@app.route('/api/v1/registration/languages')
def api_get_languages():
    """Get list of languages for registration form"""
    try:
        # Get active languages from database
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        connection = engine.connect()
        
        result = connection.execute(text("""
            SELECT language_id, language_name, language_code
            FROM languages
            WHERE is_active = TRUE
            ORDER BY language_name
        """))
        
        languages = []
        for row in result:
            languages.append({
                'language_id': row.language_id,
                'language_name': row.language_name,
                'language_code': row.language_code
            })
        
        connection.close()
        return jsonify(languages)
    except Exception as e:
        print(f"Error getting languages: {e}")
        return jsonify([]), 500


# API Routes for Forgot Password Process
@app.route('/api/forgot-password-alt', methods=['POST'])
def api_forgot_password_alt():
    """Send password reset email"""
    try:
        data = request.get_json()
        email = data.get('email')
        
        if not email:
            return jsonify({'success': False, 'message': 'Email is required'}), 400
        
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        from passlib.context import CryptContext
        import os
        from werkzeug.utils import secure_filename
                
        # Password hashing context
        pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
        
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Check if user exists
        user = db.execute(text("SELECT * FROM users WHERE email = :email"), {"email": email}).fetchone()
        if not user:
            return jsonify({'success': False, 'message': 'User not found'}), 404
        
        # Generate password reset token
        token = os.urandom(24).hex()
        db.execute(text("""
            UPDATE users
            SET password_reset_token = :token,
                password_reset_token_expires = CURRENT_TIMESTAMP + INTERVAL '1 hour'
            WHERE user_id = :user_id
        """), {
            "token": token,
            "user_id": user.user_id
        })
        
        db.commit()
        db.close()
        
        # Send password reset email
        from flask_mail import Message
        from app import mail
        
        msg = Message(
            "Password Reset Request",
            sender="noreply@example.com",
            recipients=[email]
        )
        msg.body = f"""
        To reset your password, visit the following link:
        {url_for('reset_password', token=token, _external=True)}
        
        If you did not make this request, simply ignore this email.
        """
        mail.send(msg)
        
        return jsonify({'success': True, 'message': 'Password reset email sent'})
        
    except Exception as e:
        print(f"Forgot password error: {e}")
        return jsonify({'success': False, 'message': 'Failed to send password reset email'}), 500


@app.route('/reset-password/<token>', methods=['GET', 'POST'])
def reset_password(token):
    """Reset user password"""
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        from passlib.context import CryptContext
        import os
        from werkzeug.utils import secure_filename
                
        # Password hashing context
        pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
        
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        if request.method == 'POST':
            # Get form data
            password = request.form.get('password')
            confirm_password = request.form.get('confirm_password')
            
            if not password or not confirm_password:
                flash('All fields are required', 'error')
                return redirect(url_for('reset_password', token=token))
            
            if password != confirm_password:
                flash('Passwords do not match', 'error')
                return redirect(url_for('reset_password', token=token))
            
            # Hash the password
            password_hash = pwd_context.hash(password)
            
            # Update user's password and clear password reset token
            db.execute(text("""
                UPDATE users
                SET password_hash = :password_hash,
                    password_reset_token = NULL,
                    password_reset_token_expires = NULL
                WHERE password_reset_token = :token
            """), {
                "password_hash": password_hash,
                "token": token
            })
            
            db.commit()
            db.close()
            
            flash('Password reset successfully!', 'success')
            return redirect(url_for('login'))
        
        # GET request - show form
        # Check if token is valid
        user = db.execute(text("""
            SELECT *
            FROM users
            WHERE password_reset_token = :token
            AND password_reset_token_expires > CURRENT_TIMESTAMP
        """), {"token": token}).fetchone()
        if not user:
            flash('Invalid or expired token', 'error')
            return redirect(url_for('login'))
        
        db.close()
        
        return render_template('reset_password.html', token=token)
        
    except Exception as e:
        flash(f'Error resetting password: {str(e)}', 'error')
        return redirect(url_for('login'))


@app.route('/users/edit/<int:user_id>', methods=['GET', 'POST'])
@login_required
def edit_user(user_id):
    """Edit user"""
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        from passlib.context import CryptContext
        import os
        from werkzeug.utils import secure_filename
                
        # Password hashing context
        pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
        
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        if request.method == 'POST':
            # Get form data
            first_name = request.form.get('first_name')
            last_name = request.form.get('last_name')
            email = request.form.get('email')
            phone = request.form.get('phone')
            date_of_birth = request.form.get('date_of_birth') or None
            password = request.form.get('password')
            confirm_password = request.form.get('confirm_password')
            role_id = request.form.get('role_id')
            preferred_language_id = request.form.get('preferred_language_id') or None
            preferred_currency_id = request.form.get('preferred_currency_id') or None
            is_active = 'is_active' in request.form
            is_email_verified = 'is_email_verified' in request.form
            
            # Validation
            if not all([first_name, last_name, email, role_id]):
                flash('Please fill in all required fields', 'error')
                return redirect(url_for('edit_user', user_id=user_id))
            
            if password and password != confirm_password:
                flash('Passwords do not match', 'error')
                return redirect(url_for('edit_user', user_id=user_id))
            
            # Check if email already exists (excluding current user)
            existing_user = db.execute(text(
                "SELECT user_id FROM users WHERE email = :email AND user_id != :user_id"
            ), {"email": email, "user_id": user_id}).fetchone()
            
            if existing_user:
                flash('Email already exists', 'error')
                return redirect(url_for('edit_user', user_id=user_id))
            
            # Handle file upload
            profile_photo_path = None
            if 'profile_photo' in request.files:
                file = request.files['profile_photo']
                if file and file.filename != '':
                    filename = secure_filename(file.filename)
                    upload_dir = os.path.join('static', 'uploads', 'profiles')
                    os.makedirs(upload_dir, exist_ok=True)
                    
                    import uuid
                    file_ext = filename.rsplit('.', 1)[1].lower()
                    unique_filename = f"{uuid.uuid4().hex}.{file_ext}"
                    file_path = os.path.join(upload_dir, unique_filename)
                    file.save(file_path)
                    profile_photo_path = f"/static/uploads/profiles/{unique_filename}"
            
            # Build update query
            update_fields = [
                "first_name = :first_name",
                "last_name = :last_name",
                "email = :email",
                "phone = :phone",
                "date_of_birth = :date_of_birth",
                "role_id = :role_id",
                "preferred_language_id = :preferred_language_id",
                "preferred_currency_id = :preferred_currency_id",
                "is_active = :is_active",
                "is_email_verified = :is_email_verified",
                "updated_at = CURRENT_TIMESTAMP"
            ]
            
            update_params = {
                "user_id": user_id,
                "first_name": first_name,
                "last_name": last_name,
                "email": email,
                "phone": phone,
                "date_of_birth": date_of_birth,
                "role_id": int(role_id),
                "preferred_language_id": int(preferred_language_id) if preferred_language_id else None,
                "preferred_currency_id": int(preferred_currency_id) if preferred_currency_id else None,
                "is_active": is_active,
                "is_email_verified": is_email_verified
            }
            
            # Add password update if provided
            if password:
                update_fields.append("password_hash = :password_hash")
                update_params["password_hash"] = pwd_context.hash(password)
            
            # Add profile photo update if provided
            if profile_photo_path:
                update_fields.append("profile_photo_path = :profile_photo_path")
                update_params["profile_photo_path"] = profile_photo_path
            
            # Execute update
            update_query = f"UPDATE users SET {', '.join(update_fields)} WHERE user_id = :user_id"
            db.execute(text(update_query), update_params)
            db.commit()
            
            flash(f'User "{first_name} {last_name}" updated successfully!', 'success')
            return redirect(url_for('users'))
        
        # GET request - show form with user data
        user_result = db.execute(text("""
            SELECT u.user_id, u.email, u.first_name, u.last_name, u.phone,
                   u.date_of_birth, u.profile_photo_path, u.role_id, 
                   u.preferred_language_id, u.preferred_currency_id,
                   u.is_active, u.is_email_verified, u.created_at, 
                   u.updated_at, u.last_login, ur.role_name
            FROM users u
            LEFT JOIN user_roles ur ON u.role_id = ur.role_id
            WHERE u.user_id = :user_id
        """), {"user_id": user_id}).fetchone()
        
        if not user_result:
            flash('User not found', 'error')
            return redirect(url_for('users'))
        
        user = {
            'user_id': user_result.user_id,
            'email': user_result.email,
            'first_name': user_result.first_name,
            'last_name': user_result.last_name,
            'phone': user_result.phone,
            'date_of_birth': user_result.date_of_birth,
            'profile_photo_path': user_result.profile_photo_path,
            'role_id': user_result.role_id,
            'role_name': user_result.role_name,
            'preferred_language_id': user_result.preferred_language_id,
            'preferred_currency_id': user_result.preferred_currency_id,
            'is_active': user_result.is_active,
            'is_email_verified': user_result.is_email_verified,
            'created_at': user_result.created_at,
            'updated_at': user_result.updated_at,
            'last_login': user_result.last_login
        }
        
        # Get roles
        roles_result = db.execute(text("SELECT role_id, role_name FROM user_roles ORDER BY role_name")).fetchall()
        roles = [{'role_id': r.role_id, 'role_name': r.role_name} for r in roles_result]
        
        # Get languages
        languages_result = db.execute(text("SELECT language_id, language_name FROM languages WHERE is_active = true ORDER BY language_name")).fetchall()
        languages = [{'language_id': l.language_id, 'language_name': l.language_name} for l in languages_result]
        
        # Get currencies
        currencies_result = db.execute(text("SELECT currency_id, currency_name, currency_symbol FROM currencies WHERE is_active = true ORDER BY currency_name")).fetchall()
        currencies = [{'currency_id': c.currency_id, 'currency_name': c.currency_name, 'currency_symbol': c.currency_symbol} for c in currencies_result]
        
        db.close()
        
        return render_template('edit_user.html', user=user, roles=roles, languages=languages, currencies=currencies)
        
    except Exception as e:
        flash(f'Error loading user: {str(e)}', 'error')
        return redirect(url_for('users'))

@app.route('/users/delete/<int:user_id>')
@login_required
def delete_user(user_id):
    """Delete user"""
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Get user info before deletion
        user_result = db.execute(text(
            "SELECT first_name, last_name FROM users WHERE user_id = :user_id"
        ), {"user_id": user_id}).fetchone()
        
        if not user_result:
            flash('User not found', 'error')
            return redirect(url_for('users'))
        
        user_name = f"{user_result.first_name} {user_result.last_name}"
        
        # Delete user (cascade should handle related records)
        db.execute(text("DELETE FROM users WHERE user_id = :user_id"), {"user_id": user_id})
        db.commit()
        db.close()
        
        flash(f'User "{user_name}" deleted successfully!', 'success')
        
    except Exception as e:
        flash(f'Error deleting user: {str(e)}', 'error')
    
    return redirect(url_for('users'))

@app.route('/users/reset-password/<int:user_id>', methods=['POST'])
@login_required
def reset_user_password(user_id):
    """Reset user password"""
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        from passlib.context import CryptContext
        import secrets
        import string
        
        # Password hashing context
        pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
        
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Generate temporary password
        temp_password = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(12))
        password_hash = pwd_context.hash(temp_password)
        
        # Update user password
        db.execute(text(
            "UPDATE users SET password_hash = :password_hash, updated_at = CURRENT_TIMESTAMP WHERE user_id = :user_id"
        ), {"password_hash": password_hash, "user_id": user_id})
        
        db.commit()
        db.close()
        
        # In a real application, you would send this password via email
        # For now, we'll just return it in the response
        return {'success': True, 'message': f'Password reset successful. Temporary password: {temp_password}'}
        
    except Exception as e:
        return {'success': False, 'message': str(e)}



@app.route('/beach/<beach_id>')
def beach_detail(beach_id):
    """Beach detail page"""
    try:
        print(f"Beach detail requested for ID: {beach_id}")  # Debug log
        from sqlalchemy import create_engine, text
        
        # Database connection
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        
        with engine.connect() as db:
            # Apply migration for new columns if they don't exist
            try:
                db.execute(text("""
                    SELECT contact_phone, starttime, endtime, opendays
                    FROM beach_places 
                    LIMIT 1
                """))
            except Exception:
                # Columns don't exist, add them
                try:
                    db.execute(text("""
                        ALTER TABLE beach_places 
                        ADD COLUMN IF NOT EXISTS contact_phone VARCHAR(50),
                        ADD COLUMN IF NOT EXISTS starttime TIME,
                        ADD COLUMN IF NOT EXISTS endtime TIME,
                        ADD COLUMN IF NOT EXISTS opendays VARCHAR(7) DEFAULT '1234567'
                    """))
                    db.commit()
                    print("New columns added successfully")
                except Exception as e:
                    print(f"Error adding columns: {e}")
                    
            # Get beach details with company, country information and minimum price from terrains
            beach_result = db.execute(text("""
                SELECT bp.*, c.company_name, co.country_name, bt.terrain_name,
                       MIN(CASE WHEN bpt.min_price > 0 THEN bpt.min_price ELSE NULL END) as min_price
                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
                LEFT JOIN beach_place_terrains bpt ON bp.beach_place_id = bpt.beach_place_id
                WHERE bp.beach_place_id = :beach_id AND bp.enable_beach = true
                GROUP BY bp.beach_place_id, c.company_name, co.country_name, bt.terrain_name
            """), {"beach_id": beach_id}).fetchone()
            
            if not beach_result:
                flash('Beach not found or not available', 'error')
                return redirect(url_for('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()
            
            # Get beach reviews (if reviews table exists)
            reviews_result = []
            average_rating = 0
            try:
                reviews_result = db.execute(text("""
                    SELECT r.rating, r.comment, r.created_at, u.first_name as user_name
                    FROM reviews r
                    LEFT JOIN users u ON r.user_id = u.user_id
                    WHERE r.beach_place_id = :beach_id
                    ORDER BY r.created_at DESC
                    LIMIT 10
                """), {"beach_id": beach_id}).fetchall()
                
                if reviews_result:
                    avg_result = db.execute(text("""
                        SELECT AVG(rating) as avg_rating
                        FROM reviews
                        WHERE beach_place_id = :beach_id
                    """), {"beach_id": beach_id}).fetchone()
                    average_rating = float(avg_result.avg_rating) if avg_result.avg_rating else 0
            except:
                # Reviews table might not exist
                pass
            
            # Convert beach result to dict
            beach = {
                'beach_place_id': beach_result.beach_place_id,
                'name': beach_result.beach_name,
                'beach_information': beach_result.beach_information,
                'city': beach_result.city,
                'address': beach_result.address,
                'latitude': beach_result.latitude,
                'longitude': beach_result.longitude,
                'max_seats': beach_result.max_seats,
                'company_name': beach_result.company_name,
                'country_name': beach_result.country_name,
                'terrain_name': beach_result.terrain_name,
                # Add new contact and schedule fields
                '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'),
                # Add minimum price from terrains
                'min_price': beach_result.min_price if hasattr(beach_result, 'min_price') and beach_result.min_price else None,
                # Add all the service/amenity fields
                'has_sea': beach_result.has_sea,
                'has_umbrella': beach_result.has_umbrella,
                'has_showers': beach_result.has_showers,
                'has_lockers': beach_result.has_lockers,
                'has_market': beach_result.has_market,
                'has_restaurant': beach_result.has_restaurant,
                'has_swimming_pool': beach_result.has_swimming_pool,
                'has_parking': beach_result.has_parking,
                'has_toilets': beach_result.has_toilets,
                'has_free_wifi': beach_result.has_free_wifi,
                'has_music': beach_result.has_music,
                'has_safety_box': beach_result.has_safety_box,
                'has_access_wheelchair': beach_result.has_access_wheelchair,
                'has_lockers_for_baby': beach_result.has_lockers_for_baby,
                'has_beach_volley': beach_result.has_beach_volley,
                'has_tennis': beach_result.has_tennis,
                'has_spa': beach_result.has_spa,
                'has_medical': beach_result.has_medical,
                'has_lifeguard': beach_result.has_lifeguard,
                'pet_allow': beach_result.pet_allow,
                'sea_location': beach_result.sea_location,
                'background_photo': beach_result.background_photo,
                'photos': [{'path': photo.photo_path, 'is_primary': photo.is_primary} for photo in photos_result],
                'reviews': [{
                    'rating': review.rating,
                    'comment': review.comment,
                    'created_at': review.created_at,
                    'user_name': review.user_name
                } for review in reviews_result],
                'average_rating': average_rating
            }
            
            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:
        print(f'Error loading beach details for ID {beach_id}: {str(e)}')  # Debug log
        flash(f'Error loading beach details: {str(e)}', 'error')
        return redirect(url_for('beaches_grid'))

@app.route('/adventure/<adventure_id>')
def adventure_detail(adventure_id):
    """Adventure detail page for users"""
    return render_template('adventure-detail.html', 
                         adventure_id=adventure_id,
                         google_maps_key=os.getenv('GOOGLE_MAPS_API_KEY', 'your-google-maps-api-key'))

@app.route('/market/<market_id>')
def market_detail(market_id):
    """Market detail page for users"""
    return render_template('market-detail.html', 
                         market_id=market_id,
                         google_maps_key=os.getenv('GOOGLE_MAPS_API_KEY', 'your-google-maps-api-key'))

@app.route('/beaches/add', methods=['GET', 'POST'])
@login_required
def add_beach_place():
    """Add new beach place"""
    try:
        # Database connection
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        
        with engine.connect() as db:
            # Get companies and countries for the form
            companies = db.execute(text("""
                SELECT company_id, company_name 
                FROM companies 
                WHERE company_status = 'approved'
                ORDER BY company_name
            """)).fetchall()
            
            countries = db.execute(text("""
                SELECT country_id, country_name 
                FROM countries 
                ORDER BY country_name
            """)).fetchall()
            
            terrain_types = db.execute(text("""
                SELECT terrain_type_id, terrain_name 
                FROM beach_terrain_types 
                ORDER BY terrain_name
            """)).fetchall()
        
        if request.method == 'POST':
            # Collect form data
            beach_data = {
                'beach_name': request.form.get('beach_name', '').strip(),
                'company_id': request.form.get('company_id', '').strip() or None,  # UUID as string
                'country_id': request.form.get('country_id', type=int),
                'city': request.form.get('city', '').strip(),
                'address': request.form.get('address', '').strip(),
                'terrain_type_id': request.form.get('terrain_type_id', type=int),
                'max_seats': request.form.get('max_seats', type=int),
                'top_rows': request.form.get('top_rows', type=int) or 1,
                'top_seats': request.form.get('top_seats', type=int) or 1,
                'beach_information': request.form.get('beach_information', '').strip(),
                'enable_beach': request.form.get('enable_beach') == 'on',
                'latitude': float(request.form.get('latitude', 37.9755)),
                'longitude': float(request.form.get('longitude', 23.7348)),
                'mask': request.form.get('mask', '[]').strip() or '[]',
                'disable_today': request.form.get('disable_today') == 'on',
                # Facility fields
                'is_double_seat': request.form.get('is_double_seat') == 'on',
                'has_umbrella': request.form.get('has_umbrella') == 'on',
                'has_showers': request.form.get('has_showers') == 'on',
                'has_lockers': request.form.get('has_lockers') == 'on',
                'has_market': request.form.get('has_market') == 'on',
                'has_restaurant': request.form.get('has_restaurant') == 'on',
                'has_swimming_pool': request.form.get('has_swimming_pool') == 'on',
                'has_parking': request.form.get('has_parking') == 'on',
                'has_toilets': request.form.get('has_toilets') == 'on',
                'has_free_wifi': request.form.get('has_free_wifi') == 'on',
                'has_music': request.form.get('has_music') == 'on',
                'has_safety_box': request.form.get('has_safety_box') == 'on',
                'has_access_wheelchair': request.form.get('has_access_wheelchair') == 'on',
                'has_lockers_for_baby': request.form.get('has_lockers_for_baby') == 'on',
                'has_beach_volley': request.form.get('has_beach_volley') == 'on',
                'has_tennis': request.form.get('has_tennis') == 'on',
                'has_spa': request.form.get('has_spa') == 'on',
                'has_medical': request.form.get('has_medical') == 'on',
                'has_lifeguard': request.form.get('has_lifeguard') == 'on',
                'pet_allow': request.form.get('pet_allow') == 'on',
                # Beach design configuration fields
                'has_sea': request.form.get('has_sea') == 'on',
                'sea_location': request.form.get('sea_location', ''),
                'background_photo': request.form.get('background_photo', '').strip(),
                # New contact and schedule fields
                'contact_phone': request.form.get('contact_phone', '').strip() or None,
                'starttime': request.form.get('starttime') or None,
                'endtime': request.form.get('endtime') or None,
                'opendays': request.form.get('opendays', '1234567')
            }
            
            # Validate required fields
            if not beach_data['beach_name']:
                flash('Beach name is required', 'error')
            elif not beach_data['company_id']:
                flash('Company is required', 'error')
            elif not beach_data['country_id']:
                flash('Country is required', 'error')
            elif not beach_data['city']:
                flash('City is required', 'error')
            elif not beach_data['max_seats'] or beach_data['max_seats'] <= 0:
                flash('Valid number of seats is required', 'error')
            else:
                # Insert the beach place
                result = db.execute(text("""
                    INSERT INTO beach_places (
                        beach_name, company_id, country_id, city, address, 
                        terrain_type_id, max_seats, top_rows, top_seats,
                        beach_information, enable_beach, latitude, longitude,
                        mask, disable_today,
                        is_double_seat, has_umbrella, has_showers, has_lockers,
                        has_market, has_restaurant, has_swimming_pool, has_parking,
                        has_toilets, has_free_wifi, has_music, has_safety_box,
                        has_access_wheelchair, has_lockers_for_baby, has_beach_volley,
                        has_tennis, has_spa, has_medical, has_lifeguard, pet_allow,
                        has_sea, sea_location, background_photo,
                        contact_phone, starttime, endtime, opendays,
                        created_at, updated_at
                    ) VALUES (
                        :beach_name, :company_id, :country_id, :city, :address,
                        :terrain_type_id, :max_seats, :top_rows, :top_seats,
                        :beach_information, :enable_beach, :latitude, :longitude,
                        :mask, :disable_today,
                        :is_double_seat, :has_umbrella, :has_showers, :has_lockers,
                        :has_market, :has_restaurant, :has_swimming_pool, :has_parking,
                        :has_toilets, :has_free_wifi, :has_music, :has_safety_box,
                        :has_access_wheelchair, :has_lockers_for_baby, :has_beach_volley,
                        :has_tennis, :has_spa, :has_medical, :has_lifeguard, :pet_allow,
                        :has_sea, :sea_location, :background_photo,
                        :contact_phone, :starttime, :endtime, :opendays,
                        NOW(), NOW()
                    ) RETURNING beach_place_id
                """), beach_data)
                
                beach_id = result.fetchone()[0]
                
                # Handle photo uploads
                if 'beach_photos' in request.files:
                    photos = request.files.getlist('beach_photos')
                    for i, photo in enumerate(photos):
                        if photo.filename != '':
                            try:
                                # Save photo and add to database
                                filename = secure_filename(photo.filename)
                                import uuid
                                file_ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else 'jpg'
                                unique_filename = f"{uuid.uuid4().hex}.{file_ext}"
                                
                                # Create upload directory with absolute path
                                backend_dir = os.path.dirname(os.path.abspath(__file__))
                                upload_dir = os.path.join(backend_dir, 'static', 'uploads', 'beaches')
                                
                                # Ensure directory exists
                                os.makedirs(upload_dir, exist_ok=True)
                                print(f"Upload directory: {upload_dir}")
                                
                                # Save file with absolute path
                                file_path = os.path.join(upload_dir, unique_filename)
                                print(f"Saving file to: {file_path}")
                                
                                # Save the file
                                photo.save(file_path)
                                
                                # Verify file was saved
                                if os.path.exists(file_path):
                                    file_size = os.path.getsize(file_path)
                                    print(f"File saved successfully: {file_path} ({file_size} bytes)")
                                else:
                                    raise Exception(f"File was not saved: {file_path}")
                                
                                # For new beach, first photo is always primary
                                is_primary = (i == 0)
                                
                                # Add to database
                                db.execute(text("""
                                    INSERT INTO beach_places_photos (
                                        beach_place_id, photo_path, photo_primary, sort_order
                                    ) VALUES (
                                        :beach_id, :photo_path, :is_primary, :sort_order
                                    )
                                """), {
                                    'beach_id': beach_id,
                                    'photo_path': f"/static/uploads/beaches/{unique_filename}",
                                    'is_primary': is_primary,
                                    'sort_order': i
                                })
                            except Exception as photo_error:
                                print(f"Error uploading photo in add mode: {photo_error}")
                
                db.commit()
                
                if beach_id:
                    flash('Beach place created successfully!', 'success')
                    return redirect(url_for('beaches'))
                else:
                    flash('Error creating beach place', 'error')
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        companies = []
        countries = []
        terrain_types = []
    
    return render_template('beach_form.html', 
                         companies=companies, 
                         countries=countries,
                         terrain_types=terrain_types,
                         beach=None, 
                         action='add',
                         google_maps_key=os.getenv('GOOGLE_MAPS_API_KEY', 'your-google-maps-api-key'))

@app.route('/beaches/<beach_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_beach_place(beach_id):
    """Edit existing beach place"""
    try:
        # Database connection
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        
        with engine.connect() as db:
            # Get the beach place
            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
            """), {"beach_id": beach_id}).fetchone()
            
            if not beach_result:
                flash('Beach place not found', 'error')
                return redirect(url_for('beaches'))
            
            # Get beach photos
            beach_photos = []
            try:
                photos_result = db.execute(text("""
                    SELECT photo_id, photo_path, photo_primary as is_primary, sort_order
                    FROM beach_places_photos 
                    WHERE beach_place_id = :beach_id
                    ORDER BY photo_primary DESC, sort_order ASC
                """), {"beach_id": beach_id}).fetchall()
                
                for photo in photos_result:
                    beach_photos.append({
                        'photo_id': photo.photo_id,
                        'filename': photo.photo_path.split('/')[-1],
                        'photo_path': photo.photo_path,
                        'is_primary': photo.is_primary,
                        'sort_order': photo.sort_order
                    })
            except Exception as photo_error:
                print(f"Error retrieving beach photos: {photo_error}")
                beach_photos = []
            
            # Add photos to beach_result for template use
            beach_result_with_photos = dict(beach_result._mapping) if hasattr(beach_result, '_mapping') else dict(beach_result)
            beach_result_with_photos['photos'] = beach_photos
            
            # Get companies, countries, and terrain types for the form
            companies = db.execute(text("""
                SELECT company_id, company_name 
                FROM companies 
                WHERE company_status = 'approved'
                ORDER BY company_name
            """)).fetchall()
            
            countries = db.execute(text("""
                SELECT country_id, country_name 
                FROM countries 
                ORDER BY country_name
            """)).fetchall()
            
            terrain_types = db.execute(text("""
                SELECT terrain_type_id, terrain_name 
                FROM beach_terrain_types 
                ORDER BY terrain_name
            """)).fetchall()
            
            if request.method == 'POST':
                # Collect form data
                beach_data = {
                    'beach_name': request.form.get('beach_name', '').strip(),
                    'company_id': request.form.get('company_id', '').strip() or None,  # UUID as string
                    'country_id': request.form.get('country_id', type=int),
                    'city': request.form.get('city', '').strip(),
                    'address': request.form.get('address', '').strip(),
                    'terrain_type_id': request.form.get('terrain_type_id', type=int),
                    'max_seats': request.form.get('max_seats', type=int),
                    'top_rows': request.form.get('top_rows', type=int) or 1,
                    'top_seats': request.form.get('top_seats', type=int) or 1,
                    'beach_information': request.form.get('beach_information', '').strip(),
                    'enable_beach': request.form.get('enable_beach') == 'on',
                    'latitude': float(request.form.get('latitude', 37.9755)),
                    'longitude': float(request.form.get('longitude', 23.7348)),
                    'mask': request.form.get('mask', '[]').strip() or '[]',
                    'disable_today': request.form.get('disable_today') == 'on',
                    # Facility fields
                    'is_double_seat': request.form.get('is_double_seat') == 'on',
                    'has_umbrella': request.form.get('has_umbrella') == 'on',
                    'has_showers': request.form.get('has_showers') == 'on',
                    'has_lockers': request.form.get('has_lockers') == 'on',
                    'has_market': request.form.get('has_market') == 'on',
                    'has_restaurant': request.form.get('has_restaurant') == 'on',
                    'has_swimming_pool': request.form.get('has_swimming_pool') == 'on',
                    'has_parking': request.form.get('has_parking') == 'on',
                    'has_toilets': request.form.get('has_toilets') == 'on',
                    'has_free_wifi': request.form.get('has_free_wifi') == 'on',
                    'has_music': request.form.get('has_music') == 'on',
                    'has_safety_box': request.form.get('has_safety_box') == 'on',
                    'has_access_wheelchair': request.form.get('has_access_wheelchair') == 'on',
                    'has_lockers_for_baby': request.form.get('has_lockers_for_baby') == 'on',
                    'has_beach_volley': request.form.get('has_beach_volley') == 'on',
                    'has_tennis': request.form.get('has_tennis') == 'on',
                    'has_spa': request.form.get('has_spa') == 'on',
                    'has_medical': request.form.get('has_medical') == 'on',
                    'has_lifeguard': request.form.get('has_lifeguard') == 'on',
                    'pet_allow': request.form.get('pet_allow') == 'on',
                    # Beach design configuration fields
                    'has_sea': request.form.get('has_sea') == 'on',
                    'sea_location': request.form.get('sea_location', ''),
                    'background_photo': request.form.get('background_photo', '').strip()
                }
                
                # Validate required fields
                if not beach_data['beach_name']:
                    flash('Beach name is required', 'error')
                elif not beach_data['company_id']:
                    flash('Company is required', 'error')
                elif not beach_data['country_id']:
                    flash('Country is required', 'error')
                elif not beach_data['city']:
                    flash('City is required', 'error')
                elif not beach_data['max_seats'] or beach_data['max_seats'] <= 0:
                    flash('Valid number of seats is required', 'error')
                else:
                    # Update the beach place
                    db.execute(text("""
                        UPDATE beach_places SET
                        beach_name = :beach_name,
                        company_id = :company_id,
                        country_id = :country_id,
                        city = :city,
                        address = :address,
                        terrain_type_id = :terrain_type_id,
                        max_seats = :max_seats,
                        top_rows = :top_rows,
                        top_seats = :top_seats,
                        beach_information = :beach_information,
                        enable_beach = :enable_beach,
                        latitude = :latitude,
                        longitude = :longitude,
                        mask = :mask,
                        disable_today = :disable_today,
                        is_double_seat = :is_double_seat,
                        has_umbrella = :has_umbrella,
                        has_showers = :has_showers,
                        has_lockers = :has_lockers,
                        has_market = :has_market,
                        has_restaurant = :has_restaurant,
                        has_swimming_pool = :has_swimming_pool,
                        has_parking = :has_parking,
                        has_toilets = :has_toilets,
                        has_free_wifi = :has_free_wifi,
                        has_music = :has_music,
                        has_safety_box = :has_safety_box,
                        has_access_wheelchair = :has_access_wheelchair,
                        has_lockers_for_baby = :has_lockers_for_baby,
                        has_beach_volley = :has_beach_volley,
                        has_tennis = :has_tennis,
                        has_spa = :has_spa,
                        has_medical = :has_medical,
                        has_lifeguard = :has_lifeguard,
                        pet_allow = :pet_allow,
                        has_sea = :has_sea,
                        sea_location = :sea_location,
                        background_photo = :background_photo,
                        contact_phone = :contact_phone,
                        starttime = :starttime,
                        endtime = :endtime,
                        opendays = :opendays,
                        updated_at = NOW()
                    WHERE beach_place_id = :beach_id
                    """), {**beach_data, 'beach_id': beach_id})
                    
                    db.commit()
                    
                    # Handle photo uploads for edit mode
                if 'beach_photos' in request.files:
                    photos = request.files.getlist('beach_photos')
                    
                    # Check if there's already a primary photo for this beach
                    existing_primary = db.execute(text("""
                        SELECT COUNT(*) as count FROM beach_places_photos 
                        WHERE beach_place_id = :beach_id AND photo_primary = true
                    """), {'beach_id': beach_id}).fetchone()
                    
                    has_primary = existing_primary.count > 0
                    
                    # Get the next sort order
                    max_sort = db.execute(text("""
                        SELECT COALESCE(MAX(sort_order), -1) as max_sort 
                        FROM beach_places_photos 
                        WHERE beach_place_id = :beach_id
                    """), {'beach_id': beach_id}).fetchone()
                    
                    next_sort_order = max_sort.max_sort + 1
                    
                    for i, photo in enumerate(photos):
                        if photo.filename != '':
                            try:
                                # Save photo and add to database
                                filename = secure_filename(photo.filename)
                                import uuid
                                file_ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else 'jpg'
                                unique_filename = f"{uuid.uuid4().hex}.{file_ext}"
                                
                                # Create upload directory with absolute path
                                backend_dir = os.path.dirname(os.path.abspath(__file__))
                                upload_dir = os.path.join(backend_dir, 'static', 'uploads', 'beaches')
                                
                                # Ensure directory exists
                                os.makedirs(upload_dir, exist_ok=True)
                                print(f"Upload directory: {upload_dir}")
                                
                                # Save file with absolute path
                                file_path = os.path.join(upload_dir, unique_filename)
                                print(f"Saving file to: {file_path}")
                                
                                # Save the file
                                photo.save(file_path)
                                
                                # Verify file was saved
                                if os.path.exists(file_path):
                                    file_size = os.path.getsize(file_path)
                                    print(f"File saved successfully: {file_path} ({file_size} bytes)")
                                else:
                                    raise Exception(f"File was not saved: {file_path}")
                                
                                # Only make first photo primary if no existing primary photo
                                is_primary = (i == 0 and not has_primary)
                                
                                # Add to database
                                db.execute(text("""
                                    INSERT INTO beach_places_photos (
                                        beach_place_id, photo_path, photo_primary, sort_order
                                    ) VALUES (
                                        :beach_id, :photo_path, :is_primary, :sort_order
                                    )
                                """), {
                                    'beach_id': beach_id,
                                    'photo_path': f"/static/uploads/beaches/{unique_filename}",
                                    'is_primary': is_primary,
                                    'sort_order': next_sort_order + i
                                })
                                
                                db.commit()
                                
                            except Exception as photo_error:
                                print(f"Error uploading photo in edit mode: {photo_error}")
                
                flash('Beach place updated successfully!', 'success')
                
                # Return JSON response for AJAX requests
                if request.headers.get('Content-Type') == 'application/json' or \
                   request.headers.get('X-Requested-With') == 'XMLHttpRequest' or \
                   'application/json' in request.headers.get('Accept', ''):
                    return jsonify({
                        'success': True,
                        'message': 'Beach place updated successfully!',
                        'redirect': url_for('beaches')
                    })
                
                return redirect(url_for('beaches'))
        
        return render_template('beach_form.html', 
                             companies=companies, 
                             countries=countries,
                             terrain_types=terrain_types,
                             beach=beach_result_with_photos, 
                             action='edit',
                             google_maps_key=os.getenv('GOOGLE_MAPS_API_KEY', 'your-google-maps-api-key'))
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        return redirect(url_for('beaches'))

@app.route('/beaches/<beach_id>/delete', methods=['POST'])
@login_required
def delete_beach_place(beach_id):
    """Delete beach place with comprehensive validation and cascade deletion"""
    try:
        from sqlalchemy import create_engine, text
        
        # Database connection
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        
        with engine.connect() as db:
            # First check if beach exists
            beach_check = db.execute(text("""
                SELECT beach_name FROM beach_places 
                WHERE beach_place_id = :beach_id
            """), {"beach_id": beach_id}).fetchone()
            
            if not beach_check:
                flash('Beach place not found.', 'error')
                return redirect(url_for('beaches'))
            
            beach_name = beach_check[0]
            
            # Check if beach has any bookings
            booking_count = db.execute(text("""
                SELECT COUNT(*) as count
                FROM bookings 
                WHERE beach_place_id = :beach_id
            """), {"beach_id": beach_id}).fetchone()
            
            if booking_count and booking_count.count > 0:
                flash(
                    f'Cannot delete beach place "{beach_name}". '
                    f'It has {booking_count.count} existing booking(s). '
                    f'You can disable the beach instead if you need to prevent new bookings.',
                    'error'
                )
                return redirect(url_for('beaches'))
            
            # Use the existing connection's transaction (no need to call begin())
            try:
                # Delete beach terrain designs (beach design layouts)
                design_result = db.execute(text("""
                    DELETE FROM beach_place_terrains 
                    WHERE beach_place_id = :beach_id
                """), {"beach_id": beach_id})
                design_count = design_result.rowcount
                
                # Delete beach schedules
                schedule_result = db.execute(text("""
                    DELETE FROM beach_places_schedules 
                    WHERE beach_place_id = :beach_id
                """), {"beach_id": beach_id})
                schedule_count = schedule_result.rowcount
                
                # Delete beach photos
                photo_result = db.execute(text("""
                    DELETE FROM beach_places_photos 
                    WHERE beach_place_id = :beach_id
                """), {"beach_id": beach_id})
                photo_count = photo_result.rowcount
                
                # Delete reviews
                review_result = db.execute(text("""
                    DELETE FROM reviews 
                    WHERE beach_place_id = :beach_id
                """), {"beach_id": beach_id})
                review_count = review_result.rowcount
                
                # Delete adventures
                adventure_result = db.execute(text("""
                    DELETE FROM adventures 
                    WHERE beach_place_id = :beach_id
                """), {"beach_id": beach_id})
                adventure_count = adventure_result.rowcount
                
                # Delete markets
                market_result = db.execute(text("""
                    DELETE FROM markets 
                    WHERE beach_place_id = :beach_id
                """), {"beach_id": beach_id})
                market_count = market_result.rowcount
                
                # Delete restaurants
                restaurant_result = db.execute(text("""
                    DELETE FROM restaurants 
                    WHERE beach_place_id = :beach_id
                """), {"beach_id": beach_id})
                restaurant_count = restaurant_result.rowcount
                
                # Finally delete the beach place itself
                db.execute(text("""
                    DELETE FROM beach_places 
                    WHERE beach_place_id = :beach_id
                """), {"beach_id": beach_id})
                
                # Commit the transaction (SQLAlchemy will auto-commit at context exit)
                db.commit()
                
                # Success message with details
                deleted_items = []
                if design_count > 0:
                    deleted_items.append(f'{design_count} design layout(s)')
                if schedule_count > 0:
                    deleted_items.append(f'{schedule_count} schedule(s)')
                if photo_count > 0:
                    deleted_items.append(f'{photo_count} photo(s)')
                if review_count > 0:
                    deleted_items.append(f'{review_count} review(s)')
                if adventure_count > 0:
                    deleted_items.append(f'{adventure_count} adventure(s)')
                if market_count > 0:
                    deleted_items.append(f'{market_count} market(s)')
                if restaurant_count > 0:
                    deleted_items.append(f'{restaurant_count} restaurant(s)')
                
                success_msg = f'Beach place "{beach_name}" deleted successfully!'
                if deleted_items:
                    success_msg += f' Also removed: {", ".join(deleted_items)}.'
                
                flash(success_msg, 'success')
                
            except Exception as e:
                # Rollback the transaction
                db.rollback()
                raise e
        
    except Exception as e:
        error_msg = f'Error deleting beach place: {str(e)}'
        print(f"DELETE BEACH ERROR: {error_msg}")
        flash(error_msg, 'error')
    
    return redirect(url_for('beaches'))

@app.route('/beaches/<beach_id>/design', methods=['GET'])
@login_required
def beach_design(beach_id):
    """Full screen beach design page"""
    try:
        # Redirect to the static Vue application with just the beach ID
        return redirect(f"/static/BeachDesign/index.html?beach_id={beach_id}")
        
    except Exception as e:
        error_msg = f'Error loading beach design: {str(e)}'
        print(f"BEACH DESIGN ERROR: {error_msg}")
        print(f"ERROR TYPE: {type(e).__name__}")
        print(f"ERROR ARGS: {e.args}")
        print(f"ERROR TRACEBACK: {traceback.format_exc()}")
        flash(error_msg, 'error')
        # Redirect back to edit page instead of search page
        return redirect(url_for('edit_beach_place', beach_id=beach_id))

@app.route('/api/beach/<beach_id>', methods=['GET'])
def get_beach_data(beach_id):
    """Get complete beach data for the Vue designer app"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            # Get the beach place with company and country info
            query = """
                SELECT bp.beach_name, bp.beach_place_id, bp.company_id, bp.country_id,
                       bp.city, bp.address, bp.terrain_type_id, bp.max_seats,
                       bp.top_rows, bp.top_seats, bp.beach_information, bp.enable_beach,
                       bp.latitude, bp.longitude, bp.mask, bp.disable_today,
                       bp.is_double_seat, bp.has_umbrella, bp.has_showers, bp.has_lockers,
                       bp.has_market, bp.has_restaurant, bp.has_swimming_pool, bp.has_parking,
                       bp.has_toilets, bp.has_free_wifi, bp.has_music, bp.has_safety_box,
                       bp.has_access_wheelchair, bp.has_lockers_for_baby, bp.has_beach_volley,
                       bp.has_tennis, bp.has_spa, bp.has_medical, bp.has_lifeguard, bp.pet_allow,
                       bp.has_sea, bp.sea_location, bp.background_photo,
                       bp.created_at, bp.updated_at,
                       c.company_name,
                       co.country_name,
                       btt.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 btt ON bp.terrain_type_id = btt.terrain_type_id
                WHERE bp.beach_place_id = :beach_id
            """
            result = db.execute(text(query), {"beach_id": beach_id}).fetchone()
            
            if not result:
                return jsonify({'error': 'Beach not found'}), 404
            
            # Create beach object for Vue app
            beach_data = {
                'beach_name': result.beach_name if result.beach_name else 'Unnamed Beach',
                'beach_place_id': result.beach_place_id,
                'company_id': result.company_id,
                'country_id': result.country_id,
                'city': result.city,
                'address': result.address,
                'terrain_type_id': result.terrain_type_id,
                'max_seats': result.max_seats,
                'top_rows': result.top_rows,
                'top_seats': result.top_seats,
                'beach_information': result.beach_information,
                'enable_beach': result.enable_beach,
                'latitude': float(result.latitude) if result.latitude else 37.9755,
                'longitude': float(result.longitude) if result.longitude else 23.7348,
                'mask': result.mask if result.mask else [],
                'disable_today': result.disable_today,
                'is_double_seat': result.is_double_seat,
                'has_umbrella': result.has_umbrella,
                'has_showers': result.has_showers,
                'has_lockers': result.has_lockers,
                'has_market': result.has_market,
                'has_restaurant': result.has_restaurant,
                'has_swimming_pool': result.has_swimming_pool,
                'has_parking': result.has_parking,
                'has_toilets': result.has_toilets,
                'has_free_wifi': result.has_free_wifi,
                'has_music': result.has_music,
                'has_safety_box': result.has_safety_box,
                'has_access_wheelchair': result.has_access_wheelchair,
                'has_lockers_for_baby': result.has_lockers_for_baby,
                'has_beach_volley': result.has_beach_volley,
                'has_tennis': result.has_tennis,
                'has_spa': result.has_spa,
                'has_medical': result.has_medical,
                'has_lifeguard': result.has_lifeguard,
                'pet_allow': result.pet_allow,
                'has_sea': result.has_sea,
                'sea_location': result.sea_location,
                'background_photo': result.background_photo,
                'company_name': result.company_name,
                'country_name': result.country_name,
                'terrain_name': result.terrain_name
            }
            
            return jsonify(beach_data)
    
    except Exception as e:
        print(f"Error getting beach data: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': 'Failed to load beach data'}), 500

@app.route('/beaches/<int:beach_id>/vue-design', methods=['GET'])
@login_required
def vue_beach_design(beach_id):
    """Vue-based beach design page"""
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        import traceback
        import sys
        import json
        
        print(f"=== VUE BEACH DESIGN DEBUG START ===")
        print(f"Request for beach_id: {beach_id}")
        
        # Database connection
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        print(f"Database URL: {DATABASE_URL}")
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        print("Database connection established")
        
        # Get the beach place with company and country info
        query = """
            SELECT bp.beach_name, bp.beach_place_id, bp.company_id, bp.country_id,
                   bp.city, bp.address, bp.terrain_type_id, bp.max_seats,
                   bp.top_rows, bp.top_seats, bp.beach_information, bp.enable_beach,
                   bp.latitude, bp.longitude, bp.mask, bp.disable_today,
                   bp.is_double_seat, bp.has_umbrella, bp.has_showers, bp.has_lockers,
                   bp.has_market, bp.has_restaurant, bp.has_swimming_pool, bp.has_parking,
                   bp.has_toilets, bp.has_free_wifi, bp.has_music, bp.has_safety_box,
                   bp.has_access_wheelchair, bp.has_lockers_for_baby, bp.has_beach_volley,
                   bp.has_tennis, bp.has_spa, bp.has_medical, bp.has_lifeguard, bp.pet_allow,
                   bp.has_sea, bp.sea_location, bp.background_photo,
                   bp.created_at, bp.updated_at,
                   c.company_name,
                   co.country_name,
                   btt.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 btt ON bp.terrain_type_id = btt.terrain_type_id
            WHERE bp.beach_place_id = :beach_id
        """
        print(f"Executing query for beach_id: {beach_id}")
        result = db.execute(text(query), {"beach_id": beach_id}).fetchone()
        
        if not result:
            error_msg = f'Beach with ID {beach_id} not found.'
            print(f"BEACH DESIGN ERROR: {error_msg}")
            flash(error_msg, 'error')
            db.close()
            return redirect(url_for('beaches'))
        
        # Create beach object for template
        beach = {
            'beach_name': result.beach_name if result.beach_name else 'Unnamed Beach',
            'beach_place_id': result.beach_place_id,
            'company_id': result.company_id,
            'country_id': result.country_id,
            'city': result.city,
            'address': result.address,
            'terrain_type_id': result.terrain_type_id,
            'max_seats': result.max_seats,
            'top_rows': result.top_rows,
            'top_seats': result.top_seats,
            'beach_information': result.beach_information,
            'enable_beach': result.enable_beach,
            'latitude': result.latitude,
            'longitude': result.longitude,
            'mask': result.mask,
            'disable_today': result.disable_today,
            'is_double_seat': result.is_double_seat,
            'has_umbrella': result.has_umbrella,
            'has_showers': result.has_showers,
            'has_lockers': result.has_lockers,
            'has_market': result.has_market,
            'has_restaurant': result.has_restaurant,
            'has_swimming_pool': result.has_swimming_pool,
            'has_parking': result.has_parking,
            'has_toilets': result.has_toilets,
            'has_free_wifi': result.has_free_wifi,
            'has_music': result.has_music,
            'has_safety_box': result.has_safety_box,
            'has_access_wheelchair': result.has_access_wheelchair,
            'has_lockers_for_baby': result.has_lockers_for_baby,
            'has_beach_volley': result.has_beach_volley,
            'has_tennis': result.has_tennis,
            'has_spa': result.has_spa,
            'has_medical': result.has_medical,
            'has_lifeguard': result.has_lifeguard,
            'pet_allow': result.pet_allow,
            'has_sea': result.has_sea,
            'sea_location': result.sea_location,
            'background_photo': result.background_photo,
            'company_name': result.company_name,
            'country_name': result.country_name,
            'terrain_name': result.terrain_name
        }
        
        db.close()
        
        # Redirect to the static Vue application with just the beach ID
        return redirect(f"/static/BeachDesign/index.html?beach_id={beach_id}")
        
    except Exception as e:
        error_msg = f'Error loading beach design: {str(e)}'
        print(f"BEACH DESIGN ERROR: {error_msg}")
        print(f"ERROR TYPE: {type(e).__name__}")
        print(f"ERROR ARGS: {e.args}")
        print(f"ERROR TRACEBACK: {traceback.format_exc()}")
        flash(error_msg, 'error')
        # Redirect back to edit page instead of search page
        return redirect(url_for('edit_beach_place', beach_id=beach_id))

# Restaurants Management Routes

# Restaurants Management Routes
@app.route('/restaurants')
@login_required
def restaurants():
    """Restaurants management page"""
    try:
        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()
        
        # Check if restaurants table exists
        table_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'restaurants'
            )
        """)).fetchone()[0]
        
        restaurants_data = []
        if table_exists:
            # Get all restaurants with company and beach info
            restaurants_result = db.execute(text("""
                SELECT r.restaurant_id, r.restaurant_name, r.description, r.cuisine_type,
                       r.opening_time, r.closing_time, r.is_active, r.created_at,
                       c.company_name, bp.beach_name
                FROM restaurants r
                LEFT JOIN companies c ON r.company_id = c.company_id
                LEFT JOIN beach_places bp ON r.beach_place_id = bp.beach_place_id
                ORDER BY r.restaurant_name
            """)).fetchall()
            
            for restaurant in restaurants_result:
                hours = 'N/A'
                if restaurant.opening_time and restaurant.closing_time:
                    hours = f"{restaurant.opening_time} - {restaurant.closing_time}"
                
                restaurants_data.append({
                    'id': restaurant.restaurant_id,
                    'name': restaurant.restaurant_name,
                    'company': restaurant.company_name or 'No Company',
                    'beach': restaurant.beach_name or 'No Beach',
                    'cuisine_type': restaurant.cuisine_type or 'N/A',
                    'hours': hours,
                    'status': 'Active' if restaurant.is_active else 'Inactive',
                    'created_at': restaurant.created_at.strftime('%Y-%m-%d') if restaurant.created_at else 'N/A'
                })
        
        db.close()
        
        if not restaurants_data:
            flash('No restaurants found. The restaurants table may be empty or not exist yet.', 'info')
        
    except Exception as e:
        flash(f'Error loading restaurants: {str(e)}', 'error')
        restaurants_data = []
    
    return render_template('restaurants.html', restaurants=restaurants_data)

@app.route('/restaurants/add', methods=['GET', 'POST'])
@login_required
def add_restaurant():
    """Add new restaurant"""
    try:
        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()
        
        # Get companies and beach places for the form
        companies_result = db.execute(text("""
            SELECT company_id, company_name 
            FROM companies 
            WHERE company_status = 'approved'
            ORDER BY company_name
        """)).fetchall()
        
        beach_places_result = db.execute(text("""
            SELECT bp.beach_place_id, bp.beach_name, c.company_name
            FROM beach_places bp
            LEFT JOIN companies c ON bp.company_id = c.company_id
            WHERE bp.enable_beach = true
            ORDER BY c.company_name, bp.beach_name
        """)).fetchall()
        
        # Convert Row objects to dictionaries for JSON serialization
        companies = [{
            'company_id': str(row.company_id),
            'company_name': row.company_name
        } for row in companies_result]
        
        beach_places = [{
            'beach_place_id': str(row.beach_place_id),
            'beach_name': row.beach_name,
            'company_name': row.company_name
        } for row in beach_places_result]
        
        if request.method == 'POST':
            # Collect form data
            restaurant_data = {
                'restaurant_name': request.form.get('restaurant_name', '').strip(),
                'company_id': request.form.get('company_id', '').strip() or None,  # UUID as string
                'beach_place_id': request.form.get('beach_place_id', '').strip() or None,  # UUID as string
                'description': request.form.get('description', '').strip(),
                'cuisine_type': request.form.get('cuisine_type', '').strip(),
                'phone': request.form.get('phone', '').strip(),
                'email': request.form.get('email', '').strip(),
                'website': request.form.get('website', '').strip(),
                'opening_time': request.form.get('opening_time') or None,
                'closing_time': request.form.get('closing_time') or None,
                'is_active': request.form.get('is_active') == 'on'
            }
            
            # Validate required fields
            if not restaurant_data['restaurant_name']:
                flash('Restaurant name is required', 'error')
            elif not restaurant_data['company_id']:
                flash('Company is required', 'error')
            else:
                # Insert the restaurant
                result = db.execute(text("""
                    INSERT INTO restaurants (
                        restaurant_name, company_id, beach_place_id, description,
                        cuisine_type, phone, email, website, opening_time, closing_time, 
                        is_active, created_at
                    ) VALUES (
                        :restaurant_name, :company_id, :beach_place_id, :description,
                        :cuisine_type, :phone, :email, :website, :opening_time, :closing_time, 
                        :is_active, NOW()
                    ) RETURNING restaurant_id
                """), restaurant_data)
                
                restaurant_id = result.fetchone()[0]
                db.commit()
                
                if restaurant_id:
                    flash('Restaurant created successfully!', 'success')
                    return redirect(url_for('restaurants'))
                else:
                    flash('Error creating restaurant', 'error')
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        companies = []
        beach_places = []
    
    return render_template('restaurant_form.html', 
                         companies=companies,
                         beach_places=beach_places,
                         restaurant=None, 
                         action='add')

@app.route('/restaurants/<string:restaurant_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_restaurant(restaurant_id):
    """Edit existing restaurant"""
    try:
        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()
        
        # Get the restaurant
        restaurant_result = db.execute(text("""
            SELECT r.*, c.company_name, bp.beach_name
            FROM restaurants r
            LEFT JOIN companies c ON r.company_id = c.company_id
            LEFT JOIN beach_places bp ON r.beach_place_id = bp.beach_place_id
            WHERE r.restaurant_id = :restaurant_id
        """), {"restaurant_id": restaurant_id}).fetchone()
        
        if not restaurant_result:
            flash('Restaurant not found', 'error')
            return redirect(url_for('restaurants'))
        
        # Get companies and beach places for the form
        companies_result = db.execute(text("""
            SELECT company_id, company_name 
            FROM companies 
            WHERE company_status = 'approved'
            ORDER BY company_name
        """)).fetchall()
        
        beach_places_result = db.execute(text("""
            SELECT bp.beach_place_id, bp.beach_name, c.company_name
            FROM beach_places bp
            LEFT JOIN companies c ON bp.company_id = c.company_id
            WHERE bp.enable_beach = true
            ORDER BY c.company_name, bp.beach_name
        """)).fetchall()
        
        # Convert Row objects to dictionaries for JSON serialization
        companies = [{
            'company_id': str(row.company_id),
            'company_name': row.company_name
        } for row in companies_result]
        
        beach_places = [{
            'beach_place_id': str(row.beach_place_id),
            'beach_name': row.beach_name,
            'company_name': row.company_name
        } for row in beach_places_result]
        
        if request.method == 'POST':
            # Collect form data
            restaurant_data = {
                'restaurant_name': request.form.get('restaurant_name', '').strip(),
                'company_id': request.form.get('company_id', '').strip() or None,  # UUID as string
                'beach_place_id': request.form.get('beach_place_id', '').strip() or None,  # UUID as string
                'description': request.form.get('description', '').strip(),
                'cuisine_type': request.form.get('cuisine_type', '').strip(),
                'phone': request.form.get('phone', '').strip(),
                'email': request.form.get('email', '').strip(),
                'website': request.form.get('website', '').strip(),
                'opening_time': request.form.get('opening_time') or None,
                'closing_time': request.form.get('closing_time') or None,
                'is_active': request.form.get('is_active') == 'on'
            }
            
            # Validate required fields
            if not restaurant_data['restaurant_name']:
                flash('Restaurant name is required', 'error')
            elif not restaurant_data['company_id']:
                flash('Company is required', 'error')
            else:
                # Update the restaurant
                db.execute(text("""
                    UPDATE restaurants SET
                        restaurant_name = :restaurant_name,
                        company_id = :company_id,
                        beach_place_id = :beach_place_id,
                        description = :description,
                        cuisine_type = :cuisine_type,
                        phone = :phone,
                        email = :email,
                        website = :website,
                        opening_time = :opening_time,
                        closing_time = :closing_time,
                        is_active = :is_active,
                        updated_at = NOW()
                    WHERE restaurant_id = :restaurant_id
                """), {**restaurant_data, 'restaurant_id': restaurant_id})
                
                db.commit()
                flash('Restaurant updated successfully!', 'success')
                return redirect(url_for('restaurants'))
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        return redirect(url_for('restaurants'))
    
    return render_template('restaurant_form.html', 
                         companies=companies,
                         beach_places=beach_places,
                         restaurant=restaurant_result, 
                         action='edit')

@app.route('/restaurants/<string:restaurant_id>/delete', methods=['POST'])
@login_required
def delete_restaurant(restaurant_id):
    """Delete restaurant"""
    try:
        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()
        
        # Delete the restaurant
        db.execute(text("""
            DELETE FROM restaurants 
            WHERE restaurant_id = :restaurant_id
        """), {"restaurant_id": restaurant_id})
        
        db.commit()
        flash('Restaurant deleted successfully!', 'success')
        
        db.close()
        
    except Exception as e:
        flash(f'Error deleting restaurant: {str(e)}', 'error')
    
    return redirect(url_for('restaurants'))

# Restaurant Categories Management Routes
@app.route('/restaurant-categories')
@login_required
def restaurant_categories():
    """Restaurant categories management page"""
    try:
        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()
        
        # Get search parameters
        search_query = request.args.get('search', '').strip()
        restaurant_filter = request.args.get('restaurant_id', '').strip()
        
        # Build the SQL query with filters
        where_conditions = []
        params = {}
        
        if search_query:
            where_conditions.append("""
                (LOWER(rc.category_name) LIKE LOWER(:search) 
                 OR LOWER(rc.description) LIKE LOWER(:search)
                 OR LOWER(r.restaurant_name) LIKE LOWER(:search))
            """)
            params['search'] = f'%{search_query}%'
        
        if restaurant_filter:
            where_conditions.append("rc.restaurant_id = :restaurant_id")
            params['restaurant_id'] = restaurant_filter
        
        where_clause = "WHERE " + " AND ".join(where_conditions) if where_conditions else ""
        
        # Get restaurant categories with restaurant and company info
        categories_query = f"""
            SELECT rc.category_id, rc.category_name, rc.description, rc.sort_order,
                   r.restaurant_name, r.restaurant_id, c.company_name
            FROM restaurant_categories rc
            LEFT JOIN restaurants r ON rc.restaurant_id = r.restaurant_id
            LEFT JOIN companies c ON r.company_id = c.company_id
            {where_clause}
            ORDER BY c.company_name, r.restaurant_name, rc.sort_order, rc.category_name
        """
        
        categories_result = db.execute(text(categories_query), params).fetchall()
        
        categories_data = []
        for category in categories_result:
            categories_data.append({
                'id': category.category_id,
                'name': category.category_name,
                'description': category.description or 'No description',
                'sort_order': category.sort_order or 0,
                'restaurant_name': category.restaurant_name or 'Unknown Restaurant',
                'restaurant_id': str(category.restaurant_id) if category.restaurant_id else None,
                'company_name': category.company_name or 'Unknown Company'
            })
        
        # Get filter options for dropdowns
        restaurants_result = db.execute(text("""
            SELECT r.restaurant_id, r.restaurant_name, c.company_name
            FROM restaurants r
            LEFT JOIN companies c ON r.company_id = c.company_id
            WHERE r.is_active = true
            ORDER BY c.company_name, r.restaurant_name
        """)).fetchall()
        
        restaurants = [{
            'restaurant_id': str(row.restaurant_id),
            'restaurant_name': row.restaurant_name,
            'company_name': row.company_name
        } for row in restaurants_result]
        
        db.close()
        
    except Exception as e:
        flash(f'Error loading restaurant categories: {str(e)}', 'error')
        categories_data = []
        restaurants = []
    
    return render_template('restaurant_categories.html', 
                         categories=categories_data,
                         restaurants=restaurants)

@app.route('/restaurant-categories/add', methods=['GET', 'POST'])
@login_required
def add_restaurant_category():
    """Add new restaurant category"""
    try:
        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()
        
        # Get restaurants for the form
        restaurants_result = db.execute(text("""
            SELECT r.restaurant_id, r.restaurant_name, c.company_name
            FROM restaurants r
            LEFT JOIN companies c ON r.company_id = c.company_id
            WHERE r.is_active = true
            ORDER BY c.company_name, r.restaurant_name
        """)).fetchall()
        
        restaurants = [{
            'restaurant_id': str(row.restaurant_id),
            'restaurant_name': row.restaurant_name,
            'company_name': row.company_name
        } for row in restaurants_result]
        
        if request.method == 'POST':
            # Collect form data
            category_data = {
                'category_name': request.form.get('category_name', '').strip(),
                'restaurant_id': request.form.get('restaurant_id', '').strip() or None,  # UUID as string
                'description': request.form.get('description', '').strip(),
                'sort_order': int(request.form.get('sort_order', 0) or 0)
            }
            
            # Validate required fields
            if not category_data['category_name']:
                flash('Category name is required', 'error')
            elif not category_data['restaurant_id']:
                flash('Restaurant is required', 'error')
            else:
                # Insert the category
                result = db.execute(text("""
                    INSERT INTO restaurant_categories (
                        category_name, restaurant_id, description, sort_order
                    ) VALUES (
                        :category_name, :restaurant_id, :description, :sort_order
                    ) RETURNING category_id
                """), category_data)
                
                category_id = result.fetchone()[0]
                db.commit()
                
                if category_id:
                    flash('Restaurant category created successfully!', 'success')
                    return redirect(url_for('restaurant_categories'))
                else:
                    flash('Error creating restaurant category', 'error')
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        restaurants = []
    
    return render_template('restaurant_category_form.html', 
                         restaurants=restaurants,
                         category=None, 
                         action='add')

@app.route('/restaurant-categories/<int:category_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_restaurant_category(category_id):
    """Edit existing restaurant category"""
    try:
        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()
        
        # Get the category
        category_result = db.execute(text("""
            SELECT rc.*, r.restaurant_name, c.company_name
            FROM restaurant_categories rc
            LEFT JOIN restaurants r ON rc.restaurant_id = r.restaurant_id
            LEFT JOIN companies c ON r.company_id = c.company_id
            WHERE rc.category_id = :category_id
        """), {"category_id": category_id}).fetchone()
        
        if not category_result:
            flash('Restaurant category not found', 'error')
            return redirect(url_for('restaurant_categories'))
        
        # Get restaurants for the form
        restaurants_result = db.execute(text("""
            SELECT r.restaurant_id, r.restaurant_name, c.company_name
            FROM restaurants r
            LEFT JOIN companies c ON r.company_id = c.company_id
            WHERE r.is_active = true
            ORDER BY c.company_name, r.restaurant_name
        """)).fetchall()
        
        restaurants = [{
            'restaurant_id': str(row.restaurant_id),
            'restaurant_name': row.restaurant_name,
            'company_name': row.company_name
        } for row in restaurants_result]
        
        if request.method == 'POST':
            # Collect form data
            category_data = {
                'category_name': request.form.get('category_name', '').strip(),
                'restaurant_id': request.form.get('restaurant_id', '').strip() or None,  # UUID as string
                'description': request.form.get('description', '').strip(),
                'sort_order': int(request.form.get('sort_order', 0) or 0)
            }
            
            # Validate required fields
            if not category_data['category_name']:
                flash('Category name is required', 'error')
            elif not category_data['restaurant_id']:
                flash('Restaurant is required', 'error')
            else:
                # Update the category
                db.execute(text("""
                    UPDATE restaurant_categories SET
                        category_name = :category_name,
                        restaurant_id = :restaurant_id,
                        description = :description,
                        sort_order = :sort_order
                    WHERE category_id = :category_id
                """), {**category_data, 'category_id': category_id})
                
                db.commit()
                flash('Restaurant category updated successfully!', 'success')
                return redirect(url_for('restaurant_categories'))
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        return redirect(url_for('restaurant_categories'))
    
    return render_template('restaurant_category_form.html', 
                         restaurants=restaurants,
                         category=category_result, 
                         action='edit')

@app.route('/restaurant-categories/<int:category_id>/delete', methods=['POST'])
@login_required
def delete_restaurant_category(category_id):
    """Delete restaurant category"""
    try:
        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()
        
        # Check if category has items
        items_count = db.execute(text("""
            SELECT COUNT(*) as count FROM restaurant_items 
            WHERE category_id = :category_id
        """), {"category_id": category_id}).fetchone()[0]
        
        if items_count > 0:
            flash(f'Cannot delete category. It has {items_count} items. Please delete or reassign the items first.', 'error')
        else:
            # Delete the category
            db.execute(text("""
                DELETE FROM restaurant_categories 
                WHERE category_id = :category_id
            """), {"category_id": category_id})
            
            db.commit()
            flash('Restaurant category deleted successfully!', 'success')
        
        db.close()
        
    except Exception as e:
        flash(f'Error deleting restaurant category: {str(e)}', 'error')
    
    return redirect(url_for('restaurant_categories'))

# Restaurant Items Management Routes
@app.route('/restaurant-items')
@login_required
def restaurant_items():
    """Restaurant items management page"""
    try:
        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()
        
        # Get search parameters
        search_query = request.args.get('search', '').strip()
        restaurant_filter = request.args.get('restaurant_id', '').strip()
        category_filter = request.args.get('category_id', '').strip()
        
        # Build the SQL query with filters
        where_conditions = []
        params = {}
        
        if search_query:
            where_conditions.append("""
                (LOWER(ri.item_name) LIKE LOWER(:search) 
                 OR LOWER(ri.description) LIKE LOWER(:search)
                 OR LOWER(r.restaurant_name) LIKE LOWER(:search))
            """)
            params['search'] = f'%{search_query}%'
        
        if restaurant_filter:
            where_conditions.append("ri.restaurant_id = :restaurant_id")
            params['restaurant_id'] = restaurant_filter
            
        if category_filter:
            where_conditions.append("ri.category_id = :category_id")
            params['category_id'] = int(category_filter)
        
        where_clause = "WHERE " + " AND ".join(where_conditions) if where_conditions else ""
        
        # Get restaurant items with restaurant, category, and company info
        items_query = f"""
            SELECT ri.item_id, ri.item_name, ri.description, ri.price, ri.preparation_time,
                   ri.is_available, ri.allergens, ri.photo_path,
                   r.restaurant_name, rc.category_name, c.company_name, cur.currency_code
            FROM restaurant_items ri
            LEFT JOIN restaurants r ON ri.restaurant_id = r.restaurant_id
            LEFT JOIN restaurant_categories rc ON ri.category_id = rc.category_id
            LEFT JOIN companies c ON r.company_id = c.company_id
            LEFT JOIN currencies cur ON ri.currency_id = cur.currency_id
            {where_clause}
            ORDER BY c.company_name, r.restaurant_name, rc.category_name, ri.item_name
        """
        
        items_result = db.execute(text(items_query), params).fetchall()
        
        items_data = []
        for item in items_result:
            items_data.append({
                'item_id': str(item.item_id),
                'item_name': item.item_name,
                'description': item.description or 'No description',
                'price': float(item.price) if item.price else 0.0,
                'currency': item.currency_code or 'EUR',
                'preparation_time': item.preparation_time or 0,
                'is_available': item.is_available,
                'allergens': item.allergens or '',
                'photo_path': item.photo_path or '',
                'restaurant_name': item.restaurant_name or 'Unknown Restaurant',
                'category_name': item.category_name or 'No Category',
                'company_name': item.company_name or 'Unknown Company'
            })
        
        # Get filter options for dropdowns
        restaurants_result = db.execute(text("""
            SELECT r.restaurant_id, r.restaurant_name, c.company_name
            FROM restaurants r
            LEFT JOIN companies c ON r.company_id = c.company_id
            WHERE r.is_active = true
            ORDER BY c.company_name, r.restaurant_name
        """)).fetchall()
        
        categories_result = db.execute(text("""
            SELECT rc.category_id, rc.category_name, r.restaurant_name
            FROM restaurant_categories rc
            LEFT JOIN restaurants r ON rc.restaurant_id = r.restaurant_id
            ORDER BY r.restaurant_name, rc.sort_order, rc.category_name
        """)).fetchall()
        
        restaurants = [{
            'restaurant_id': str(row.restaurant_id),
            'restaurant_name': row.restaurant_name,
            'company_name': row.company_name
        } for row in restaurants_result]
        
        categories = [{
            'category_id': row.category_id,
            'category_name': row.category_name,
            'restaurant_name': row.restaurant_name
        } for row in categories_result]
        
        db.close()
        
    except Exception as e:
        flash(f'Error loading restaurant items: {str(e)}', 'error')
        items_data = []
        restaurants = []
        categories = []
    
    return render_template('restaurant_items.html', 
                         items=items_data,
                         restaurants=restaurants,
                         categories=categories)

@app.route('/restaurant-items/add', methods=['GET', 'POST'])
@login_required
def add_restaurant_item():
    """Add new restaurant item"""
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        import uuid
        
        # Database connection
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Get restaurants for the form
        restaurants_result = db.execute(text("""
            SELECT r.restaurant_id, r.restaurant_name, c.company_name
            FROM restaurants r
            LEFT JOIN companies c ON r.company_id = c.company_id
            WHERE r.is_active = true
            ORDER BY c.company_name, r.restaurant_name
        """)).fetchall()
        
        # Get categories for the form
        categories_result = db.execute(text("""
            SELECT rc.category_id, rc.category_name, r.restaurant_name, r.restaurant_id
            FROM restaurant_categories rc
            LEFT JOIN restaurants r ON rc.restaurant_id = r.restaurant_id
            ORDER BY r.restaurant_name, rc.sort_order, rc.category_name
        """)).fetchall()
        
        # Get currencies for the form
        currencies_result = db.execute(text("""
            SELECT currency_id, currency_code, currency_name
            FROM currencies
            WHERE is_active = true
            ORDER BY currency_code
        """)).fetchall()
        
        restaurants = [{
            'restaurant_id': str(row.restaurant_id),
            'restaurant_name': row.restaurant_name,
            'company_name': row.company_name
        } for row in restaurants_result]
        
        categories = [{
            'category_id': row.category_id,
            'category_name': row.category_name,
            'restaurant_name': row.restaurant_name,
            'restaurant_id': str(row.restaurant_id)
        } for row in categories_result]
        
        currencies = [{
            'currency_id': row.currency_id,
            'currency_code': row.currency_code,
            'currency_name': row.currency_name
        } for row in currencies_result]
        
        if request.method == 'POST':
            # Handle photo upload
            photo_path = None
            photo_file = request.files.get('photo')
            
            if photo_file and photo_file.filename:
                try:
                    import os
                    from werkzeug.utils import secure_filename
                    
                    # Generate unique filename
                    item_uuid = str(uuid.uuid4())
                    file_extension = os.path.splitext(secure_filename(photo_file.filename))[1]
                    filename = f"{item_uuid}_{secure_filename(photo_file.filename.replace(file_extension, ''))}{file_extension}"
                    
                    # Use backend/static instead of root static
                    upload_dir = os.path.join('backend', 'static', 'uploads', 'restaurant_items')
                    full_upload_dir = os.path.abspath(upload_dir)
                    
                    if not os.path.exists(full_upload_dir):
                        os.makedirs(full_upload_dir, exist_ok=True)
                    
                    file_path = os.path.join(full_upload_dir, filename)
                    photo_file.save(file_path)
                    
                    # Store relative path for database
                    photo_path = f'/static/uploads/restaurant_items/{filename}'
                    
                    print(f"Add photo upload debug - photo_path: {photo_path}")
                    print(f"Add photo upload debug - file saved successfully, size: {os.path.getsize(file_path)} bytes")
                    
                except Exception as photo_error:
                    print(f"Photo upload error: {photo_error}")
                    flash(f'Photo upload failed: {str(photo_error)}', 'warning')
            
            # Collect form data
            item_data = {
                'item_id': str(uuid.uuid4()),  # Generate UUID for item
                'item_name': request.form.get('item_name', '').strip(),
                'restaurant_id': request.form.get('restaurant_id', '').strip() or None,  # UUID as string
                'category_id': int(request.form.get('category_id') or 0) or None,
                'description': request.form.get('description', '').strip(),
                'price': float(request.form.get('price', 0) or 0),
                'currency_id': int(request.form.get('currency_id') or 1),
                'preparation_time': int(request.form.get('preparation_time', 0) or 0),
                'allergens': request.form.get('allergens', '').strip(),
                'is_available': request.form.get('is_available') == 'on',
                'photo_path': photo_path
            }
            
            # Validate required fields
            if not item_data['item_name']:
                flash('Item name is required', 'error')
            elif not item_data['restaurant_id']:
                flash('Restaurant is required', 'error')
            elif not item_data['category_id']:
                flash('Category is required', 'error')
            elif item_data['price'] <= 0:
                flash('Price must be greater than 0', 'error')
            else:
                # Insert the item
                result = db.execute(text("""
                    INSERT INTO restaurant_items (
                        item_id, item_name, restaurant_id, category_id, description,
                        price, currency_id, preparation_time, allergens, 
                        is_available, photo_path
                    ) VALUES (
                        :item_id, :item_name, :restaurant_id, :category_id, :description,
                        :price, :currency_id, :preparation_time, :allergens,
                        :is_available, :photo_path
                    ) RETURNING item_id
                """), item_data)
                
                result_item_id = result.fetchone()[0]
                db.commit()
                
                if result_item_id:
                    flash('Restaurant item created successfully!', 'success')
                    return redirect(url_for('restaurant_items'))
                else:
                    flash('Error creating restaurant item', 'error')
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        restaurants = []
        categories = []
        currencies = []
    
    return render_template('restaurant_item_form.html', 
                         restaurants=restaurants,
                         categories=categories,
                         currencies=currencies,
                         item=None, 
                         action='add')

@app.route('/restaurant-items/<string:item_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_restaurant_item(item_id):
    """Edit existing restaurant item"""
    try:
        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()
        
        # Get the item
        item_result = db.execute(text("""
            SELECT ri.*, r.restaurant_name, rc.category_name, c.company_name, cur.currency_code
            FROM restaurant_items ri
            LEFT JOIN restaurants r ON ri.restaurant_id = r.restaurant_id
            LEFT JOIN restaurant_categories rc ON ri.category_id = rc.category_id
            LEFT JOIN companies c ON r.company_id = c.company_id
            LEFT JOIN currencies cur ON ri.currency_id = cur.currency_id
            WHERE ri.item_id = :item_id
        """), {"item_id": item_id}).fetchone()
        
        if not item_result:
            flash('Restaurant item not found', 'error')
            return redirect(url_for('restaurant_items'))
        
        # Convert to dictionary with photo_path included
        item = {
            'item_id': str(item_result.item_id),
            'item_name': item_result.item_name,
            'restaurant_id': str(item_result.restaurant_id),
            'category_id': item_result.category_id,
            'description': item_result.description,
            'price': float(item_result.price) if item_result.price else 0,
            'currency_id': item_result.currency_id,
            'preparation_time': item_result.preparation_time,
            'allergens': item_result.allergens,
            'is_available': item_result.is_available,
            'photo_path': item_result.photo_path or '',
            'restaurant_name': item_result.restaurant_name,
            'category_name': item_result.category_name,
            'company_name': item_result.company_name
        }
        
        # Get form data similar to add_restaurant_item
        restaurants_result = db.execute(text("""
            SELECT r.restaurant_id, r.restaurant_name, c.company_name
            FROM restaurants r
            LEFT JOIN companies c ON r.company_id = c.company_id
            WHERE r.is_active = true
            ORDER BY c.company_name, r.restaurant_name
        """)).fetchall()
        
        categories_result = db.execute(text("""
            SELECT rc.category_id, rc.category_name, r.restaurant_name, r.restaurant_id
            FROM restaurant_categories rc
            LEFT JOIN restaurants r ON rc.restaurant_id = r.restaurant_id
            ORDER BY r.restaurant_name, rc.sort_order, rc.category_name
        """)).fetchall()
        
        currencies_result = db.execute(text("""
            SELECT currency_id, currency_code, currency_name
            FROM currencies
            WHERE is_active = true
            ORDER BY currency_code
        """)).fetchall()
        
        restaurants = [{
            'restaurant_id': str(row.restaurant_id),
            'restaurant_name': row.restaurant_name,
            'company_name': row.company_name
        } for row in restaurants_result]
        
        categories = [{
            'category_id': row.category_id,
            'category_name': row.category_name,
            'restaurant_name': row.restaurant_name,
            'restaurant_id': str(row.restaurant_id)
        } for row in categories_result]
        
        currencies = [{
            'currency_id': row.currency_id,
            'currency_code': row.currency_code,
            'currency_name': row.currency_name
        } for row in currencies_result]
        
        if request.method == 'POST':
            # Handle photo upload and deletion (same logic as market items)
            photo_path = item_result.photo_path  # Keep existing photo by default
            
            # Check if user wants to delete current photo
            if request.form.get('delete_photo') == 'on':
                if item_result.photo_path:
                    try:
                        import os
                        old_file_path = os.path.join('backend', 'static', 'uploads', 'restaurant_items', 
                                                   os.path.basename(item_result.photo_path))
                        if os.path.exists(old_file_path):
                            os.remove(old_file_path)
                    except Exception as delete_error:
                        print(f"Error deleting old photo: {delete_error}")
                photo_path = None
            
            # Handle new photo upload
            photo_file = request.files.get('photo')
            if photo_file and photo_file.filename:
                try:
                    import os
                    from werkzeug.utils import secure_filename
                    
                    # Delete old photo if exists
                    if item_result.photo_path and not request.form.get('delete_photo'):
                        try:
                            old_file_path = os.path.join('backend', 'static', 'uploads', 'restaurant_items', 
                                                       os.path.basename(item_result.photo_path))
                            if os.path.exists(old_file_path):
                                os.remove(old_file_path)
                        except Exception as delete_error:
                            print(f"Error deleting old photo: {delete_error}")
                    
                    # Generate unique filename
                    file_extension = os.path.splitext(secure_filename(photo_file.filename))[1]
                    filename = f"{item_id}_{secure_filename(photo_file.filename.replace(file_extension, ''))}{file_extension}"
                    
                    upload_dir = os.path.join('backend', 'static', 'uploads', 'restaurant_items')
                    full_upload_dir = os.path.abspath(upload_dir)
                    
                    if not os.path.exists(full_upload_dir):
                        os.makedirs(full_upload_dir, exist_ok=True)
                    
                    file_path = os.path.join(full_upload_dir, filename)
                    photo_file.save(file_path)
                    
                    photo_path = f'/static/uploads/restaurant_items/{filename}'
                    
                    print(f"Edit photo upload debug - photo_path: {photo_path}")
                    print(f"Edit photo upload debug - file saved successfully, size: {os.path.getsize(file_path)} bytes")
                    
                except Exception as photo_error:
                    print(f"Photo upload error: {photo_error}")
                    flash(f'Photo upload failed: {str(photo_error)}', 'warning')
            
            # Collect form data
            item_data = {
                'item_name': request.form.get('item_name', '').strip(),
                'restaurant_id': request.form.get('restaurant_id', '').strip() or None,
                'category_id': int(request.form.get('category_id') or 0) or None,
                'description': request.form.get('description', '').strip(),
                'price': float(request.form.get('price', 0) or 0),
                'currency_id': int(request.form.get('currency_id') or 1),
                'preparation_time': int(request.form.get('preparation_time', 0) or 0),
                'allergens': request.form.get('allergens', '').strip(),
                'is_available': request.form.get('is_available') == 'on',
                'photo_path': photo_path
            }
            
            # Validate required fields
            if not item_data['item_name']:
                flash('Item name is required', 'error')
            elif not item_data['restaurant_id']:
                flash('Restaurant is required', 'error')
            elif not item_data['category_id']:
                flash('Category is required', 'error')
            elif item_data['price'] <= 0:
                flash('Price must be greater than 0', 'error')
            else:
                # Update the item
                db.execute(text("""
                    UPDATE restaurant_items SET
                        item_name = :item_name,
                        restaurant_id = :restaurant_id,
                        category_id = :category_id,
                        description = :description,
                        price = :price,
                        currency_id = :currency_id,
                        preparation_time = :preparation_time,
                        allergens = :allergens,
                        is_available = :is_available,
                        photo_path = :photo_path
                    WHERE item_id = :item_id
                """), {**item_data, 'item_id': item_id})
                
                db.commit()
                flash('Restaurant item updated successfully!', 'success')
                return redirect(url_for('restaurant_items'))
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        return redirect(url_for('restaurant_items'))
    
    return render_template('restaurant_item_form.html', 
                         restaurants=restaurants,
                         categories=categories,
                         currencies=currencies,
                         item=item, 
                         action='edit')

@app.route('/restaurant-items/<string:item_id>/delete', methods=['POST'])
@login_required
def delete_restaurant_item(item_id):
    """Delete restaurant item"""
    try:
        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()
        
        # Get the item to check if it has a photo
        item_result = db.execute(text("""
            SELECT photo_path FROM restaurant_items 
            WHERE item_id = :item_id
        """), {"item_id": item_id}).fetchone()
        
        if item_result and item_result.photo_path:
            # Delete the photo file
            try:
                import os
                file_path = os.path.join('backend', 'static', 'uploads', 'restaurant_items', 
                                       os.path.basename(item_result.photo_path))
                if os.path.exists(file_path):
                    os.remove(file_path)
                    print(f"Deleted photo file: {file_path}")
            except Exception as delete_error:
                print(f"Error deleting photo file: {delete_error}")
        
        # Delete the item
        db.execute(text("""
            DELETE FROM restaurant_items 
            WHERE item_id = :item_id
        """), {"item_id": item_id})
        
        db.commit()
        flash('Restaurant item deleted successfully!', 'success')
        
        db.close()
        
    except Exception as e:
        flash(f'Error deleting restaurant item: {str(e)}', 'error')
    
    return redirect(url_for('restaurant_items'))
@app.route('/markets')
@login_required
def markets():
    """Markets management page"""
    try:
        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()
        
        # Check if markets table exists
        table_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'markets'
            )
        """)).fetchone()[0]
        
        markets_data = []
        if table_exists:
            # Get all markets with company and beach info
            markets_result = db.execute(text("""
                SELECT m.market_id, m.market_name, m.description,
                       m.opening_time, m.closing_time, m.delivery_available,
                       m.delivery_fee, m.min_order_amount, m.is_active, m.created_at,
                       c.company_name, bp.beach_name
                FROM markets m
                LEFT JOIN companies c ON m.company_id = c.company_id
                LEFT JOIN beach_places bp ON m.beach_place_id = bp.beach_place_id
                ORDER BY m.market_name
            """)).fetchall()
            
            for market in markets_result:
                hours = 'N/A'
                if market.opening_time and market.closing_time:
                    hours = f"{market.opening_time} - {market.closing_time}"
                
                markets_data.append({
                    'id': market.market_id,
                    'name': market.market_name,
                    'company': market.company_name or 'No Company',
                    'beach': market.beach_name or 'No Beach',
                    'hours': hours,
                    'delivery': 'Yes' if market.delivery_available else 'No',
                    'delivery_fee': f'€{market.delivery_fee:.2f}' if market.delivery_fee else '€0.00',
                    'min_order': f'€{market.min_order_amount:.2f}' if market.min_order_amount else '€0.00',
                    'status': 'Active' if market.is_active else 'Inactive',
                    'created_at': market.created_at.strftime('%Y-%m-%d') if market.created_at else 'N/A'
                })
        
        db.close()
        
        if not markets_data:
            flash('No markets found. The markets table may be empty or not exist yet.', 'info')
        
    except Exception as e:
        flash(f'Error loading markets: {str(e)}', 'error')
        markets_data = []
    
    return render_template('markets.html', markets=markets_data)

@app.route('/markets/add', methods=['GET', 'POST'])
@login_required
def add_market():
    """Add new market"""
    try:
        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()
        
        # Get companies and beach places for the form
        companies_result = db.execute(text("""
            SELECT company_id, company_name 
            FROM companies 
            WHERE company_status = 'approved'
            ORDER BY company_name
        """)).fetchall()
        
        beach_places_result = db.execute(text("""
            SELECT bp.beach_place_id, bp.beach_name, c.company_name
            FROM beach_places bp
            LEFT JOIN companies c ON bp.company_id = c.company_id
            WHERE bp.enable_beach = true
            ORDER BY c.company_name, bp.beach_name
        """)).fetchall()
        
        # Convert Row objects to dictionaries for JSON serialization
        companies = [{
            'company_id': str(row.company_id),
            'company_name': row.company_name
        } for row in companies_result]
        
        beach_places = [{
            'beach_place_id': str(row.beach_place_id),
            'beach_name': row.beach_name,
            'company_name': row.company_name
        } for row in beach_places_result]
        
        if request.method == 'POST':
            # Collect form data
            market_data = {
                'market_name': request.form.get('market_name', '').strip(),
                'company_id': request.form.get('company_id', '').strip() or None,  # UUID as string
                'beach_place_id': request.form.get('beach_place_id', '').strip() or None,  # UUID as string
                'description': request.form.get('description', '').strip(),
                'opening_time': request.form.get('opening_time') or None,
                'closing_time': request.form.get('closing_time') or None,
                'delivery_available': request.form.get('delivery_available') == 'on',
                'delivery_fee': float(request.form.get('delivery_fee', 0) or 0),
                'min_order_amount': float(request.form.get('min_order_amount', 0) or 0),
                'is_active': request.form.get('is_active') == 'on'
            }
            
            # Validate required fields
            if not market_data['market_name']:
                flash('Market name is required', 'error')
            elif not market_data['company_id']:
                flash('Company is required', 'error')
            else:
                # Insert the market
                result = db.execute(text("""
                    INSERT INTO markets (
                        market_name, company_id, beach_place_id, description,
                        opening_time, closing_time, delivery_available, 
                        delivery_fee, min_order_amount, is_active, created_at
                    ) VALUES (
                        :market_name, :company_id, :beach_place_id, :description,
                        :opening_time, :closing_time, :delivery_available,
                        :delivery_fee, :min_order_amount, :is_active, NOW()
                    ) RETURNING market_id
                """), market_data)
                
                market_id = result.fetchone()[0]
                db.commit()
                
                if market_id:
                    flash('Market created successfully!', 'success')
                    return redirect(url_for('markets'))
                else:
                    flash('Error creating market', 'error')
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        companies = []
        beach_places = []
    
    return render_template('market_form.html', 
                         companies=companies,
                         beach_places=beach_places,
                         market=None, 
                         action='add')

@app.route('/markets/<string:market_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_market(market_id):
    """Edit existing market"""
    try:
        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()
        
        # Get the market
        market_result = db.execute(text("""
            SELECT m.*, c.company_name, bp.beach_name
            FROM markets m
            LEFT JOIN companies c ON m.company_id = c.company_id
            LEFT JOIN beach_places bp ON m.beach_place_id = bp.beach_place_id
            WHERE m.market_id = :market_id
        """), {"market_id": market_id}).fetchone()
        
        if not market_result:
            flash('Market not found', 'error')
            return redirect(url_for('markets'))
        
        # Get companies and beach places for the form
        companies_result = db.execute(text("""
            SELECT company_id, company_name 
            FROM companies 
            WHERE company_status = 'approved'
            ORDER BY company_name
        """)).fetchall()
        
        beach_places_result = db.execute(text("""
            SELECT bp.beach_place_id, bp.beach_name, c.company_name
            FROM beach_places bp
            LEFT JOIN companies c ON bp.company_id = c.company_id
            WHERE bp.enable_beach = true
            ORDER BY c.company_name, bp.beach_name
        """)).fetchall()
        
        # Convert Row objects to dictionaries for JSON serialization
        companies = [{
            'company_id': str(row.company_id),
            'company_name': row.company_name
        } for row in companies_result]
        
        beach_places = [{
            'beach_place_id': str(row.beach_place_id),
            'beach_name': row.beach_name,
            'company_name': row.company_name
        } for row in beach_places_result]
        
        if request.method == 'POST':
            # Collect form data
            market_data = {
                'market_name': request.form.get('market_name', '').strip(),
                'company_id': request.form.get('company_id', '').strip() or None,  # UUID as string
                'beach_place_id': request.form.get('beach_place_id', '').strip() or None,  # UUID as string
                'description': request.form.get('description', '').strip(),
                'opening_time': request.form.get('opening_time') or None,
                'closing_time': request.form.get('closing_time') or None,
                'delivery_available': request.form.get('delivery_available') == 'on',
                'delivery_fee': float(request.form.get('delivery_fee', 0) or 0),
                'min_order_amount': float(request.form.get('min_order_amount', 0) or 0),
                'is_active': request.form.get('is_active') == 'on'
            }
            
            # Validate required fields
            if not market_data['market_name']:
                flash('Market name is required', 'error')
            elif not market_data['company_id']:
                flash('Company is required', 'error')
            else:
                # Update the market
                db.execute(text("""
                    UPDATE markets SET
                        market_name = :market_name,
                        company_id = :company_id,
                        beach_place_id = :beach_place_id,
                        description = :description,
                        opening_time = :opening_time,
                        closing_time = :closing_time,
                        delivery_available = :delivery_available,
                        delivery_fee = :delivery_fee,
                        min_order_amount = :min_order_amount,
                        is_active = :is_active
                    WHERE market_id = :market_id
                """), {**market_data, 'market_id': market_id})
                
                db.commit()
                flash('Market updated successfully!', 'success')
                return redirect(url_for('markets'))
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        return redirect(url_for('markets'))
    
    return render_template('market_form.html', 
                         companies=companies,
                         beach_places=beach_places,
                         market=market_result, 
                         action='edit')

@app.route('/markets/<string:market_id>/delete', methods=['POST'])
@login_required
def delete_market(market_id):
    """Delete market"""
    try:
        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()
        
        # Delete the market
        db.execute(text("""
            DELETE FROM markets 
            WHERE market_id = :market_id
        """), {"market_id": market_id})
        
        db.commit()
        flash('Market deleted successfully!', 'success')
        
        db.close()
        
    except Exception as e:
        flash(f'Error deleting market: {str(e)}', 'error')
    
    return redirect(url_for('markets'))

# Market Categories Management Routes
@app.route('/market-categories')
@login_required
def market_categories():
    """Market categories management page"""
    try:
        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()
        
        # Check if market_categories table exists
        table_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'market_categories'
            )
        """)).fetchone()[0]
        
        categories_data = []
        if table_exists:
            # Check for data type mismatch and fix it automatically
            try:
                markets_type = db.execute(text("""
                    SELECT data_type 
                    FROM information_schema.columns 
                    WHERE table_name = 'markets' AND column_name = 'market_id'
                """)).fetchone()
                
                categories_type = db.execute(text("""
                    SELECT data_type 
                    FROM information_schema.columns 
                    WHERE table_name = 'market_categories' AND column_name = 'market_id'
                """)).fetchone()
                
                # Check if there's a type mismatch between UUID and BIGINT
                if (markets_type and categories_type and 
                    markets_type[0] == 'uuid' and categories_type[0] == 'bigint'):
                    
                    print(f"Auto-fixing schema: markets.market_id={markets_type[0]}, market_categories.market_id={categories_type[0]}")
                    
                    # Perform automatic migration
                    db.execute(text("""
                        DO $$ 
                        BEGIN
                            -- Drop foreign key constraint if exists
                            IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'market_categories_market_id_fkey') THEN
                                ALTER TABLE market_categories DROP CONSTRAINT market_categories_market_id_fkey;
                            END IF;
                            
                            -- Add temporary UUID column
                            ALTER TABLE market_categories ADD COLUMN market_id_uuid UUID;
                            
                            -- Update with UUID values from markets table
                            UPDATE market_categories mc 
                            SET market_id_uuid = CASE 
                                WHEN EXISTS(SELECT 1 FROM markets m WHERE m.market_id::TEXT = mc.market_id::TEXT) 
                                THEN (SELECT m.market_id FROM markets m WHERE m.market_id::TEXT = mc.market_id::TEXT LIMIT 1)
                                ELSE NULL
                            END;
                            
                            -- Drop old column and rename new one
                            ALTER TABLE market_categories DROP COLUMN market_id;
                            ALTER TABLE market_categories RENAME COLUMN market_id_uuid TO market_id;
                            
                            -- Add foreign key constraint back
                            ALTER TABLE market_categories 
                            ADD CONSTRAINT market_categories_market_id_fkey 
                            FOREIGN KEY (market_id) REFERENCES markets(market_id);
                            
                            -- Create index
                            CREATE INDEX IF NOT EXISTS idx_market_categories_market_id 
                            ON market_categories(market_id);
                        END $$;
                    """))
                    
                    db.commit()
                    flash('Database schema automatically updated for UUID compatibility!', 'success')
                    
            except Exception as migration_error:
                db.rollback()
                print(f"Auto-migration error: {migration_error}")
                # Continue with the original query attempt
            
            # Get all market categories with market and company info
            categories_result = db.execute(text("""
                SELECT mc.category_id, mc.category_name, mc.description, mc.sort_order,
                       m.market_name, c.company_name
                FROM market_categories mc
                LEFT JOIN markets m ON mc.market_id = m.market_id
                LEFT JOIN companies c ON m.company_id = c.company_id
                ORDER BY c.company_name, m.market_name, mc.sort_order, mc.category_name
            """)).fetchall()
            
            for category in categories_result:
                categories_data.append({
                    'id': category.category_id,
                    'name': category.category_name,
                    'description': category.description or 'No description',
                    'sort_order': category.sort_order,
                    'market': category.market_name or 'No Market',
                    'company': category.company_name or 'No Company'
                })
        
        db.close()
        
        if not categories_data:
            flash('No market categories found. The market_categories table may be empty or not exist yet.', 'info')
        
    except Exception as e:
        flash(f'Error loading market categories: {str(e)}', 'error')
        categories_data = []
    
    return render_template('market_categories.html', categories=categories_data)

@app.route('/market-categories/add', methods=['GET', 'POST'])
@login_required
def add_market_category():
    """Add new market category"""
    try:
        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()
        
        # Get markets for the form
        markets_result = db.execute(text("""
            SELECT m.market_id, m.market_name, c.company_name
            FROM markets m
            LEFT JOIN companies c ON m.company_id = c.company_id
            WHERE m.is_active = true
            ORDER BY c.company_name, m.market_name
        """)).fetchall()
        
        # Convert Row objects to dictionaries for JSON serialization
        markets = [{
            'market_id': str(row.market_id),
            'market_name': row.market_name,
            'company_name': row.company_name or 'No Company'
        } for row in markets_result]
        
        if request.method == 'POST':
            # Collect form data
            category_data = {
                'category_name': request.form.get('category_name', '').strip(),
                'market_id': request.form.get('market_id', '').strip() or None,  # UUID as string
                'description': request.form.get('description', '').strip(),
                'sort_order': int(request.form.get('sort_order', 0) or 0)
            }
            
            # Validate required fields
            if not category_data['category_name']:
                flash('Category name is required', 'error')
            elif not category_data['market_id']:
                flash('Market is required', 'error')
            else:
                # Insert the market category
                result = db.execute(text("""
                    INSERT INTO market_categories (
                        category_name, market_id, description, sort_order
                    ) VALUES (
                        :category_name, :market_id, :description, :sort_order
                    ) RETURNING category_id
                """), category_data)
                
                category_id = result.fetchone()[0]
                db.commit()
                
                if category_id:
                    flash('Market category created successfully!', 'success')
                    return redirect(url_for('market_categories'))
                else:
                    flash('Error creating market category', 'error')
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        markets = []
    
    return render_template('market_category_form.html', 
                         markets=markets,
                         category=None, 
                         action='add')

@app.route('/market-categories/<int:category_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_market_category(category_id):
    """Edit existing market category"""
    try:
        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()
        
        # Get the market category
        category_result = db.execute(text("""
            SELECT mc.*, m.market_name, c.company_name
            FROM market_categories mc
            LEFT JOIN markets m ON mc.market_id = m.market_id
            LEFT JOIN companies c ON m.company_id = c.company_id
            WHERE mc.category_id = :category_id
        """), {"category_id": category_id}).fetchone()
        
        if not category_result:
            flash('Market category not found', 'error')
            return redirect(url_for('market_categories'))
        
        # Get markets for the form
        markets_result = db.execute(text("""
            SELECT m.market_id, m.market_name, c.company_name
            FROM markets m
            LEFT JOIN companies c ON m.company_id = c.company_id
            WHERE m.is_active = true
            ORDER BY c.company_name, m.market_name
        """)).fetchall()
        
        # Convert Row objects to dictionaries for JSON serialization
        markets = [{
            'market_id': str(row.market_id),
            'market_name': row.market_name,
            'company_name': row.company_name or 'No Company'
        } for row in markets_result]
        
        if request.method == 'POST':
            # Collect form data
            category_data = {
                'category_name': request.form.get('category_name', '').strip(),
                'market_id': request.form.get('market_id', '').strip() or None,  # UUID as string
                'description': request.form.get('description', '').strip(),
                'sort_order': int(request.form.get('sort_order', 0) or 0)
            }
            
            # Validate required fields
            if not category_data['category_name']:
                flash('Category name is required', 'error')
            elif not category_data['market_id']:
                flash('Market is required', 'error')
            else:
                # Update the market category
                db.execute(text("""
                    UPDATE market_categories SET
                        category_name = :category_name,
                        market_id = :market_id,
                        description = :description,
                        sort_order = :sort_order
                    WHERE category_id = :category_id
                """), {**category_data, 'category_id': category_id})
                
                db.commit()
                flash('Market category updated successfully!', 'success')
                return redirect(url_for('market_categories'))
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        return redirect(url_for('market_categories'))
    
    return render_template('market_category_form.html', 
                         markets=markets,
                         category=category_result, 
                         action='edit')

@app.route('/market-categories/<int:category_id>/delete', methods=['POST'])
@login_required
def delete_market_category(category_id):
    """Delete market category"""
    try:
        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()
        
        # Check if category has items
        items_count = db.execute(text("""
            SELECT COUNT(*) FROM market_items 
            WHERE category_id = :category_id
        """), {"category_id": category_id}).fetchone()[0]
        
        if items_count > 0:
            flash(f'Cannot delete category. It has {items_count} items. Please move or delete the items first.', 'error')
        else:
            # Delete the market category
            db.execute(text("""
                DELETE FROM market_categories 
                WHERE category_id = :category_id
            """), {"category_id": category_id})
            
            db.commit()
            flash('Market category deleted successfully!', 'success')
        
        db.close()
        
    except Exception as e:
        flash(f'Error deleting market category: {str(e)}', 'error')
    
    return redirect(url_for('market_categories'))

# Market Items Management Routes
@app.route('/market-items')
@login_required
def market_items():
    """Market items management page with advanced search"""
    try:
        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()
        
        # Get search parameters
        search_query = request.args.get('search', '').strip()
        market_filter = request.args.get('market_id', '').strip()
        category_filter = request.args.get('category_id', '').strip()
        
        # Build the SQL query with filters
        where_conditions = []
        params = {}
        
        if search_query:
            where_conditions.append("""
                (LOWER(mi.item_name) LIKE LOWER(:search) 
                 OR LOWER(mi.description) LIKE LOWER(:search)
                 OR LOWER(r.restaurant_name) LIKE LOWER(:search))
            """)
            params['search'] = f'%{search_query}%'
        
        if market_filter:
            where_conditions.append("mi.market_id = :market_id")
            params['market_id'] = market_filter
            
        if category_filter:
            where_conditions.append("mi.category_id = :category_id")
            params['category_id'] = int(category_filter)
        
        where_clause = "WHERE " + " AND ".join(where_conditions) if where_conditions else ""
        
        # Get market items with market, category, restaurant, and company info
        items_query = f"""
            SELECT mi.item_id, mi.item_name, mi.description, mi.price, mi.stock_quantity,
                   mi.is_available, mi.brand, mi.barcode, mi.photo_path,
                   m.market_name, mc.category_name, c.company_name, cur.currency_code,
                   r.restaurant_name, r.restaurant_id
            FROM market_items mi
            LEFT JOIN markets m ON mi.market_id = m.market_id
            LEFT JOIN market_categories mc ON mi.category_id = mc.category_id
            LEFT JOIN companies c ON m.company_id = c.company_id
            LEFT JOIN currencies cur ON mi.currency_id = cur.currency_id
            LEFT JOIN restaurants r ON r.beach_place_id = m.beach_place_id
            {where_clause}
            ORDER BY c.company_name, m.market_name, mc.category_name, mi.item_name
        """
        
        items_result = db.execute(text(items_query), params).fetchall()
        
        items_data = []
        for item in items_result:
            items_data.append({
                'item_id': str(item.item_id),
                'item_name': item.item_name,
                'description': item.description or 'No description',
                'price': float(item.price) if item.price else 0.0,
                'currency': item.currency_code or 'EUR',
                'stock_quantity': item.stock_quantity or 0,
                'is_available': item.is_available,
                'brand': item.brand or '',
                'barcode': item.barcode or '',
                'photo_path': item.photo_path or '',
                'market_name': item.market_name or 'Unknown Market',
                'category_name': item.category_name or 'No Category',
                'company_name': item.company_name or 'Unknown Company',
                'restaurant_name': item.restaurant_name or 'No Restaurant',
                'restaurant_id': str(item.restaurant_id) if item.restaurant_id else None
            })
        
        # Get filter options for dropdowns
        markets_result = db.execute(text("""
            SELECT m.market_id, m.market_name, c.company_name
            FROM markets m
            LEFT JOIN companies c ON m.company_id = c.company_id
            WHERE m.is_active = true
            ORDER BY c.company_name, m.market_name
        """)).fetchall()
        
        categories_result = db.execute(text("""
            SELECT mc.category_id, mc.category_name, m.market_name
            FROM market_categories mc
            LEFT JOIN markets m ON mc.market_id = m.market_id
            ORDER BY m.market_name, mc.category_name
        """)).fetchall()
        
        # Convert to dictionaries for template
        markets = [{
            'market_id': str(row.market_id),
            'market_name': row.market_name,
            'company_name': row.company_name or 'No Company'
        } for row in markets_result]
        
        categories = [{
            'category_id': row.category_id,
            'category_name': row.category_name,
            'market_name': row.market_name or 'No Market'
        } for row in categories_result]
        
        db.close()
        
        # Statistics
        total_items = len(items_data)
        available_items = sum(1 for item in items_data if item['is_available'])
        
        return render_template('market_items.html', 
                             items=items_data,
                             markets=markets,
                             categories=categories,
                             search_query=search_query,
                             selected_market=market_filter,
                             selected_category=category_filter,
                             total_items=total_items,
                             available_items=available_items)
        
    except Exception as e:
        flash(f'Error loading market items: {str(e)}', 'error')
        return render_template('market_items.html', 
                             items=[],
                             markets=[],
                             categories=[],
                             total_items=0,
                             available_items=0)

@app.route('/market-items/add', methods=['GET', 'POST'])
@login_required
def add_market_item():
    """Add new market item"""
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Get markets and categories for the form
        markets_result = db.execute(text("""
            SELECT m.market_id, m.market_name, c.company_name
            FROM markets m
            LEFT JOIN companies c ON m.company_id = c.company_id
            WHERE m.is_active = true
            ORDER BY c.company_name, m.market_name
        """)).fetchall()
        
        categories_result = db.execute(text("""
            SELECT mc.category_id, mc.category_name, m.market_name, m.market_id
            FROM market_categories mc
            LEFT JOIN markets m ON mc.market_id = m.market_id
            ORDER BY m.market_name, mc.category_name
        """)).fetchall()
        
        currencies_result = db.execute(text("""
            SELECT currency_id, currency_code, currency_name
            FROM currencies
            WHERE is_active = true
            ORDER BY currency_code
        """)).fetchall()
        
        # Convert to dictionaries
        markets = [{
            'market_id': str(row.market_id),
            'market_name': row.market_name,
            'company_name': row.company_name or 'No Company'
        } for row in markets_result]
        
        categories = [{
            'category_id': row.category_id,
            'category_name': row.category_name,
            'market_name': row.market_name or 'No Market',
            'market_id': str(row.market_id) if row.market_id else ''
        } for row in categories_result]
        
        currencies = [{
            'currency_id': row.currency_id,
            'currency_code': row.currency_code,
            'currency_name': row.currency_name
        } for row in currencies_result]
        
        if request.method == 'POST':
            # Generate UUID for new item
            import uuid
            item_id = str(uuid.uuid4())
            
            # Handle photo upload
            photo_path = None
            if 'photo' in request.files:
                file = request.files['photo']
                print(f"Photo upload debug - file: {file}, filename: {file.filename if file else 'None'}")
                if file and file.filename:
                    from werkzeug.utils import secure_filename
                    import os
                    
                    # Validate file type
                    allowed_extensions = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
                    file_ext = file.filename.rsplit('.', 1)[1].lower() if '.' in file.filename else ''
                    print(f"Photo upload debug - file extension: {file_ext}")
                    
                    if file_ext in allowed_extensions:
                        try:
                            # Create upload directory if it doesn't exist
                            # Use backend/static instead of root static
                            upload_dir = os.path.join('backend', 'static', 'uploads', 'market_items')
                            full_upload_dir = os.path.abspath(upload_dir)
                            os.makedirs(full_upload_dir, exist_ok=True)
                            print(f"Photo upload debug - upload directory: {upload_dir}")
                            print(f"Photo upload debug - full upload directory: {full_upload_dir}")
                            print(f"Photo upload debug - current working directory: {os.getcwd()}")
                            
                            # Generate unique filename
                            filename = f"{item_id}_{secure_filename(file.filename)}"
                            file_path = os.path.join(full_upload_dir, filename)
                            print(f"Photo upload debug - saving to: {file_path}")
                            
                            # Save file
                            file.save(file_path)
                            photo_path = f"/static/uploads/market_items/{filename}"
                            print(f"Photo upload debug - photo_path: {photo_path}")
                            
                            # Verify file was saved
                            if os.path.exists(file_path):
                                print(f"Photo upload debug - file saved successfully, size: {os.path.getsize(file_path)} bytes")
                            else:
                                print(f"Photo upload debug - ERROR: file was not saved!")
                        except Exception as upload_error:
                            print(f"Photo upload debug - Exception: {upload_error}")
                            flash(f'Error uploading file: {str(upload_error)}', 'error')
                            db.close()
                            return render_template('market_item_form.html', 
                                                 markets=markets, categories=categories, currencies=currencies,
                                                 item=None, action='add')
                    else:
                        flash('Invalid file type. Please upload PNG, JPG, JPEG, GIF, or WEBP files only.', 'error')
                        db.close()
                        return render_template('market_item_form.html', 
                                             markets=markets, categories=categories, currencies=currencies,
                                             item=None, action='add')
            
            # Collect form data
            item_data = {
                'item_id': item_id,
                'item_name': request.form.get('item_name', '').strip(),
                'market_id': request.form.get('market_id', '').strip() or None,
                'category_id': int(request.form.get('category_id', 0)) or None,
                'description': request.form.get('description', '').strip(),
                'price': float(request.form.get('price', 0)) or 0.0,
                'currency_id': int(request.form.get('currency_id', 1)) or 1,
                'stock_quantity': int(request.form.get('stock_quantity', 0)) or 0,
                'is_available': request.form.get('is_available') == 'on',
                'brand': request.form.get('brand', '').strip(),
                'barcode': request.form.get('barcode', '').strip(),
                'photo_path': photo_path
            }
            
            # Validate required fields
            if not item_data['item_name']:
                flash('Item name is required', 'error')
            elif not item_data['market_id']:
                flash('Market is required', 'error')
            elif not item_data['category_id']:
                flash('Category is required', 'error')
            elif item_data['price'] <= 0:
                flash('Price must be greater than 0', 'error')
            else:
                # Insert the market item
                db.execute(text("""
                    INSERT INTO market_items (
                        item_id, item_name, market_id, category_id, description, 
                        price, currency_id, stock_quantity, is_available, brand, barcode, photo_path
                    ) VALUES (
                        :item_id, :item_name, :market_id, :category_id, :description,
                        :price, :currency_id, :stock_quantity, :is_available, :brand, :barcode, :photo_path
                    )
                """), item_data)
                
                db.commit()
                flash('Market item created successfully!', 'success')
                return redirect(url_for('market_items'))
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        markets = []
        categories = []
        currencies = []
    
    return render_template('market_item_form.html', 
                         markets=markets,
                         categories=categories,
                         currencies=currencies,
                         item=None, 
                         action='add')

@app.route('/market-items/<string:item_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_market_item(item_id):
    """Edit existing market item"""
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Get the market item
        item_result = db.execute(text("""
            SELECT mi.*, m.market_name, mc.category_name, c.company_name
            FROM market_items mi
            LEFT JOIN markets m ON mi.market_id = m.market_id
            LEFT JOIN market_categories mc ON mi.category_id = mc.category_id
            LEFT JOIN companies c ON m.company_id = c.company_id
            WHERE mi.item_id = :item_id
        """), {"item_id": item_id}).fetchone()
        
        if not item_result:
            flash('Market item not found', 'error')
            return redirect(url_for('market_items'))
        
        # Get markets, categories, and currencies for the form (same as add)
        markets_result = db.execute(text("""
            SELECT m.market_id, m.market_name, c.company_name
            FROM markets m
            LEFT JOIN companies c ON m.company_id = c.company_id
            WHERE m.is_active = true
            ORDER BY c.company_name, m.market_name
        """)).fetchall()
        
        categories_result = db.execute(text("""
            SELECT mc.category_id, mc.category_name, m.market_name, m.market_id
            FROM market_categories mc
            LEFT JOIN markets m ON mc.market_id = m.market_id
            ORDER BY m.market_name, mc.category_name
        """)).fetchall()
        
        currencies_result = db.execute(text("""
            SELECT currency_id, currency_code, currency_name
            FROM currencies
            WHERE is_active = true
            ORDER BY currency_code
        """)).fetchall()
        
        # Convert to dictionaries
        markets = [{
            'market_id': str(row.market_id),
            'market_name': row.market_name,
            'company_name': row.company_name or 'No Company'
        } for row in markets_result]
        
        categories = [{
            'category_id': row.category_id,
            'category_name': row.category_name,
            'market_name': row.market_name or 'No Market',
            'market_id': str(row.market_id) if row.market_id else ''
        } for row in categories_result]
        
        currencies = [{
            'currency_id': row.currency_id,
            'currency_code': row.currency_code,
            'currency_name': row.currency_name
        } for row in currencies_result]
        
        if request.method == 'POST':
            # Handle photo upload/update
            photo_path = item_result.photo_path  # Keep existing photo by default
            
            if 'photo' in request.files:
                file = request.files['photo']
                print(f"Edit photo upload debug - file: {file}, filename: {file.filename if file else 'None'}")
                if file and file.filename:
                    from werkzeug.utils import secure_filename
                    import os
                    
                    # Validate file type
                    allowed_extensions = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
                    file_ext = file.filename.rsplit('.', 1)[1].lower() if '.' in file.filename else ''
                    print(f"Edit photo upload debug - file extension: {file_ext}")
                    
                    if file_ext in allowed_extensions:
                        try:
                            # Delete old photo if exists
                            if item_result.photo_path:
                                old_file_path = os.path.join('backend', item_result.photo_path.lstrip('/'))
                                print(f"Edit photo upload debug - deleting old file: {old_file_path}")
                                if os.path.exists(old_file_path):
                                    try:
                                        os.remove(old_file_path)
                                        print(f"Edit photo upload debug - old file deleted successfully")
                                    except OSError as e:
                                        print(f"Edit photo upload debug - error deleting old file: {e}")
                                        pass  # Continue even if deletion fails
                            
                            # Create upload directory if it doesn't exist
                            # Use backend/static instead of root static
                            upload_dir = os.path.join('backend', 'static', 'uploads', 'market_items')
                            full_upload_dir = os.path.abspath(upload_dir)
                            os.makedirs(full_upload_dir, exist_ok=True)
                            print(f"Edit photo upload debug - upload directory: {upload_dir}")
                            print(f"Edit photo upload debug - full upload directory: {full_upload_dir}")
                            print(f"Edit photo upload debug - current working directory: {os.getcwd()}")
                            
                            # Generate unique filename
                            filename = f"{item_id}_{secure_filename(file.filename)}"
                            file_path = os.path.join(full_upload_dir, filename)
                            print(f"Edit photo upload debug - saving to: {file_path}")
                            
                            # Save file
                            file.save(file_path)
                            photo_path = f"/static/uploads/market_items/{filename}"
                            print(f"Edit photo upload debug - photo_path: {photo_path}")
                            
                            # Verify file was saved
                            if os.path.exists(file_path):
                                print(f"Edit photo upload debug - file saved successfully, size: {os.path.getsize(file_path)} bytes")
                            else:
                                print(f"Edit photo upload debug - ERROR: file was not saved!")
                        except Exception as upload_error:
                            print(f"Edit photo upload debug - Exception: {upload_error}")
                            flash(f'Error uploading file: {str(upload_error)}', 'error')
                            db.close()
                            return redirect(url_for('edit_market_item', item_id=item_id))
                    else:
                        flash('Invalid file type. Please upload PNG, JPG, JPEG, GIF, or WEBP files only.', 'error')
                        db.close()
                        return redirect(url_for('edit_market_item', item_id=item_id))
            
            # Handle photo deletion
            if request.form.get('delete_photo') == 'true' and item_result.photo_path:
                import os
                old_file_path = item_result.photo_path.lstrip('/')
                if os.path.exists(old_file_path):
                    try:
                        os.remove(old_file_path)
                    except OSError:
                        pass
                photo_path = None
            
            # Collect form data
            item_data = {
                'item_name': request.form.get('item_name', '').strip(),
                'market_id': request.form.get('market_id', '').strip() or None,
                'category_id': int(request.form.get('category_id', 0)) or None,
                'description': request.form.get('description', '').strip(),
                'price': float(request.form.get('price', 0)) or 0.0,
                'currency_id': int(request.form.get('currency_id', 1)) or 1,
                'stock_quantity': int(request.form.get('stock_quantity', 0)) or 0,
                'is_available': request.form.get('is_available') == 'on',
                'brand': request.form.get('brand', '').strip(),
                'barcode': request.form.get('barcode', '').strip(),
                'photo_path': photo_path
            }
            
            # Validate required fields
            if not item_data['item_name']:
                flash('Item name is required', 'error')
            elif not item_data['market_id']:
                flash('Market is required', 'error')
            elif not item_data['category_id']:
                flash('Category is required', 'error')
            elif item_data['price'] <= 0:
                flash('Price must be greater than 0', 'error')
            else:
                # Update the market item
                db.execute(text("""
                    UPDATE market_items SET
                        item_name = :item_name,
                        market_id = :market_id,
                        category_id = :category_id,
                        description = :description,
                        price = :price,
                        currency_id = :currency_id,
                        stock_quantity = :stock_quantity,
                        is_available = :is_available,
                        brand = :brand,
                        barcode = :barcode,
                        photo_path = :photo_path
                    WHERE item_id = :item_id
                """), {**item_data, 'item_id': item_id})
                
                db.commit()
                flash('Market item updated successfully!', 'success')
                return redirect(url_for('market_items'))
        
        # Convert item data for template
        item = {
            'item_id': str(item_result.item_id),
            'item_name': item_result.item_name,
            'market_id': str(item_result.market_id),
            'category_id': item_result.category_id,
            'description': item_result.description or '',
            'price': float(item_result.price) if item_result.price else 0.0,
            'currency_id': item_result.currency_id,
            'stock_quantity': item_result.stock_quantity or 0,
            'is_available': item_result.is_available,
            'brand': item_result.brand or '',
            'barcode': item_result.barcode or '',
            'photo_path': item_result.photo_path or '',
            'market_name': item_result.market_name,
            'category_name': item_result.category_name,
            'company_name': item_result.company_name
        }
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        return redirect(url_for('market_items'))
    
    return render_template('market_item_form.html', 
                         markets=markets,
                         categories=categories,
                         currencies=currencies,
                         item=item, 
                         action='edit')

@app.route('/market-items/<string:item_id>/delete', methods=['POST'])
@login_required
def delete_market_item(item_id):
    """Delete market item"""
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Check if item exists
        item_exists = db.execute(text("""
            SELECT item_name FROM market_items WHERE item_id = :item_id
        """), {"item_id": item_id}).fetchone()
        
        if not item_exists:
            flash('Market item not found', 'error')
        else:
            # Delete the item
            db.execute(text("DELETE FROM market_items WHERE item_id = :item_id"), {"item_id": item_id})
            db.commit()
            flash(f'Market item "{item_exists.item_name}" deleted successfully!', 'success')
        
        db.close()
        
    except Exception as e:
        flash(f'Error deleting market item: {str(e)}', 'error')
    
    return redirect(url_for('market_items'))

# Adventures Management Routes
@app.route('/adventures')
@login_required
def adventures():
    """Adventures management page"""
    try:
        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()
        
        # Check if adventures table exists
        table_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'adventures'
            )
        """)).fetchone()[0]
        
        adventures_data = []
        if table_exists:
            # Get all adventures with company and beach info
            adventures_result = db.execute(text("""
                SELECT a.adventure_id, a.adventure_name, a.description,
                       a.duration_minutes, a.max_participants, a.min_participants,
                       a.price, a.is_active, a.created_at,
                       c.company_name, bp.beach_name, cur.currency_symbol
                FROM adventures a
                LEFT JOIN companies c ON a.company_id = c.company_id
                LEFT JOIN beach_places bp ON a.beach_place_id = bp.beach_place_id
                LEFT JOIN currencies cur ON a.currency_id = cur.currency_id
                ORDER BY a.adventure_name
            """)).fetchall()
            
            for adventure in adventures_result:
                duration = f"{adventure.duration_minutes} min" if adventure.duration_minutes else 'N/A'
                participants = f"{adventure.min_participants}-{adventure.max_participants}" if adventure.min_participants and adventure.max_participants else 'N/A'
                price = f"{adventure.price}{adventure.currency_symbol or '€'}" if adventure.price else 'N/A'
                
                adventures_data.append({
                    'id': adventure.adventure_id,
                    'name': adventure.adventure_name,
                    'company': adventure.company_name or 'No Company',
                    'beach': adventure.beach_name or 'No Beach',
                    'duration': duration,
                    'participants': participants,
                    'price': price,
                    'status': 'Active' if adventure.is_active else 'Inactive',
                    'created_at': adventure.created_at.strftime('%Y-%m-%d') if adventure.created_at else 'N/A'
                })
        
        db.close()
        
        if not adventures_data:
            flash('No adventures found. The adventures table may be empty or not exist yet.', 'info')
        
    except Exception as e:
        flash(f'Error loading adventures: {str(e)}', 'error')
        adventures_data = []
    
    return render_template('adventures.html', adventures=adventures_data)

@app.route('/adventures/add', methods=['GET', 'POST'])
@login_required
def add_adventure():
    """Add new adventure"""
    try:
        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()
        
        # Get companies, beach places, and currencies for the form
        companies_result = db.execute(text("""
            SELECT company_id, company_name 
            FROM companies 
            WHERE company_status = 'approved'
            ORDER BY company_name
        """)).fetchall()
        
        beach_places_result = db.execute(text("""
            SELECT bp.beach_place_id, bp.beach_name, c.company_name
            FROM beach_places bp
            LEFT JOIN companies c ON bp.company_id = c.company_id
            WHERE bp.enable_beach = true
            ORDER BY c.company_name, bp.beach_name
        """)).fetchall()
        
        currencies_result = db.execute(text("""
            SELECT currency_id, currency_name, currency_symbol
            FROM currencies 
            WHERE is_active = true
            ORDER BY currency_name
        """)).fetchall()
        
        # Convert Row objects to dictionaries for JSON serialization
        companies = [{
            'company_id': str(row.company_id),
            'company_name': row.company_name
        } for row in companies_result]
        
        beach_places = [{
            'beach_place_id': str(row.beach_place_id),
            'beach_name': row.beach_name,
            'company_name': row.company_name
        } for row in beach_places_result]
        
        currencies = [{
            'currency_id': row.currency_id,
            'currency_name': row.currency_name,
            'currency_symbol': row.currency_symbol
        } for row in currencies_result]
        
        if request.method == 'POST':
            # Collect form data
            adventure_data = {
                'adventure_name': request.form.get('adventure_name', '').strip(),
                'company_id': request.form.get('company_id', '').strip() or None,  # UUID as string
                'beach_place_id': request.form.get('beach_place_id', '').strip() or None,  # UUID as string
                'description': request.form.get('description', '').strip(),
                'duration_minutes': int(request.form.get('duration_minutes', 0) or 0) if request.form.get('duration_minutes') else None,
                'max_participants': int(request.form.get('max_participants', 0) or 0) if request.form.get('max_participants') else None,
                'min_participants': int(request.form.get('min_participants', 1) or 1),
                'price': float(request.form.get('price', 0) or 0),
                'currency_id': int(request.form.get('currency_id', 0) or 0) if request.form.get('currency_id') else None,
                'equipment_provided': request.form.get('equipment_provided', '').strip(),
                'requirements': request.form.get('requirements', '').strip(),
                'safety_instructions': request.form.get('safety_instructions', '').strip(),
                'is_active': request.form.get('is_active') == 'on'
            }
            
            # Validate required fields
            if not adventure_data['adventure_name']:
                flash('Adventure name is required', 'error')
            elif not adventure_data['company_id']:
                flash('Company is required', 'error')
            elif adventure_data['price'] <= 0:
                flash('Price must be greater than 0', 'error')
            elif not adventure_data['currency_id']:
                flash('Currency is required', 'error')
            else:
                # Insert the adventure
                result = db.execute(text("""
                    INSERT INTO adventures (
                        adventure_name, company_id, beach_place_id, description,
                        duration_minutes, max_participants, min_participants, price, currency_id,
                        equipment_provided, requirements, safety_instructions, is_active, created_at
                    ) VALUES (
                        :adventure_name, :company_id, :beach_place_id, :description,
                        :duration_minutes, :max_participants, :min_participants, :price, :currency_id,
                        :equipment_provided, :requirements, :safety_instructions, :is_active, NOW()
                    ) RETURNING adventure_id
                """), adventure_data)
                
                adventure_id = result.fetchone()[0]
                db.commit()
                
                if adventure_id:
                    flash('Adventure created successfully!', 'success')
                    return redirect(url_for('adventures'))
                else:
                    flash('Error creating adventure', 'error')
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        companies = []
        beach_places = []
        currencies = []
    
    return render_template('adventure_form.html', 
                         companies=companies,
                         beach_places=beach_places,
                         currencies=currencies,
                         adventure=None, 
                         action='add')

@app.route('/adventures/<string:adventure_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_adventure(adventure_id):
    """Edit existing adventure"""
    try:
        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()
        
        # Get the adventure
        adventure_result = db.execute(text("""
            SELECT a.*, c.company_name, bp.beach_name, cur.currency_name
            FROM adventures a
            LEFT JOIN companies c ON a.company_id = c.company_id
            LEFT JOIN beach_places bp ON a.beach_place_id = bp.beach_place_id
            LEFT JOIN currencies cur ON a.currency_id = cur.currency_id
            WHERE a.adventure_id = :adventure_id
        """), {"adventure_id": adventure_id}).fetchone()
        
        if not adventure_result:
            flash('Adventure not found', 'error')
            return redirect(url_for('adventures'))
        
        # Get companies, beach places, and currencies for the form
        companies_result = db.execute(text("""
            SELECT company_id, company_name 
            FROM companies 
            WHERE company_status = 'approved'
            ORDER BY company_name
        """)).fetchall()
        
        beach_places_result = db.execute(text("""
            SELECT bp.beach_place_id, bp.beach_name, c.company_name
            FROM beach_places bp
            LEFT JOIN companies c ON bp.company_id = c.company_id
            WHERE bp.enable_beach = true
            ORDER BY c.company_name, bp.beach_name
        """)).fetchall()
        
        currencies_result = db.execute(text("""
            SELECT currency_id, currency_name, currency_symbol
            FROM currencies 
            WHERE is_active = true
            ORDER BY currency_name
        """)).fetchall()
        
        # Convert Row objects to dictionaries for JSON serialization
        companies = [{
            'company_id': str(row.company_id),
            'company_name': row.company_name
        } for row in companies_result]
        
        beach_places = [{
            'beach_place_id': str(row.beach_place_id),
            'beach_name': row.beach_name,
            'company_name': row.company_name
        } for row in beach_places_result]
        
        currencies = [{
            'currency_id': row.currency_id,
            'currency_name': row.currency_name,
            'currency_symbol': row.currency_symbol
        } for row in currencies_result]
        
        if request.method == 'POST':
            # Collect form data
            adventure_data = {
                'adventure_name': request.form.get('adventure_name', '').strip(),
                'company_id': request.form.get('company_id', '').strip() or None,  # UUID as string
                'beach_place_id': request.form.get('beach_place_id', '').strip() or None,  # UUID as string
                'description': request.form.get('description', '').strip(),
                'duration_minutes': int(request.form.get('duration_minutes', 0) or 0) if request.form.get('duration_minutes') else None,
                'max_participants': int(request.form.get('max_participants', 0) or 0) if request.form.get('max_participants') else None,
                'min_participants': int(request.form.get('min_participants', 1) or 1),
                'price': float(request.form.get('price', 0) or 0),
                'currency_id': int(request.form.get('currency_id', 0) or 0) if request.form.get('currency_id') else None,
                'equipment_provided': request.form.get('equipment_provided', '').strip(),
                'requirements': request.form.get('requirements', '').strip(),
                'safety_instructions': request.form.get('safety_instructions', '').strip(),
                'is_active': request.form.get('is_active') == 'on'
            }
            
            # Validate required fields
            if not adventure_data['adventure_name']:
                flash('Adventure name is required', 'error')
            elif not adventure_data['company_id']:
                flash('Company is required', 'error')
            elif adventure_data['price'] <= 0:
                flash('Price must be greater than 0', 'error')
            elif not adventure_data['currency_id']:
                flash('Currency is required', 'error')
            else:
                # Update the adventure
                db.execute(text("""
                    UPDATE adventures SET
                        adventure_name = :adventure_name,
                        company_id = :company_id,
                        beach_place_id = :beach_place_id,
                        description = :description,
                        duration_minutes = :duration_minutes,
                        max_participants = :max_participants,
                        min_participants = :min_participants,
                        price = :price,
                        currency_id = :currency_id,
                        equipment_provided = :equipment_provided,
                        requirements = :requirements,
                        safety_instructions = :safety_instructions,
                        is_active = :is_active
                    WHERE adventure_id = :adventure_id
                """), {**adventure_data, 'adventure_id': adventure_id})
                
                db.commit()
                flash('Adventure updated successfully!', 'success')
                return redirect(url_for('adventures'))
        
        db.close()
        
    except Exception as e:
        flash(f'Error: {str(e)}', 'error')
        return redirect(url_for('adventures'))
    
    return render_template('adventure_form.html', 
                         companies=companies,
                         beach_places=beach_places,
                         currencies=currencies,
                         adventure=adventure_result, 
                         action='edit')

@app.route('/adventures/<string:adventure_id>/delete', methods=['POST'])
@login_required
def delete_adventure(adventure_id):
    """Delete adventure"""
    try:
        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()
        
        # Delete the adventure
        db.execute(text("""
            DELETE FROM adventures 
            WHERE adventure_id = :adventure_id
        """), {"adventure_id": adventure_id})
        
        db.commit()
        flash('Adventure deleted successfully!', 'success')
        
        db.close()
        
    except Exception as e:
        flash(f'Error deleting adventure: {str(e)}', 'error')
    
    return redirect(url_for('adventures'))

@app.route('/bookings')
@login_required
def bookings():
    """Manage bookings"""
    # Get real bookings from database
    try:
        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()
        
        # Check if bookings table exists
        table_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'bookings'
            )
        """)).fetchone()[0]
        
        bookings_data = []
        if table_exists:
            # Get all bookings with user and beach info
            bookings_result = db.execute(text("""
                SELECT bk.booking_id, 
                       CONCAT(u.first_name, ' ', u.last_name) as user_name,
                       bp.beach_name,
                       bk.booking_date, bk.start_time, bk.end_time,
                       bk.status, bk.total_price
                FROM bookings bk
                LEFT JOIN users u ON bk.user_id = u.user_id
                LEFT JOIN beach_places bp ON bk.beach_place_id = bp.beach_place_id
                ORDER BY bk.booking_date DESC, bk.start_time DESC
                LIMIT 100
            """)).fetchall()
            
            for booking in bookings_result:
                time_range = 'N/A'
                if booking.start_time and booking.end_time:
                    time_range = f"{booking.start_time} - {booking.end_time}"
                
                bookings_data.append({
                    'id': booking.booking_id,
                    'user': booking.user_name or 'Unknown User',
                    'beach': booking.beach_name or 'Unknown Beach',
                    'date': booking.booking_date.strftime('%Y-%m-%d') if booking.booking_date else 'N/A',
                    'time': time_range,
                    'status': booking.status or 'Unknown',
                    'amount': f'€{booking.total_price:.2f}' if booking.total_price else 'N/A'
                })
        
        db.close()
        
        if not bookings_data:
            # Show message if no bookings found
            flash('No bookings found. The bookings table may be empty or not exist yet.', 'info')
        
    except Exception as e:
        flash(f'Error loading bookings: {str(e)}', 'error')
        bookings_data = []
    
    return render_template('bookings.html', bookings=bookings_data)

@app.route('/settings')
@login_required
def settings():
    """System settings"""
    # Get real settings from database if available
    try:
        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()
        
        # Check if settings table exists
        table_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'system_settings'
            )
        """)).fetchone()[0]
        
        settings_data = {
            'site_name': 'BookBeach',
            'default_currency': 'EUR',
            'default_language': 'en',
            'platform_commission': '5.0',
            'vat_percentage': '24.0',
            'maintenance_mode': False,
            'company_approval_required': True
        }
        
        if table_exists:
            # Load settings from database
            settings_result = db.execute(text("""
                SELECT setting_key, setting_value, setting_type
                FROM system_settings
                WHERE is_active = true
            """)).fetchall()
            
            for setting in settings_result:
                key = setting.setting_key
                value = setting.setting_value
                
                # Convert based on type
                if setting.setting_type == 'boolean':
                    value = value.lower() in ('true', '1', 'yes')
                elif setting.setting_type == 'number':
                    value = float(value) if '.' in value else int(value)
                
                settings_data[key] = value
        
        db.close()
        
    except Exception as e:
        flash(f'Error loading settings: {str(e)}', 'warning')
        # Use default settings on error
        settings_data = {
            'site_name': 'BookBeach',
            'default_currency': 'EUR',
            'default_language': 'en',
            'platform_commission': '5.0',
            'vat_percentage': '24.0',
            'maintenance_mode': False,
            'company_approval_required': True
        }
    
    return render_template('settings.html', settings=settings_data)

@app.route('/settings', methods=['POST'])
@login_required
def update_settings():
    """Update system settings"""
    # TODO: Implement actual settings update
    flash('Settings updated successfully!', 'success')
    return redirect(url_for('settings'))

@app.route('/reports')
@login_required
def reports():
    """View reports and analytics"""
    # Get real reports data from database
    try:
        from sqlalchemy import create_engine, text
        from sqlalchemy.orm import sessionmaker
        from datetime import datetime, timedelta
        
        # Database connection
        DATABASE_URL = ADMIN_CONFIG['DATABASE_URL']
        engine = create_engine(DATABASE_URL)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        db = SessionLocal()
        
        # Initialize reports data
        reports_data = {
            'revenue': {
                'today': 0.00,
                'this_week': 0.00,
                'this_month': 0.00,
                'this_year': 0.00
            },
            'bookings': {
                'today': 0,
                'this_week': 0,
                'this_month': 0,
                'this_year': 0
            },
            'top_beaches': []
        }
        
        # Check if required tables exist
        bookings_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' AND table_name = 'bookings'
            )
        """)).fetchone()[0]
        
        beaches_exists = db.execute(text("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' AND table_name = 'beaches'
            )
        """)).fetchone()[0]
        
        if bookings_exists:
            today = datetime.now().date()
            week_start = today - timedelta(days=today.weekday())
            month_start = today.replace(day=1)
            year_start = today.replace(month=1, day=1)
            
            # Revenue calculations
            revenue_queries = {
                'today': f"booking_date = '{today}'",
                'this_week': f"booking_date >= '{week_start}'",
                'this_month': f"booking_date >= '{month_start}'",
                'this_year': f"booking_date >= '{year_start}'"
            }
            
            for period, condition in revenue_queries.items():
                result = db.execute(text(f"""
                    SELECT COALESCE(SUM(total_amount), 0) as revenue,
                           COUNT(*) as count
                    FROM bookings 
                    WHERE {condition}
                    AND booking_status IN ('confirmed', 'completed')
                """)).fetchone()
                
                reports_data['revenue'][period] = float(result.revenue or 0)
                reports_data['bookings'][period] = int(result.count or 0)
        
        # Top beaches
        if bookings_exists and beaches_exists:
            top_beaches_result = db.execute(text("""
                SELECT b.beach_name, COUNT(bk.booking_id) as booking_count
                FROM beaches b
                LEFT JOIN bookings bk ON b.beach_id = bk.beach_id
                WHERE bk.booking_status IN ('confirmed', 'completed')
                GROUP BY b.beach_id, b.beach_name
                ORDER BY booking_count DESC
                LIMIT 5
            """)).fetchall()
            
            reports_data['top_beaches'] = [
                {'name': beach.beach_name, 'bookings': beach.booking_count}
                for beach in top_beaches_result
            ]
        
        db.close()
        
    except Exception as e:
        flash(f'Error loading reports: {str(e)}', 'error')
        # Fallback to default empty data
        reports_data = {
            'revenue': {
                'today': 0.00,
                'this_week': 0.00,
                'this_month': 0.00,
                'this_year': 0.00
            },
            'bookings': {
                'today': 0,
                'this_week': 0,
                'this_month': 0,
                'this_year': 0
            },
            'top_beaches': []
        }
    
    return render_template('reports.html', reports=reports_data)

@app.route('/encryption', methods=['GET', 'POST'])
@login_required
def encryption():
    """Encryption/Decryption tool"""
    result = None
    error_message = None
    
    if request.method == 'POST':
        action = request.form.get('action')
        text_input = request.form.get('text_input', '').strip()
        key_phrase = request.form.get('key_phrase', 'babagamma').strip()
        
        if not text_input:
            error_message = "Please enter text to encrypt or decrypt"
        elif not key_phrase:
            error_message = "Please enter a key phrase"
        else:
            try:
                if action == 'encrypt':
                    from app.utils.encryption import encrypt_password
                    result = encrypt_password(text_input, key_phrase)
                    flash(f'Text encrypted successfully!', 'success')
                elif action == 'decrypt':
                    from app.utils.encryption import decrypt_password
                    result = decrypt_password(text_input, key_phrase)
                    flash(f'Text decrypted successfully!', 'success')
                else:
                    error_message = "Invalid action specified"
            except Exception as e:
                error_message = f"Operation failed: {str(e)}"
    
    return render_template('encryption.html', 
                         result=result, 
                         error_message=error_message,
                         text_input=request.form.get('text_input', '') if request.method == 'POST' else '',
                         key_phrase=request.form.get('key_phrase', 'babagamma') if request.method == 'POST' else 'babagamma')

@app.route('/terrain-types')
@login_required
def terrain_types():
    """Manage Beach Terrain Types"""
    if not TerrainTypeService:
        flash('Terrain service not available', 'error')
        return redirect(url_for('dashboard'))
    
    with TerrainTypeService() as service:
        terrain_types_data = service.get_all_terrain_types()
    
    return render_template('terrain_types.html', terrain_types=terrain_types_data)

@app.route('/terrain-types/add', methods=['GET', 'POST'])
@login_required
def add_terrain_type():
    """Add new terrain type"""
    if not TerrainTypeService:
        flash('Terrain service not available', 'error')
        return redirect(url_for('terrain_types'))
    
    if request.method == 'POST':
        terrain_name = request.form.get('terrain_name', '').strip()
        description = request.form.get('description', '').strip()
        
        if not terrain_name:
            flash('Terrain name is required', 'error')
        else:
            with TerrainTypeService() as service:
                # First create the terrain type without photo
                success = service.create_terrain_type(terrain_name, description)
                
                if success:
                    # Get the newly created terrain type ID
                    terrain_types = service.get_all_terrain_types()
                    new_terrain = None
                    for terrain in terrain_types:
                        if terrain['terrain_name'] == terrain_name:
                            new_terrain = terrain
                            break
                    
                    # Handle photo upload if provided
                    photo_path = None
                    if 'photo' in request.files and request.files['photo'].filename:
                        photo_path = save_uploaded_file(request.files['photo'], new_terrain['terrain_type_id'])
                        
                        if photo_path:
                            # Update terrain type with photo path
                            service.update_terrain_type(
                                new_terrain['terrain_type_id'],
                                terrain_name,
                                description,
                                photo_path
                            )
                    
                    flash('Terrain type added successfully!', 'success')
                    return redirect(url_for('terrain_types'))
                else:
                    flash('Error adding terrain type', 'error')
    
    return render_template('terrain_types.html', terrain_types=[], add_mode=True)

@app.route('/terrain-types/edit/<int:terrain_id>', methods=['GET', 'POST'])
@login_required
def edit_terrain_type(terrain_id):
    """Edit existing terrain type"""
    if not TerrainTypeService:
        flash('Terrain service not available', 'error')
        return redirect(url_for('terrain_types'))
    
    with TerrainTypeService() as service:
        terrain_type = service.get_terrain_type_by_id(terrain_id)
        
        if not terrain_type:
            flash('Terrain type not found', 'error')
            return redirect(url_for('terrain_types'))
        
        if request.method == 'POST':
            terrain_name = request.form.get('terrain_name', '').strip()
            description = request.form.get('description', '').strip()
            
            if not terrain_name:
                flash('Terrain name is required', 'error')
            else:
                # Handle photo upload if provided
                photo_path = terrain_type['photo_path']  # Keep existing photo by default
                
                if 'photo' in request.files and request.files['photo'].filename:
                    new_photo_path = save_uploaded_file(request.files['photo'], terrain_id)
                    if new_photo_path:
                        photo_path = new_photo_path
                
                success = service.update_terrain_type(terrain_id, terrain_name, description, photo_path)
                
                if success:
                    flash('Terrain type updated successfully!', 'success')
                    return redirect(url_for('terrain_types'))
                else:
                    flash('Error updating terrain type', 'error')
        
        terrain_types_data = service.get_all_terrain_types()
    
    return render_template('terrain_types.html', 
                         terrain_types=terrain_types_data, 
                         edit_terrain=terrain_type)

@app.route('/terrain-types/delete/<int:terrain_id>', methods=['POST'])
@login_required
def delete_terrain_type(terrain_id):
    """Delete terrain type"""
    if not TerrainTypeService:
        flash('Terrain service not available', 'error')
        return redirect(url_for('terrain_types'))
    
    with TerrainTypeService() as service:
        usage_count = service.get_terrain_type_usage_count(terrain_id)
        
        if usage_count > 0:
            flash(f'Cannot delete terrain type. It is used by {usage_count} beach place(s).', 'error')
        else:
            success = service.delete_terrain_type(terrain_id)
            
            if success:
                flash('Terrain type deleted successfully!', 'success')
            else:
                flash('Error deleting terrain type', 'error')
    
    return redirect(url_for('terrain_types'))

# Companies Management Routes
@app.route('/companies')
@login_required
def companies():
    """Companies search and listing page"""
    if not CompanyService:
        flash('Companies service not available', 'error')
        return redirect(url_for('dashboard'))
    
    # Get search parameters
    search_term = request.args.get('search', '')
    company_status = request.args.get('status', '')
    country_id = request.args.get('country_id', type=int)
    page = request.args.get('page', 1, type=int)
    per_page = 10
    
    with CompanyService() as service:
        companies_data, total_count = service.search_companies(
            search_term=search_term,
            company_status=company_status,
            country_id=country_id,
            page=page,
            per_page=per_page
        )
        countries = service.get_countries()
    
    # Calculate pagination
    total_pages = (total_count + per_page - 1) // per_page
    has_prev = page > 1
    has_next = page < total_pages
    prev_num = page - 1 if has_prev else None
    next_num = page + 1 if has_next else None
    
    return render_template('companies.html', 
                         companies=companies_data,
                         countries=countries,
                         search_term=search_term,
                         company_status=company_status,
                         selected_country_id=country_id,
                         page=page,
                         total_pages=total_pages,
                         total_count=total_count,
                         has_prev=has_prev,
                         has_next=has_next,
                         prev_num=prev_num,
                         next_num=next_num)

@app.route('/companies/add', methods=['GET', 'POST'])
@login_required
def add_company():
    """Add new company"""
    if not CompanyService:
        flash('Companies service not available', 'error')
        return redirect(url_for('companies'))
    
    with CompanyService() as service:
        countries = service.get_countries()
        
        if request.method == 'POST':
            # Collect form data
            company_data = {
                'company_name': request.form.get('company_name', '').strip(),
                'address': request.form.get('address', '').strip(),
                'country_id': request.form.get('country_id', type=int),
                'province': request.form.get('province', '').strip(),
                'city': request.form.get('city', '').strip(),
                'postal_code': request.form.get('postal_code', '').strip(),
                'phone': request.form.get('phone', '').strip(),
                'mobile': request.form.get('mobile', '').strip(),
                'fax': request.form.get('fax', '').strip(),
                'email': request.form.get('email', '').strip(),
                'registration_number': request.form.get('registration_number', '').strip(),
                'vat_number': request.form.get('vat_number', '').strip(),
                'tax_office': request.form.get('tax_office', '').strip(),
                'website': request.form.get('website', '').strip(),
                'remarks': request.form.get('remarks', '').strip(),
                'company_status': request.form.get('company_status', 'pending'),
                'send_time_reports': request.form.get('send_time_reports', '09:00:00'),
                'company_logo_path': None
            }
            
            # Validate required fields
            if not company_data['company_name']:
                flash('Company name is required', 'error')
            elif not company_data['email']:
                flash('Email is required', 'error')
            elif not company_data['phone']:
                flash('Phone is required', 'error')
            else:
                # Create the company
                company_id = service.create_company(company_data)
                
                if company_id:
                    # Handle logo upload if provided
                    print(f"Debug: Checking for logo upload in request.files: {list(request.files.keys())}")
                    if 'logo' in request.files:
                        logo_file = request.files['logo']
                        print(f"Debug: Logo file found - filename: {logo_file.filename}, content_type: {getattr(logo_file, 'content_type', 'unknown')}")
                        if logo_file.filename:
                            logo_path = save_company_logo(logo_file, company_id)
                            print(f"Debug: Logo save result: {logo_path}")
                            if logo_path:
                                # Update company with logo path
                                company_data['company_logo_path'] = logo_path
                                service.update_company(company_id, company_data)
                                print(f"Debug: Company updated with logo path: {logo_path}")
                        else:
                            print("Debug: Logo file has no filename")
                    else:
                        print("Debug: No 'logo' key found in request.files")
                    
                    flash('Company created successfully!', 'success')
                    return redirect(url_for('company_details', company_id=company_id))
                else:
                    flash('Error creating company', 'error')
    
    return render_template('company_form.html', 
                         countries=countries, 
                         company=None, 
                         action='add')

@app.route('/companies/<company_id>')
@login_required
def company_details(company_id):
    """Company details with tabs"""
    if not CompanyService:
        flash('Companies service not available', 'error')
        return redirect(url_for('companies'))
    
    tab = request.args.get('tab', 'details')
    
    with CompanyService() as service:
        company = service.get_company_by_id(company_id)
        
        if not company:
            flash('Company not found', 'error')
            return redirect(url_for('companies'))
        
        # Load data based on active tab
        tab_data = {}
        if tab == 'beaches':
            tab_data['beaches'] = service.get_company_beaches(company_id)
        elif tab == 'restaurants':
            tab_data['restaurants'] = service.get_company_restaurants(company_id)
        elif tab == 'markets':
            tab_data['markets'] = service.get_company_markets(company_id)
        elif tab == 'adventures':
            tab_data['adventures'] = service.get_company_adventures(company_id)
    
    return render_template('company_details.html', 
                         company=company, 
                         active_tab=tab, 
                         tab_data=tab_data)

@app.route('/companies/<company_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_company(company_id):
    """Edit existing company"""
    if not CompanyService:
        flash('Companies service not available', 'error')
        return redirect(url_for('companies'))
    
    with CompanyService() as service:
        company = service.get_company_by_id(company_id)
        countries = service.get_countries()
        
        if not company:
            flash('Company not found', 'error')
            return redirect(url_for('companies'))
        
        if request.method == 'POST':
            # Collect form data
            company_data = {
                'company_name': request.form.get('company_name', '').strip(),
                'address': request.form.get('address', '').strip(),
                'country_id': request.form.get('country_id', type=int),
                'province': request.form.get('province', '').strip(),
                'city': request.form.get('city', '').strip(),
                'postal_code': request.form.get('postal_code', '').strip(),
                'phone': request.form.get('phone', '').strip(),
                'mobile': request.form.get('mobile', '').strip(),
                'fax': request.form.get('fax', '').strip(),
                'email': request.form.get('email', '').strip(),
                'registration_number': request.form.get('registration_number', '').strip(),
                'vat_number': request.form.get('vat_number', '').strip(),
                'tax_office': request.form.get('tax_office', '').strip(),
                'website': request.form.get('website', '').strip(),
                'remarks': request.form.get('remarks', '').strip(),
                'company_status': request.form.get('company_status', 'pending'),
                'send_time_reports': request.form.get('send_time_reports', '09:00:00'),
                'company_logo_path': company['company_logo_path']  # Keep existing logo by default
            }
            
            # Validate required fields
            if not company_data['company_name']:
                flash('Company name is required', 'error')
            elif not company_data['email']:
                flash('Email is required', 'error')
            elif not company_data['phone']:
                flash('Phone is required', 'error')
            else:
                # Handle logo upload if provided
                print(f"Debug: Checking for logo upload in edit form - request.files: {list(request.files.keys())}")
                if 'logo' in request.files:
                    logo_file = request.files['logo']
                    print(f"Debug: Edit - Logo file found - filename: {logo_file.filename}")
                    if logo_file.filename:
                        new_logo_path = save_company_logo(logo_file, company_id)
                        print(f"Debug: Edit - Logo save result: {new_logo_path}")
                        if new_logo_path:
                            company_data['company_logo_path'] = new_logo_path
                            print(f"Debug: Edit - Company will be updated with logo path: {new_logo_path}")
                    else:
                        print("Debug: Edit - Logo file has no filename")
                else:
                    print("Debug: Edit - No 'logo' key found in request.files")
                
                success = service.update_company(company_id, company_data)
                
                if success:
                    flash('Company updated successfully!', 'success')
                    return redirect(url_for('company_details', company_id=company_id))
                else:
                    flash('Error updating company', 'error')
    
    return render_template('company_form.html', 
                         countries=countries, 
                         company=company, 
                         action='edit')

@app.route('/companies/<company_id>/delete', methods=['POST'])
@login_required
def delete_company(company_id):
    """Delete company"""
    if not CompanyService:
        flash('Companies service not available', 'error')
        return redirect(url_for('companies'))
    
    with CompanyService() as service:
        success = service.delete_company(company_id)
        
        if success:
            flash('Company deleted successfully!', 'success')
        else:
            flash('Cannot delete company. It has related data (beaches, restaurants, etc.)', 'error')
    
    return redirect(url_for('companies'))

# Beach Layout API Endpoints
@app.route('/WSTJWeb', methods=['POST'])
def handle_stored_procedure():
    """Handle encrypted stored procedure calls from beach designer"""

    try:
        from utils.http.encrypt import Decrypt
        data = request.get_json()
        
        if not data or 'reg' not in data:
            return jsonify({'status': '0', 'message': 'Invalid request format'}), 400
        
        # Decrypt the request
        try:
            decrypted_data = Decrypt(data['reg'])
            sp_name = decrypted_data.get('SP')
            parameters = decrypted_data.get('P', {})
        except Exception as e:
            return jsonify({'status': '0', 'message': 'Decryption failed'}), 400
        
        # Route to appropriate handler based on stored procedure name
        if sp_name == 'APPBB_UpdateCompaniesBeachPlaceTerrains':
            return handle_update_terrain(parameters)
        elif sp_name == 'APPBB_DeleteCompaniesBeachPlaceTerrains':
            return handle_delete_terrain(parameters)
        elif sp_name == 'APPBB_GetCompaniesBeachPlaceTerrains':
            return handle_get_terrains(parameters)
        elif sp_name == 'APPBB_GetSingleCompaniesBeachPlaceTerrains':
            return handle_get_single_terrain(parameters)
        else:
            return jsonify({'status': '0', 'message': f'Unknown stored procedure: {sp_name}'}), 400
            
    except Exception as e:
        return jsonify({'status': '0', 'message': f'Server error: {str(e)}'}), 500

def handle_update_terrain(params):
    """Handle terrain update/insert operations"""
    
    def rgb_to_hex(color):
        """Convert RGB color to hex format"""
        if not color or color in ['transparent', 'inherit']:
            return '#FFFFFF'
        
        # Clean up the input
        color = str(color).strip()
        
        # If already in hex format, return as is
        if color.startswith('#'):
            return color if len(color) == 7 else '#FFFFFF'
        
        # Handle rgb() format
        import re
        rgb_match = re.match(r'rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)', color)
        if rgb_match:
            r = int(rgb_match.group(1))
            g = int(rgb_match.group(2))
            b = int(rgb_match.group(3))
            return '#{:02x}{:02x}{:02x}'.format(r, g, b)
        
        # Handle rgba() format
        rgba_match = re.match(r'rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*[\d.]+\s*\)', color)
        if rgba_match:
            r = int(rgba_match.group(1))
            g = int(rgba_match.group(2))
            b = int(rgba_match.group(3))
            return '#{:02x}{:02x}{:02x}'.format(r, g, b)
        
        # Default fallback
        return '#FFFFFF'
    
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            terrain_id = params.get('CompaniesBeachPlaceTerrainID')
            
            if terrain_id and terrain_id != '00000000-0000-0000-0000-000000000000':
                # Update existing terrain
                db.execute(text("""
                    UPDATE beach_place_terrains SET
                        uid = :uid,
                        angle = :angle,
                        background_color = :background_color,
                        bed_reference = :bed_reference,
                        block_online = :block_online,
                        classification = :classification,
                        covers = :covers,
                        description = :description,
                        description_text = :description_text,
                        description_text_position = :description_text_position,
                        height = :height,
                        left_position = :left_position,
                        bed_price = :bed_price,
                        min_price = :min_price,
                        name = :name,
                        top_position = :top_position,
                        width = :width
                    WHERE terrain_id = :terrain_id
                """), {
                    'terrain_id': terrain_id,
                    'uid': params.get('uid', 0),
                    'angle': params.get('angle', 0),
                    'background_color': rgb_to_hex(params.get('backgroundColor', '#FFFFFF')),
                    'bed_reference': params.get('bedReference', ''),
                    'block_online': bool(params.get('blockOnline', False)),
                    'classification': params.get('classification', 0),
                    'covers': params.get('covers', ''),
                    'description': params.get('description', ''),
                    'description_text': params.get('descriptionText', ''),
                    'description_text_position': params.get('descriptionTextPosition', ''),
                    'height': float(params.get('height', 40)),
                    'left_position': float(params.get('left', 0)),
                    'bed_price': float(params.get('bedPrice', 0)),
                    'min_price': float(params.get('minPrice', 0)),
                    'name': params.get('name', ''),
                    'top_position': float(params.get('top', 0)),
                    'width': float(params.get('width', 60))
                })
            else:
                # Insert new terrain
                from uuid import uuid4
                new_terrain_id = str(uuid4())
                
                db.execute(text("""
                    INSERT INTO beach_place_terrains (
                        terrain_id, uid, beach_place_id, angle, background_color,
                        bed_reference, block_online, classification, covers,
                        description, description_text, description_text_position,
                        height, left_position, bed_price, min_price, name,
                        top_position, width, z_index, is_layout
                    ) VALUES (
                        :terrain_id, :uid, :beach_place_id, :angle, :background_color,
                        :bed_reference, :block_online, :classification, :covers,
                        :description, :description_text, :description_text_position,
                        :height, :left_position, :bed_price, :min_price, :name,
                        :top_position, :width, 0, false
                    )
                """), {
                    'terrain_id': new_terrain_id,
                    'uid': params.get('uid', 0),
                    'beach_place_id': params.get('CompanyBeachPlaceID', 0),
                    'angle': params.get('angle', 0),
                    'background_color': rgb_to_hex(params.get('backgroundColor', '#FFFFFF')),
                    'bed_reference': params.get('bedReference', ''),
                    'block_online': bool(params.get('blockOnline', False)),
                    'classification': params.get('classification', 0),
                    'covers': params.get('covers', ''),
                    'description': params.get('description', ''),
                    'description_text': params.get('descriptionText', ''),
                    'description_text_position': params.get('descriptionTextPosition', ''),
                    'height': float(params.get('height', 40)),
                    'left_position': float(params.get('left', 0)),
                    'bed_price': float(params.get('bedPrice', 0)),
                    'min_price': float(params.get('minPrice', 0)),
                    'name': params.get('name', ''),
                    'top_position': float(params.get('top', 0)),
                    'width': float(params.get('width', 60))
                })
                
                # Update the terrain_id in the response
                terrain_id = new_terrain_id
            
            db.commit()
            
            return jsonify({
                'status': '1',
                'message': 'Terrain updated successfully',
                'results': [{'CompaniesBeachPlaceTerrainID': terrain_id}]
            })
            
    except Exception as e:
        return jsonify({'status': '0', 'message': f'Update failed: {str(e)}'})

def handle_delete_terrain(params):
    """Handle terrain deletion"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            terrain_id = params.get('CompaniesBeachPlaceTerrainID')
            
            if not terrain_id:
                return jsonify({'status': '0', 'message': 'Terrain ID required'})
            
            db.execute(text("""
                DELETE FROM beach_place_terrains WHERE terrain_id = :terrain_id
            """), {'terrain_id': terrain_id})
            
            db.commit()
            
            return jsonify({
                'status': '1',
                'message': 'Terrain deleted successfully',
                'results': []
            })
            
    except Exception as e:
        return jsonify({'status': '0', 'message': f'Delete failed: {str(e)}'})

def handle_get_terrains(params):
    """Handle getting all terrains for a beach place"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            # Handle parameter naming convention
            beach_place_id = params.get('CompanyBeachPlaceID')
            
            if not beach_place_id or beach_place_id == 0:
                return jsonify({'status': '1', 'results': []})
            
            # Get beach information
            beach_info = db.execute(text("""
                SELECT bp.beach_name, bp.has_sea, bp.sea_location, bp.background_photo
                FROM beach_places bp
                WHERE bp.beach_place_id = :beach_place_id
            """), {'beach_place_id': beach_place_id}).fetchone()
            
            # Get terrains
            terrains = db.execute(text("""
                SELECT terrain_id, uid, angle, background_color, bed_reference,
                       block_online, classification, covers, description,
                       description_text, description_text_position, height,
                       left_position, bed_price, min_price, name,
                       top_position, width, z_index, is_layout
                FROM beach_place_terrains 
                WHERE beach_place_id = :beach_place_id
                ORDER BY z_index ASC
            """), {'beach_place_id': beach_place_id}).fetchall()
            
            results = []
            for terrain in terrains:
                results.append({
                    'CompaniesBeachPlaceTerrainID': str(terrain.terrain_id),
                    'uid': terrain.uid,
                    'angle': terrain.angle,
                    'backgroundColor': terrain.background_color,
                    'bedReference': terrain.bed_reference,
                    'blockOnline': terrain.block_online,
                    'classification': terrain.classification,
                    'covers': terrain.covers,
                    'description': terrain.description,
                    'descriptionText': terrain.description_text,
                    'descriptionTextPosition': terrain.description_text_position,
                    'height': float(terrain.height),
                    'left': float(terrain.left_position),
                    'bedPrice': float(terrain.bed_price),
                    'minPrice': float(terrain.min_price),
                    'name': terrain.name,
                    'top': float(terrain.top_position),
                    'width': float(terrain.width)
                })
            
            # Format response to match what the Vue app expects
            response_data = {
                'CompaniesBeachPlaceTerrains': results,
                'BeachName': beach_info.beach_name if beach_info else 'Unnamed Beach',
                'hasSea': beach_info.has_sea if beach_info else 0,
                'SeaLocation': beach_info.sea_location if beach_info else '',
                'BackgroundPhoto': beach_info.background_photo if beach_info else ''
            }
            
            return jsonify({
                'status': '1',
                'message': 'Success',
                'results': [response_data]  # Wrap in array to match expected format
            })
            
    except Exception as e:
        return jsonify({'status': '0', 'message': f'Get terrains failed: {str(e)}'})

def handle_get_single_terrain(params):
    """Handle getting single terrain by ID"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            terrain_id = params.get('CompaniesBeachPlaceTerrainID')
            
            if not terrain_id:
                return jsonify({'status': '0', 'message': 'Terrain ID required'})
            
            terrain = db.execute(text("""
                SELECT terrain_id, uid, angle, background_color, bed_reference,
                       block_online, classification, covers, description,
                       description_text, description_text_position, height,
                       left_position, bed_price, min_price, name,
                       top_position, width, z_index, is_layout
                FROM beach_place_terrains 
                WHERE terrain_id = :terrain_id
            """), {'terrain_id': terrain_id}).fetchone()
            
            if not terrain:
                return jsonify({'status': '0', 'message': 'Terrain not found'})
            
            result = {
                'CompaniesBeachPlaceTerrainID': str(terrain.terrain_id),
                'uid': terrain.uid,
                'angle': terrain.angle,
                'backgroundColor': terrain.background_color,
                'bedReference': terrain.bed_reference,
                'blockOnline': terrain.block_online,
                'classification': terrain.classification,
                'covers': terrain.covers,
                'description': terrain.description,
                'descriptionText': terrain.description_text,
                'descriptionTextPosition': terrain.description_text_position,
                'height': float(terrain.height),
                'left': float(terrain.left_position),
                'bedPrice': float(terrain.bed_price),
                'minPrice': float(terrain.min_price),
                'name': terrain.name,
                'top': float(terrain.top_position),
                'width': float(terrain.width)
            }
            
            return jsonify({
                'status': '1',
                'message': 'Success',
                'results': [result]
            })
            
    except Exception as e:
        return jsonify({'status': '0', 'message': f'Get terrain failed: {str(e)}'})

@app.route('/api/beach-info/<int:beach_id>', methods=['GET'])
def get_beach_info(beach_id):
    """Get basic beach information by beach place ID"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            beach_info = db.execute(text("""
                SELECT bp.beach_name, bp.beach_place_id, c.company_name,
                       bp.city, bp.address, bp.enable_beach
                FROM beach_places bp
                LEFT JOIN companies c ON bp.company_id = c.company_id
                WHERE bp.beach_place_id = :beach_id
            """), {"beach_id": beach_id}).fetchone()
            
            if not beach_info:
                return jsonify({'error': 'Beach not found'}), 404
            
            return jsonify({
                'beach_name': beach_info.beach_name,
                'beach_place_id': beach_info.beach_place_id,
                'company_name': beach_info.company_name,
                'city': beach_info.city,
                'address': beach_info.address,
                'enable_beach': beach_info.enable_beach
            })
    
    except Exception as e:
        print(f"Error getting beach info: {e}")
        return jsonify({'error': 'Failed to load beach information'}), 500

# API endpoints for beach photos - temporarily disabled
# @app.route('/api/beach-photos/<beach_id>', methods=['GET'])
# def get_beach_photos(beach_id):
#     """Get all photos for a beach place"""
#     return jsonify([])  # Return empty array for now

@app.route('/api/beach-photos/<beach_id>', methods=['GET'])
def get_beach_photos(beach_id):
    """Get all photos for a beach place"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            # Check if beach_places_photos table exists
            table_exists = db.execute(text("""
                SELECT EXISTS (
                    SELECT FROM information_schema.tables 
                    WHERE table_schema = 'public' AND table_name = 'beach_places_photos'
                )
            """)).fetchone()[0]
            
            if not table_exists:
                return jsonify([])
            
            # Get photos for this beach
            photos_result = db.execute(text("""
                SELECT photo_id, photo_path, photo_primary as is_primary, sort_order
                FROM beach_places_photos 
                WHERE beach_place_id = :beach_id
                ORDER BY photo_primary DESC, sort_order ASC
            """), {"beach_id": beach_id}).fetchall()
            
            photos = []
            for photo in photos_result:
                photos.append({
                    'photo_id': photo.photo_id,
                    'photo_path': photo.photo_path,
                    'is_primary': photo.is_primary,
                    'sort_order': photo.sort_order
                })
            
            return jsonify(photos)
    
    except Exception as e:
        print(f"Error getting beach photos: {e}")
        return jsonify([])

@app.route('/api/beach-photos/<int:beach_id>', methods=['POST'])
def upload_beach_photos(beach_id):
    """Upload photos for a beach place"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        if 'beach_photos' not in request.files:
            return jsonify({'error': 'No photos uploaded'}), 400
        
        photos = request.files.getlist('beach_photos')
        uploaded_photos = []
        
        with engine.connect() as db:
            # Check if there's already a primary photo for this beach
            existing_primary = db.execute(text("""
                SELECT COUNT(*) as count FROM beach_places_photos 
                WHERE beach_place_id = :beach_id AND photo_primary = true
            """), {'beach_id': beach_id}).fetchone()
            
            has_primary = existing_primary.count > 0
            
            # Get the next sort order
            max_sort = db.execute(text("""
                SELECT COALESCE(MAX(sort_order), -1) as max_sort 
                FROM beach_places_photos 
                WHERE beach_place_id = :beach_id
            """), {'beach_id': beach_id}).fetchone()
            
            next_sort_order = max_sort.max_sort + 1
            
            for i, photo in enumerate(photos):
                if photo.filename != '':
                    try:
                        # Save photo and add to database
                        filename = secure_filename(photo.filename)
                        import uuid
                        file_ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else 'jpg'
                        unique_filename = f"{uuid.uuid4().hex}.{file_ext}"
                        
                        # Create upload directory with absolute path
                        backend_dir = os.path.dirname(os.path.abspath(__file__))
                        upload_dir = os.path.join(backend_dir, 'static', 'uploads', 'beaches')
                        
                        # Ensure directory exists
                        os.makedirs(upload_dir, exist_ok=True)
                        print(f"Upload directory: {upload_dir}")
                        
                        # Save file with absolute path
                        file_path = os.path.join(upload_dir, unique_filename)
                        print(f"Saving file to: {file_path}")
                        
                        # Save the file
                        photo.save(file_path)
                        
                        # Verify file was saved
                        if os.path.exists(file_path):
                            file_size = os.path.getsize(file_path)
                            print(f"File saved successfully: {file_path} ({file_size} bytes)")
                        else:
                            raise Exception(f"File was not saved: {file_path}")
                        
                        # Only make first photo primary if no existing primary photo
                        is_primary = (i == 0 and not has_primary)
                        
                        # Add to database
                        result = db.execute(text("""
                            INSERT INTO beach_places_photos (
                                beach_place_id, photo_path, photo_primary, sort_order
                            ) VALUES (
                                :beach_id, :photo_path, :is_primary, :sort_order
                            ) RETURNING photo_id
                        """), {
                            'beach_id': beach_id,
                            'photo_path': f"/static/uploads/beaches/{unique_filename}",
                            'is_primary': is_primary,
                            'sort_order': next_sort_order + i
                        })
                        
                        photo_id = result.fetchone()[0]
                        uploaded_photos.append({
                            'photo_id': photo_id,
                            'photo_path': f"/static/uploads/beaches/{unique_filename}",
                            'is_primary': is_primary
                        })
                        
                    except Exception as photo_error:
                        print(f"Error uploading photo: {photo_error}")
                        return jsonify({'error': f'Failed to upload photo: {str(photo_error)}'}), 500
            
            db.commit()
            
        return jsonify({
            'success': True,
            'message': f'{len(uploaded_photos)} photo(s) uploaded successfully',
            'photos': uploaded_photos
        })
        
    except Exception as e:
        print(f"Error in photo upload: {e}")
        return jsonify({'error': 'Failed to upload photos'}), 500

@app.route('/api/beach-photos/<int:photo_id>/set-primary', methods=['PUT'])
def set_photo_primary(photo_id):
    """Set a photo as the primary photo for its beach"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            # Get the beach_place_id for this photo
            photo_result = db.execute(text("""
                SELECT beach_place_id FROM beach_places_photos 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id}).fetchone()
            
            if not photo_result:
                return jsonify({'error': 'Photo not found'}), 404
            
            beach_place_id = photo_result.beach_place_id
            
            # First, set all photos for this beach as non-primary
            db.execute(text("""
                UPDATE beach_places_photos 
                SET photo_primary = false 
                WHERE beach_place_id = :beach_place_id
            """), {"beach_place_id": beach_place_id})
            
            # Then set the specified photo as primary
            db.execute(text("""
                UPDATE beach_places_photos 
                SET photo_primary = true 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id})
            
            db.commit()
            
            return jsonify({'success': True, 'message': 'Photo set as primary successfully'})
    
    except Exception as e:
        print(f"Error setting photo as primary: {e}")
        return jsonify({'error': 'Failed to set photo as primary'}), 500

@app.route('/api/beach-photos/<int:photo_id>', methods=['DELETE'])
def delete_beach_photo(photo_id):
    """Delete a beach photo"""
    try:
        # Database connection
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            # Get photo path before deletion
            photo_result = db.execute(text("""
                SELECT photo_path FROM beach_places_photos 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id}).fetchone()
            
            if not photo_result:
                return jsonify({'error': 'Photo not found'}), 404
            
            # Delete from database
            db.execute(text("""
                DELETE FROM beach_places_photos 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id})
            
            db.commit()
            
            # Try to delete the file
            try:
                photo_path = photo_result.photo_path
                if photo_path.startswith('/static/'):
                    file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), photo_path[1:])  # Remove leading /
                    if os.path.exists(file_path):
                        os.remove(file_path)
            except Exception as file_error:
                print(f"Error deleting photo file: {file_error}")
            
            return jsonify({'success': True})
    
    except Exception as e:
        print(f"Error deleting beach photo: {e}")
        return jsonify({'error': 'Failed to delete photo'}), 500

@app.route('/api/restaurant-photos/<uuid:restaurant_id>', methods=['POST'])
def upload_restaurant_photos(restaurant_id):
    """Upload photos for a restaurant"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        if 'restaurant_photos' not in request.files:
            return jsonify({'error': 'No photos uploaded'}), 400
        
        photos = request.files.getlist('restaurant_photos')
        uploaded_photos = []
        
        with engine.connect() as db:
            # Check if there's already a primary photo for this restaurant
            existing_primary = db.execute(text("""
                SELECT COUNT(*) as count FROM restaurant_photos 
                WHERE restaurant_id = :restaurant_id AND is_primary = true
            """), {'restaurant_id': restaurant_id}).fetchone()
            
            has_primary = existing_primary.count > 0
            
            # Get the next sort order
            max_sort = db.execute(text("""
                SELECT COALESCE(MAX(photo_id), 0) as max_sort 
                FROM restaurant_photos 
                WHERE restaurant_id = :restaurant_id
            """), {'restaurant_id': restaurant_id}).fetchone()
            
            next_sort_order = max_sort.max_sort + 1
            
            for i, photo in enumerate(photos):
                if photo.filename != '':
                    try:
                        # Save photo and add to database
                        filename = secure_filename(photo.filename)
                        import uuid
                        file_ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else 'jpg'
                        unique_filename = f"{uuid.uuid4().hex}.{file_ext}"
                        
                        # Create upload directory with absolute path
                        backend_dir = os.path.dirname(os.path.abspath(__file__))
                        upload_dir = os.path.join(backend_dir, 'static', 'uploads', 'restaurant_photos')
                        
                        # Ensure directory exists
                        os.makedirs(upload_dir, exist_ok=True)
                        print(f"Upload directory: {upload_dir}")
                        
                        # Save file with absolute path
                        file_path = os.path.join(upload_dir, unique_filename)
                        print(f"Saving file to: {file_path}")
                        
                        # Save the file
                        photo.save(file_path)
                        
                        # Verify file was saved
                        if os.path.exists(file_path):
                            file_size = os.path.getsize(file_path)
                            print(f"File saved successfully: {file_path} ({file_size} bytes)")
                        else:
                            raise Exception(f"File was not saved: {file_path}")
                        
                        # Only make first photo primary if no existing primary photo
                        is_primary = (i == 0 and not has_primary)
                        
                        # Add to database
                        result = db.execute(text("""
                            INSERT INTO restaurant_photos (
                                restaurant_id, photo_path, is_primary
                            ) VALUES (
                                :restaurant_id, :photo_path, :is_primary
                            ) RETURNING photo_id
                        """), {
                            'restaurant_id': restaurant_id,
                            'photo_path': f"/static/uploads/restaurant_photos/{unique_filename}",
                            'is_primary': is_primary
                        })
                        
                        photo_id = result.fetchone()[0]
                        uploaded_photos.append({
                            'photo_id': photo_id,
                            'photo_path': f"/static/uploads/restaurant_photos/{unique_filename}",
                            'is_primary': is_primary
                        })
                        
                    except Exception as photo_error:
                        print(f"Error uploading photo: {photo_error}")
                        return jsonify({'error': f'Failed to upload photo: {str(photo_error)}'}), 500
            
            db.commit()
            
        return jsonify({
            'success': True,
            'message': f'{len(uploaded_photos)} photo(s) uploaded successfully',
            'photos': uploaded_photos
        })
        
    except Exception as e:
        print(f"Error in photo upload: {e}")
        return jsonify({'error': 'Failed to upload photos'}), 500


@app.route('/api/market-photos/<uuid:market_id>', methods=['POST'])
def upload_market_photos(market_id):
    """Upload photos for a market"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        if 'market_photos' not in request.files:
            return jsonify({'error': 'No photos uploaded'}), 400
        
        photos = request.files.getlist('market_photos')
        uploaded_photos = []
        
        with engine.connect() as db:
            # Check if there's already a primary photo for this market
            existing_primary = db.execute(text("""
                SELECT COUNT(*) as count FROM market_photos 
                WHERE market_id = :market_id AND is_primary = true
            """), {'market_id': market_id}).fetchone()
            
            has_primary = existing_primary.count > 0
            
            # Get the next sort order
            max_sort = db.execute(text("""
                SELECT COALESCE(MAX(photo_id), 0) as max_sort 
                FROM market_photos 
                WHERE market_id = :market_id
            """), {'market_id': market_id}).fetchone()
            
            next_sort_order = max_sort.max_sort + 1
            
            for i, photo in enumerate(photos):
                if photo.filename != '':
                    try:
                        # Save photo and add to database
                        filename = secure_filename(photo.filename)
                        import uuid
                        file_ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else 'jpg'
                        unique_filename = f"{uuid.uuid4().hex}.{file_ext}"
                        
                        # Create upload directory with absolute path
                        backend_dir = os.path.dirname(os.path.abspath(__file__))
                        upload_dir = os.path.join(backend_dir, 'static', 'uploads', 'markets')
                        
                        # Ensure directory exists
                        os.makedirs(upload_dir, exist_ok=True)
                        print(f"Upload directory: {upload_dir}")
                        
                        # Save file with absolute path
                        file_path = os.path.join(upload_dir, unique_filename)
                        print(f"Saving file to: {file_path}")
                        
                        # Save the file
                        photo.save(file_path)
                        
                        # Verify file was saved
                        if os.path.exists(file_path):
                            file_size = os.path.getsize(file_path)
                            print(f"File saved successfully: {file_path} ({file_size} bytes)")
                        else:
                            raise Exception(f"File was not saved: {file_path}")
                        
                        # Only make first photo primary if no existing primary photo
                        is_primary = (i == 0 and not has_primary)
                        
                        # Add to database
                        result = db.execute(text("""
                            INSERT INTO market_photos (
                                market_id, photo_path, is_primary
                            ) VALUES (
                                :market_id, :photo_path, :is_primary
                            ) RETURNING photo_id
                        """), {
                            'market_id': market_id,
                            'photo_path': f"/static/uploads/markets/{unique_filename}",
                            'is_primary': is_primary
                        })
                        
                        photo_id = result.fetchone()[0]
                        uploaded_photos.append({
                            'photo_id': photo_id,
                            'photo_path': f"/static/uploads/markets/{unique_filename}",
                            'is_primary': is_primary
                        })
                        
                    except Exception as photo_error:
                        print(f"Error uploading photo: {photo_error}")
                        return jsonify({'error': f'Failed to upload photo: {str(photo_error)}'}), 500
            
            db.commit()
            
        return jsonify({
            'success': True,
            'message': f'{len(uploaded_photos)} photo(s) uploaded successfully',
            'photos': uploaded_photos
        })
        
    except Exception as e:
        print(f"Error in photo upload: {e}")
        return jsonify({'error': 'Failed to upload photos'}), 500


@app.route('/api/adventure-photos/<uuid:adventure_id>', methods=['POST'])
def upload_adventure_photos(adventure_id):
    """Upload photos for an adventure"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        if 'adventure_photos' not in request.files:
            return jsonify({'error': 'No photos uploaded'}), 400
        
        photos = request.files.getlist('adventure_photos')
        uploaded_photos = []
        
        with engine.connect() as db:
            # Check if there's already a primary photo for this adventure
            existing_primary = db.execute(text("""
                SELECT COUNT(*) as count FROM adventure_photos 
                WHERE adventure_id = :adventure_id AND is_primary = true
            """), {'adventure_id': adventure_id}).fetchone()
            
            has_primary = existing_primary.count > 0
            
            # Get the next sort order
            max_sort = db.execute(text("""
                SELECT COALESCE(MAX(photo_id), 0) as max_sort 
                FROM adventure_photos 
                WHERE adventure_id = :adventure_id
            """), {'adventure_id': adventure_id}).fetchone()
            
            next_sort_order = max_sort.max_sort + 1
            
            for i, photo in enumerate(photos):
                if photo.filename != '':
                    try:
                        # Save photo and add to database
                        filename = secure_filename(photo.filename)
                        import uuid
                        file_ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else 'jpg'
                        unique_filename = f"{uuid.uuid4().hex}.{file_ext}"
                        
                        # Create upload directory with absolute path
                        backend_dir = os.path.dirname(os.path.abspath(__file__))
                        upload_dir = os.path.join(backend_dir, 'static', 'uploads', 'adventures')
                        
                        # Ensure directory exists
                        os.makedirs(upload_dir, exist_ok=True)
                        print(f"Upload directory: {upload_dir}")
                        
                        # Save file with absolute path
                        file_path = os.path.join(upload_dir, unique_filename)
                        print(f"Saving file to: {file_path}")
                        
                        # Save the file
                        photo.save(file_path)
                        
                        # Verify file was saved
                        if os.path.exists(file_path):
                            file_size = os.path.getsize(file_path)
                            print(f"File saved successfully: {file_path} ({file_size} bytes)")
                        else:
                            raise Exception(f"File was not saved: {file_path}")
                        
                        # Only make first photo primary if no existing primary photo
                        is_primary = (i == 0 and not has_primary)
                        
                        # Add to database
                        result = db.execute(text("""
                            INSERT INTO adventure_photos (
                                adventure_id, photo_path, is_primary
                            ) VALUES (
                                :adventure_id, :photo_path, :is_primary
                            ) RETURNING photo_id
                        """), {
                            'adventure_id': adventure_id,
                            'photo_path': f"/static/uploads/adventures/{unique_filename}",
                            'is_primary': is_primary
                        })
                        
                        photo_id = result.fetchone()[0]
                        uploaded_photos.append({
                            'photo_id': photo_id,
                            'photo_path': f"/static/uploads/adventures/{unique_filename}",
                            'is_primary': is_primary
                        })
                        
                    except Exception as photo_error:
                        print(f"Error uploading photo: {photo_error}")
                        return jsonify({'error': f'Failed to upload photo: {str(photo_error)}'}), 500
            
            db.commit()
            
        return jsonify({
            'success': True,
            'message': f'{len(uploaded_photos)} photo(s) uploaded successfully',
            'photos': uploaded_photos
        })
        
    except Exception as e:
        print(f"Error in photo upload: {e}")
        return jsonify({'error': 'Failed to upload photos'}), 500


@app.route('/api/restaurant-photos/<uuid:photo_id>/set-primary', methods=['PUT'])
def set_restaurant_photo_primary(photo_id):
    """Set a photo as the primary photo for its restaurant"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            # Get the restaurant_id for this photo
            photo_result = db.execute(text("""
                SELECT restaurant_id FROM restaurant_photos 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id}).fetchone()
            
            if not photo_result:
                return jsonify({'error': 'Photo not found'}), 404
            
            restaurant_id = photo_result.restaurant_id
            
            # First, set all photos for this restaurant as non-primary
            db.execute(text("""
                UPDATE restaurant_photos 
                SET is_primary = false 
                WHERE restaurant_id = :restaurant_id
            """), {"restaurant_id": restaurant_id})
            
            # Then set the specified photo as primary
            db.execute(text("""
                UPDATE restaurant_photos 
                SET is_primary = true 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id})
            
            db.commit()
            
            return jsonify({'success': True, 'message': 'Photo set as primary successfully'})
    
    except Exception as e:
        print(f"Error setting photo as primary: {e}")
        return jsonify({'error': 'Failed to set photo as primary'}), 500


@app.route('/api/restaurant-photos/<uuid:photo_id>', methods=['DELETE'])
def delete_restaurant_photo(photo_id):
    """Delete a restaurant photo"""
    try:
        # Database connection
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            # Get photo path before deletion
            photo_result = db.execute(text("""
                SELECT photo_path FROM restaurant_photos 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id}).fetchone()
            
            if not photo_result:
                return jsonify({'error': 'Photo not found'}), 404
            
            # Delete from database
            db.execute(text("""
                DELETE FROM restaurant_photos 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id})
            
            db.commit()
            
            # Try to delete the file
            try:
                photo_path = photo_result.photo_path
                if photo_path.startswith('/static/'):
                    file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), photo_path[1:])  # Remove leading /
                    if os.path.exists(file_path):
                        os.remove(file_path)
            except Exception as file_error:
                print(f"Error deleting photo file: {file_error}")
            
            return jsonify({'success': True})
    
    except Exception as e:
        print(f"Error deleting restaurant photo: {e}")
        return jsonify({'error': 'Failed to delete photo'}), 500


@app.route('/api/market-photos/<uuid:photo_id>/set-primary', methods=['PUT'])
def set_market_photo_primary(photo_id):
    """Set a photo as the primary photo for its market"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            # Get the market_id for this photo
            photo_result = db.execute(text("""
                SELECT market_id FROM market_photos 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id}).fetchone()
            
            if not photo_result:
                return jsonify({'error': 'Photo not found'}), 404
            
            market_id = photo_result.market_id
            
            # First, set all photos for this market as non-primary
            db.execute(text("""
                UPDATE market_photos 
                SET is_primary = false 
                WHERE market_id = :market_id
            """), {"market_id": market_id})
            
            # Then set the specified photo as primary
            db.execute(text("""
                UPDATE market_photos 
                SET is_primary = true 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id})
            
            db.commit()
            
            return jsonify({'success': True, 'message': 'Photo set as primary successfully'})
    
    except Exception as e:
        print(f"Error setting photo as primary: {e}")
        return jsonify({'error': 'Failed to set photo as primary'}), 500


@app.route('/api/market-photos/<uuid:photo_id>', methods=['DELETE'])
def delete_market_photo(photo_id):
    """Delete a market photo"""
    try:
        # Database connection
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            # Get photo path before deletion
            photo_result = db.execute(text("""
                SELECT photo_path FROM market_photos 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id}).fetchone()
            
            if not photo_result:
                return jsonify({'error': 'Photo not found'}), 404
            
            # Delete from database
            db.execute(text("""
                DELETE FROM market_photos 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id})
            
            db.commit()
            
            # Try to delete the file
            try:
                photo_path = photo_result.photo_path
                if photo_path.startswith('/static/'):
                    file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), photo_path[1:])  # Remove leading /
                    if os.path.exists(file_path):
                        os.remove(file_path)
            except Exception as file_error:
                print(f"Error deleting photo file: {file_error}")
            
            return jsonify({'success': True})
    
    except Exception as e:
        print(f"Error deleting market photo: {e}")
        return jsonify({'error': 'Failed to delete photo'}), 500


@app.route('/api/adventure-photos/<uuid:photo_id>/set-primary', methods=['PUT'])
def set_adventure_photo_primary(photo_id):
    """Set a photo as the primary photo for its adventure"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            # Get the adventure_id for this photo
            photo_result = db.execute(text("""
                SELECT adventure_id FROM adventure_photos 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id}).fetchone()
            
            if not photo_result:
                return jsonify({'error': 'Photo not found'}), 404
            
            adventure_id = photo_result.adventure_id
            
            # First, set all photos for this adventure as non-primary
            db.execute(text("""
                UPDATE adventure_photos 
                SET is_primary = false 
                WHERE adventure_id = :adventure_id
            """), {"adventure_id": adventure_id})
            
            # Then set the specified photo as primary
            db.execute(text("""
                UPDATE adventure_photos 
                SET is_primary = true 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id})
            
            db.commit()
            
            return jsonify({'success': True, 'message': 'Photo set as primary successfully'})
    
    except Exception as e:
        print(f"Error setting photo as primary: {e}")
        return jsonify({'error': 'Failed to set photo as primary'}), 500


@app.route('/api/adventure-photos/<uuid:photo_id>', methods=['DELETE'])
def delete_adventure_photo(photo_id):
    """Delete an adventure photo"""
    try:
        # Database connection
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            # Get photo path before deletion
            photo_result = db.execute(text("""
                SELECT photo_path FROM adventure_photos 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id}).fetchone()
            
            if not photo_result:
                return jsonify({'error': 'Photo not found'}), 404
            
            # Delete from database
            db.execute(text("""
                DELETE FROM adventure_photos 
                WHERE photo_id = :photo_id
            """), {"photo_id": photo_id})
            
            db.commit()
            
            # Try to delete the file
            try:
                photo_path = photo_result.photo_path
                if photo_path.startswith('/static/'):
                    file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), photo_path[1:])  # Remove leading /
                    if os.path.exists(file_path):
                        os.remove(file_path)
            except Exception as file_error:
                print(f"Error deleting photo file: {file_error}")
            
            return jsonify({'success': True})
    
    except Exception as e:
        print(f"Error deleting adventure photo: {e}")
        return jsonify({'error': 'Failed to delete photo'}), 500


@app.route('/api/beach-schedules/<beach_id>', methods=['GET'])
def get_beach_schedules(beach_id):
    """Get all schedules for a beach place"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            schedules = db.execute(text("""
                SELECT s.*, c.currency_symbol 
                FROM beach_places_schedules s
                LEFT JOIN currencies c ON s.currency_id = c.currency_id
                WHERE s.beach_place_id = :beach_id
                ORDER BY s.from_date DESC
            """), {"beach_id": beach_id}).fetchall()
            
            schedules_data = []
            for schedule in schedules:
                schedules_data.append({
                    'schedule_id': schedule.schedule_id,
                    'from_date': schedule.from_date.isoformat(),
                    'to_date': schedule.to_date.isoformat(),
                    'from_time': schedule.from_time.strftime('%H:%M'),
                    'to_time': schedule.to_time.strftime('%H:%M'),
                    'valid_dates': schedule.valid_dates,
                    'min_hours': schedule.min_hours,
                    'can_refund': schedule.can_refund,
                    'refund_before_hours': schedule.refund_before_hours,
                    'price': float(schedule.price),
                    'price_vip': float(schedule.price_vip),
                    'currency_symbol': schedule.currency_symbol or '€',
                    'extras': schedule.extras,
                    'extras_vip': schedule.extras_vip
                })
            
            return jsonify(schedules_data)
    
    except Exception as e:
        print(f"Error getting beach schedules: {e}")
        return jsonify({'error': 'Failed to load schedules'}), 500

@app.route('/api/beach-schedules/<beach_id>', methods=['POST'])
def add_beach_schedule(beach_id):
    """Add a new schedule for a beach place"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        data = request.get_json()
        
        with engine.connect() as db:
            # Get EUR currency ID
            currency_result = db.execute(text("""
                SELECT currency_id FROM currencies WHERE currency_code = 'EUR'
            """)).fetchone()
            currency_id = currency_result.currency_id if currency_result else 1
            
            # Insert new schedule
            result = db.execute(text("""
                INSERT INTO beach_places_schedules (
                    beach_place_id, from_date, to_date, from_time, to_time,
                    valid_dates, min_hours, can_refund, refund_before_hours,
                    currency_id, price, price_vip, extras, extras_vip
                ) VALUES (
                    :beach_id, :from_date, :to_date, :from_time, :to_time,
                    :valid_dates, :min_hours, :can_refund, :refund_before_hours,
                    :currency_id, :price, :price_vip, :extras, :extras_vip
                ) RETURNING schedule_id
            """), {
                'beach_id': beach_id,
                'from_date': data['from_date'],
                'to_date': data['to_date'],
                'from_time': data['from_time'],
                'to_time': data['to_time'],
                'valid_dates': data['valid_dates'],
                'min_hours': data['min_hours'],
                'can_refund': data['can_refund'],
                'refund_before_hours': data['refund_before_hours'],
                'currency_id': currency_id,
                'price': data['price'],
                'price_vip': data['price_vip'],
                'extras': data.get('extras', ''),
                'extras_vip': data.get('extras_vip', '')
            })
            
            schedule_id = result.fetchone()[0]
            db.commit()
            
            return jsonify({
                'success': True,
                'schedule_id': schedule_id,
                'message': 'Schedule created successfully'
            })
    
    except Exception as e:
        print(f"Error adding beach schedule: {e}")
        return jsonify({'error': 'Failed to create schedule'}), 500

@app.route('/api/beach-schedules/<int:schedule_id>', methods=['PUT'])
def update_beach_schedule(schedule_id):
    """Update an existing beach schedule"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        data = request.get_json()
        
        with engine.connect() as db:
            # Check if schedule exists
            existing = db.execute(text("""
                SELECT schedule_id FROM beach_places_schedules 
                WHERE schedule_id = :schedule_id
            """), {"schedule_id": schedule_id}).fetchone()
            
            if not existing:
                return jsonify({'error': 'Schedule not found'}), 404
            
            # Get EUR currency ID
            currency_result = db.execute(text("""
                SELECT currency_id FROM currencies WHERE currency_code = 'EUR'
            """)).fetchone()
            currency_id = currency_result.currency_id if currency_result else 1
            
            # Update schedule
            db.execute(text("""
                UPDATE beach_places_schedules SET
                    from_date = :from_date,
                    to_date = :to_date,
                    from_time = :from_time,
                    to_time = :to_time,
                    valid_dates = :valid_dates,
                    min_hours = :min_hours,
                    can_refund = :can_refund,
                    refund_before_hours = :refund_before_hours,
                    currency_id = :currency_id,
                    price = :price,
                    price_vip = :price_vip,
                    extras = :extras,
                    extras_vip = :extras_vip
                WHERE schedule_id = :schedule_id
            """), {
                'schedule_id': schedule_id,
                'from_date': data['from_date'],
                'to_date': data['to_date'],
                'from_time': data['from_time'],
                'to_time': data['to_time'],
                'valid_dates': data['valid_dates'],
                'min_hours': data['min_hours'],
                'can_refund': data['can_refund'],
                'refund_before_hours': data['refund_before_hours'],
                'currency_id': currency_id,
                'price': data['price'],
                'price_vip': data['price_vip'],
                'extras': data.get('extras', ''),
                'extras_vip': data.get('extras_vip', '')
            })
            
            db.commit()
            
            return jsonify({
                'success': True,
                'message': 'Schedule updated successfully'
            })
    
    except Exception as e:
        print(f"Error updating beach schedule: {e}")
        return jsonify({'error': 'Failed to update schedule'}), 500

@app.route('/api/beach-schedules/delete/<int:schedule_id>', methods=['DELETE'])
def delete_beach_schedule(schedule_id):
    """Delete a beach schedule"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            # Check if schedule exists
            result = db.execute(text("""
                SELECT schedule_id FROM beach_places_schedules 
                WHERE schedule_id = :schedule_id
            """), {"schedule_id": schedule_id}).fetchone()
            
            if not result:
                return jsonify({'error': 'Schedule not found'}), 404
            
            # Delete the schedule
            db.execute(text("""
                DELETE FROM beach_places_schedules 
                WHERE schedule_id = :schedule_id
            """), {"schedule_id": schedule_id})
            
            db.commit()
            
            return jsonify({
                'success': True,
                'message': 'Schedule deleted successfully'
            })
    
    except Exception as e:
        print(f"Error deleting beach schedule: {e}")
        return jsonify({'error': 'Failed to delete schedule'}), 500

@app.route('/api/beach-design/<beach_id>', methods=['GET'])
def get_beach_design(beach_id):
    """Get beach design/terrain elements for a beach place"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        with engine.connect() as db:
            terrains = db.execute(text("""
                SELECT * FROM beach_place_terrains 
                WHERE beach_place_id = :beach_id
                ORDER BY z_index ASC
            """), {"beach_id": beach_id}).fetchall()
            
            terrain_data = []
            for terrain in terrains:
                terrain_data.append({
                    'terrain_id': str(terrain.terrain_id),
                    'uid': terrain.uid,
                    'angle': terrain.angle,
                    'background_color': terrain.background_color,
                    'bed_reference': terrain.bed_reference,
                    'block_online': terrain.block_online,
                    'classification': terrain.classification,
                    'covers': terrain.covers,
                    'description': terrain.description,
                    'description_text': terrain.description_text,
                    'description_text_position': terrain.description_text_position,
                    'height': float(terrain.height),
                    'left_position': float(terrain.left_position),
                    'bed_price': float(terrain.bed_price),
                    'min_price': float(terrain.min_price),
                    'name': terrain.name,
                    'top_position': float(terrain.top_position),
                    'width': float(terrain.width),
                    'z_index': terrain.z_index,
                    'is_layout': terrain.is_layout
                })
            
            return jsonify(terrain_data)
    
    except Exception as e:
        print(f"Error getting beach design: {e}")
        return jsonify({'error': 'Failed to load beach design'}), 500

@app.route('/api/beach-design/<beach_id>', methods=['POST'])
def save_beach_design(beach_id):
    """Save beach design/terrain elements for a beach place"""
    try:
        database_password = get_decrypted_env_var('DATABASE_PASSWORD')
        database_url = f"postgresql://{os.getenv('DATABASE_USER', 'postgres')}:{quote_plus(database_password)}@{os.getenv('DATABASE_HOST', 'localhost')}:{os.getenv('DATABASE_PORT', '5432')}/{os.getenv('DATABASE_NAME', 'bookbeach')}"
        engine = create_engine(database_url)
        
        design_data = request.get_json()
        
        with engine.connect() as db:
            # Clear existing design elements
            db.execute(text("""
                DELETE FROM beach_place_terrains WHERE beach_place_id = :beach_id
            """), {"beach_id": beach_id})
            
            # Insert new design elements
            elements = design_data.get('elements', [])
            for i, element in enumerate(elements):
                # Handle both the old format and the new Vue app format
                uid = element.get('uid', element.get('uid', i + 1))
                angle = element.get('angle', element.get('angle', 0))
                background_color = element.get('background_color', element.get('color', '#FFD700'))
                bed_reference = element.get('bed_reference', element.get('bedReference', ''))
                block_online = element.get('block_online', element.get('blockOnline', False))
                classification = element.get('classification', element.get('classification', 0))
                covers = element.get('covers', element.get('covers', ''))
                description = element.get('description', element.get('description', ''))
                description_text = element.get('description_text', element.get('descriptionText', ''))
                description_text_position = element.get('description_text_position', element.get('descriptionTextPosition', ''))
                height = element.get('height', element.get('height', 40))
                left_position = element.get('left_position', element.get('x', element.get('left', 0)))
                bed_price = element.get('bed_price', element.get('bedPrice', element.get('price', 0)))
                min_price = element.get('min_price', element.get('minPrice', element.get('price', 0)))
                name = element.get('name', element.get('name', element.get('type', 'Element')))
                top_position = element.get('top_position', element.get('y', element.get('top', 0)))
                width = element.get('width', element.get('width', 60))
                z_index = element.get('z_index', element.get('zIndex', element.get('zindex', i)))
                is_layout = bool(element.get('is_layout', element.get('isLayout', element.get('islayout', False))))
                
                # Handle terrain_id for updates
                terrain_id = element.get('terrain_id', element.get('CompaniesBeachPlaceTerrainID', None))
                
                db.execute(text("""
                    INSERT INTO beach_place_terrains (
                        uid, beach_place_id, angle, background_color, bed_reference,
                        block_online, classification, covers, description, description_text,
                        description_text_position, height, left_position, bed_price,
                        min_price, name, top_position, width, z_index, is_layout
                    ) VALUES (
                        :uid, :beach_place_id, :angle, :background_color, :bed_reference,
                        :block_online, :classification, :covers, :description, :description_text,
                        :description_text_position, :height, :left_position, :bed_price,
                        :min_price, :name, :top_position, :width, :z_index, :is_layout
                    )
                """), {
                    'uid': uid,
                    'beach_place_id': beach_id,
                    'angle': angle,
                    'background_color': background_color,
                    'bed_reference': bed_reference,
                    'block_online': block_online,
                    'classification': classification,
                    'covers': covers,
                    'description': description,
                    'description_text': description_text,
                    'description_text_position': description_text_position,
                    'height': height,
                    'left_position': left_position,
                    'bed_price': bed_price,
                    'min_price': min_price,
                    'name': name,
                    'top_position': top_position,
                    'width': width,
                    'z_index': z_index,
                    'is_layout': is_layout
                })
            
            db.commit()
            
            return jsonify({
                'success': True,
                'message': f'Beach design saved with {len(elements)} elements'
            })
    
    except Exception as e:
        print(f"Error saving beach design: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': 'Failed to save beach design'}), 500

@app.route('/maps-key-test')
def maps_key_test():
    """Serve maps key test page"""
    return app.send_static_file('maps_key_test.html')

@app.route('/debug-maps-key')
def debug_maps_key():
    """Debug endpoint to check what Google Maps key is being used"""
    import os
    from dotenv import load_dotenv
    
    # Force reload .env
    load_dotenv(override=True)
    
    key = os.getenv('GOOGLE_MAPS_API_KEY', 'your-google-maps-api-key')
    
    # Get all environment variables containing GOOGLE
    google_vars = {k: v for k, v in os.environ.items() if 'GOOGLE' in k}
    
    # Check if .env file exists and show its content
    env_content = ""
    try:
        with open('.env', 'r') as f:
            lines = f.readlines()
            for i, line in enumerate(lines):
                if 'GOOGLE_MAPS_API_KEY' in line:
                    env_content = f"Line {i+1}: {line.strip()}"
                    break
    except Exception as e:
        env_content = f"Error reading .env: {e}"
    
    return f"""<h3>Google Maps API Key Debug</h3>
    <p><strong>Key from os.getenv():</strong> {key}</p>
    <p><strong>Key length:</strong> {len(key) if key else 0}</p>
    <p><strong>Template condition:</strong> {key and key != 'your-google-maps-api-key'}</p>
    <p><strong>Expected behavior:</strong> {'Use YOUR key' if key and key != 'your-google-maps-api-key' else 'Use TEST key'}</p>
    <p><strong>.env file content:</strong> {env_content}</p>
    <p><strong>All Google env vars:</strong> {google_vars}</p>
    <p><strong>Current working directory:</strong> {os.getcwd()}</p>
    """

@app.errorhandler(404)
def not_found(error):
    return render_template('error.html', 
                         error_code=404,
                         error_message="Page not found"), 404

@app.errorhandler(500)
def internal_error(error):
    return render_template('error.html',
                         error_code=500,
                         error_message="Internal server error"), 500

# Route to serve uploaded beach photos
@app.route('/uploads/beach_photos/<filename>')
def uploaded_beach_photo(filename):
    """Serve beach photo files from uploads directory"""
    upload_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads', 'beach_photos')
    return send_from_directory(upload_dir, filename)

# Route to serve uploaded market item photos
@app.route('/uploads/market_items/<filename>')
def uploaded_market_item_photo(filename):
    """Serve market item photo files from uploads directory"""
    upload_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'uploads', 'market_items')
    return send_from_directory(upload_dir, filename)

if __name__ == '__main__':
    # Create templates directory if it doesn't exist
    os.makedirs('templates', exist_ok=True)
    os.makedirs('static/css', exist_ok=True)
    os.makedirs('static/js', exist_ok=True)
    
    print("Starting BookBeach Admin Interface...")
    print(f"Admin Username: {ADMIN_CONFIG['ADMIN_USERNAME']}")
    print(f"Admin Password: {ADMIN_CONFIG['ADMIN_PASSWORD']}")
    print("Access at: http://localhost:8001")
    
    app.run(host='0.0.0.0', port=8001, debug=True)