<?php
/**
 * Local Business Schema Class for BW AI Schema Pro
 *
 * @package BW_AI_Schema_Pro
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class BW_Schema_LocalBusiness extends BW_Schema_Base {
	
	/**
	 * Generate local business schema
	 */
	public function generate( $post, $type = 'LocalBusiness' ) {
		// Base schema
		$schema = array(
			'@context' => 'https://schema.org',
			'@type' => $type,
		);
		
		// Add common properties
		$schema['@id'] = get_permalink( $post );
		$schema['name'] = get_the_title( $post );
		$schema['url'] = get_permalink( $post );
		
		// Add description
		if ( has_excerpt( $post ) ) {
			$schema['description'] = wp_strip_all_tags( get_the_excerpt( $post ) );
		}
		
		// Add image
		if ( has_post_thumbnail( $post ) ) {
			$schema['image'] = get_the_post_thumbnail_url( $post, 'full' );
		}
		
		// Add address (required for local business)
		$address = get_post_meta( $post->ID, '_bw_schema_address', true );
		if ( ! empty( $address ) && is_array( $address ) ) {
			$schema['address'] = array(
				'@type' => 'PostalAddress',
				'streetAddress' => $address['street'] ?? '',
				'addressLocality' => $address['city'] ?? '',
				'addressRegion' => $address['state'] ?? '',
				'postalCode' => $address['zip'] ?? '',
				'addressCountry' => $address['country'] ?? 'US',
			);
		}
		
		// Add geo coordinates
		$latitude = get_post_meta( $post->ID, '_bw_schema_latitude', true );
		$longitude = get_post_meta( $post->ID, '_bw_schema_longitude', true );
		if ( ! empty( $latitude ) && ! empty( $longitude ) ) {
			$schema['geo'] = array(
				'@type' => 'GeoCoordinates',
				'latitude' => floatval( $latitude ),
				'longitude' => floatval( $longitude ),
			);
		}
		
		// Add contact info
		$telephone = get_post_meta( $post->ID, '_bw_schema_telephone', true );
		if ( ! empty( $telephone ) ) {
			$schema['telephone'] = $telephone;
		}
		
		$email = get_post_meta( $post->ID, '_bw_schema_email', true );
		if ( ! empty( $email ) ) {
			$schema['email'] = $email;
		}
		
		// Add opening hours
		$opening_hours = get_post_meta( $post->ID, '_bw_schema_opening_hours', true );
		if ( ! empty( $opening_hours ) && is_array( $opening_hours ) ) {
			$hours_spec = array();
			foreach ( $opening_hours as $hours ) {
				if ( ! empty( $hours['days'] ) && ! empty( $hours['opens'] ) && ! empty( $hours['closes'] ) ) {
					$spec = array(
						'@type' => 'OpeningHoursSpecification',
						'dayOfWeek' => $hours['days'],
						'opens' => $hours['opens'],
						'closes' => $hours['closes'],
					);
					$hours_spec[] = $spec;
				}
			}
			if ( ! empty( $hours_spec ) ) {
				$schema['openingHoursSpecification'] = $hours_spec;
			}
		}
		
		// Add price range - check if enabled globally
		$enable_price_range = get_option( 'bw_schema_enable_price_range', 'no' );
		if ( $enable_price_range === 'yes' ) {
			$price_range = get_post_meta( $post->ID, '_bw_schema_price_range', true );
			
			// Use global default if no post-specific price range
			if ( empty( $price_range ) ) {
				$price_range = get_option( 'bw_schema_price_range', '' );
			}
			
			if ( ! empty( $price_range ) ) {
				$schema['priceRange'] = $price_range;
			}
		}
		
		// Add payment accepted
		$payment_accepted = get_post_meta( $post->ID, '_bw_schema_payment_accepted', true );
		if ( ! empty( $payment_accepted ) && is_array( $payment_accepted ) ) {
			$schema['paymentAccepted'] = implode( ', ', array_filter( $payment_accepted ) );
		}
		
		// Add currencies accepted
		$currencies = get_post_meta( $post->ID, '_bw_schema_currencies_accepted', true );
		if ( ! empty( $currencies ) ) {
			$schema['currenciesAccepted'] = $currencies;
		}
		
		// Add social profiles
		$social_profiles = get_post_meta( $post->ID, '_bw_schema_social_profiles', true );
		if ( ! empty( $social_profiles ) && is_array( $social_profiles ) ) {
			$schema['sameAs'] = array_filter( $social_profiles );
		}
		
		// Add area served
		$area_served = get_post_meta( $post->ID, '_bw_schema_area_served', true );
		if ( ! empty( $area_served ) && is_array( $area_served ) ) {
			$areas = array();
			foreach ( $area_served as $area ) {
				if ( ! empty( $area ) ) {
					$areas[] = array(
						'@type' => 'GeoCircle',
						'name' => $area,
					);
				}
			}
			if ( ! empty( $areas ) ) {
				$schema['areaServed'] = $areas;
			}
		}
		
		// Add aggregate rating
		$rating_value = get_post_meta( $post->ID, '_bw_schema_rating_value', true );
		$rating_count = get_post_meta( $post->ID, '_bw_schema_rating_count', true );
		if ( ! empty( $rating_value ) && ! empty( $rating_count ) ) {
			$schema['aggregateRating'] = array(
				'@type' => 'AggregateRating',
				'ratingValue' => floatval( $rating_value ),
				'ratingCount' => intval( $rating_count ),
				'bestRating' => '5',
			);
		}
		
		// Add type-specific properties
		switch ( $type ) {
			case 'ProfessionalService':
			case 'ConsultingBusiness':
				$schema = $this->add_professional_service_properties( $schema, $post );
				break;
				
			case 'Hotel':
			case 'Resort':
				$schema = $this->add_lodging_properties( $schema, $post );
				break;
				
			case 'Attorney':
				$schema = $this->add_attorney_properties( $schema, $post );
				break;
				
			case 'Restaurant':
				$schema = $this->add_restaurant_properties( $schema, $post );
				break;
				
			case 'MedicalBusiness':
				$schema = $this->add_medical_properties( $schema, $post );
				break;
				
			case 'FinancialService':
				$schema = $this->add_financial_properties( $schema, $post );
				break;
				
			case 'RealEstateAgent':
				$schema = $this->add_real_estate_properties( $schema, $post );
				break;
		}
		
		// Add amenity features (for various business types)
		$amenities = get_post_meta( $post->ID, '_bw_schema_amenities', true );
		if ( ! empty( $amenities ) && is_array( $amenities ) ) {
			$amenity_features = array();
			foreach ( $amenities as $amenity ) {
				if ( ! empty( $amenity ) ) {
					$amenity_features[] = array(
						'@type' => 'LocationFeatureSpecification',
						'name' => $amenity,
						'value' => true,
					);
				}
			}
			if ( ! empty( $amenity_features ) ) {
				$schema['amenityFeature'] = $amenity_features;
			}
		}
		
		// Add AI-optimized properties
		$schema = $this->add_ai_properties( $schema, $post );
		
		return apply_filters( 'bw_schema_localbusiness', $schema, $post, $type );
	}
	
	/**
	 * Add professional service properties
	 */
	private function add_professional_service_properties( $schema, $post ) {
		// Add services offered
		$services = get_post_meta( $post->ID, '_bw_schema_services_offered', true );
		if ( ! empty( $services ) && is_array( $services ) ) {
			$offers = array();
			foreach ( $services as $service ) {
				if ( ! empty( $service['name'] ) ) {
					$offer = array(
						'@type' => 'Offer',
						'itemOffered' => array(
							'@type' => 'Service',
							'name' => $service['name'],
						)
					);
					if ( ! empty( $service['description'] ) ) {
						$offer['itemOffered']['description'] = $service['description'];
					}
					$offers[] = $offer;
				}
			}
			if ( ! empty( $offers ) ) {
				$schema['hasOfferCatalog'] = array(
					'@type' => 'OfferCatalog',
					'name' => 'Services',
					'itemListElement' => $offers,
				);
			}
		}
		
		// Add expertise areas
		$expertise = get_post_meta( $post->ID, '_bw_schema_expertise_areas', true );
		if ( ! empty( $expertise ) && is_array( $expertise ) ) {
			$schema['knowsAbout'] = array_filter( $expertise );
		}
		
		// Add certifications
		$certifications = get_post_meta( $post->ID, '_bw_schema_certifications', true );
		if ( ! empty( $certifications ) && is_array( $certifications ) ) {
			$certs = array();
			foreach ( $certifications as $cert ) {
				if ( ! empty( $cert['name'] ) ) {
					$certification = array(
						'@type' => 'Certification',
						'name' => $cert['name'],
					);
					if ( ! empty( $cert['issuedBy'] ) ) {
						$certification['issuedBy'] = array(
							'@type' => 'Organization',
							'name' => $cert['issuedBy'],
						);
					}
					$certs[] = $certification;
				}
			}
			if ( ! empty( $certs ) ) {
				$schema['hasCertification'] = $certs;
			}
		}
		
		// Add founding date for credibility
		$founding_date = get_post_meta( $post->ID, '_bw_schema_founding_date', true );
		if ( ! empty( $founding_date ) ) {
			$schema['foundingDate'] = $founding_date;
		}
		
		// Add awards
		$awards = get_post_meta( $post->ID, '_bw_schema_awards', true );
		if ( ! empty( $awards ) && is_array( $awards ) ) {
			$schema['award'] = array_filter( $awards );
		}
		
		// Add client testimonials as reviews
		$testimonials = get_post_meta( $post->ID, '_bw_schema_testimonials', true );
		if ( ! empty( $testimonials ) && is_array( $testimonials ) ) {
			$reviews = array();
			foreach ( $testimonials as $testimonial ) {
				if ( ! empty( $testimonial['text'] ) && ! empty( $testimonial['author'] ) ) {
					$review = array(
						'@type' => 'Review',
						'reviewBody' => $testimonial['text'],
						'author' => array(
							'@type' => 'Person',
							'name' => $testimonial['author'],
						),
					);
					if ( ! empty( $testimonial['rating'] ) ) {
						$review['reviewRating'] = array(
							'@type' => 'Rating',
							'ratingValue' => $testimonial['rating'],
							'bestRating' => '5',
						);
					}
					$reviews[] = $review;
				}
			}
			if ( ! empty( $reviews ) ) {
				$schema['review'] = $reviews;
			}
		}
		
		return $schema;
	}
	
	/**
	 * Add lodging-specific properties (Hotel/Resort)
	 */
	private function add_lodging_properties( $schema, $post ) {
		// Add star rating
		$star_rating = get_post_meta( $post->ID, '_bw_schema_star_rating', true );
		if ( ! empty( $star_rating ) ) {
			$schema['starRating'] = array(
				'@type' => 'Rating',
				'ratingValue' => $star_rating,
			);
		}
		
		// Add check-in/check-out times
		$checkin_time = get_post_meta( $post->ID, '_bw_schema_checkin_time', true );
		if ( ! empty( $checkin_time ) ) {
			$schema['checkinTime'] = $checkin_time;
		}
		
		$checkout_time = get_post_meta( $post->ID, '_bw_schema_checkout_time', true );
		if ( ! empty( $checkout_time ) ) {
			$schema['checkoutTime'] = $checkout_time;
		}
		
		// Add number of rooms
		$num_rooms = get_post_meta( $post->ID, '_bw_schema_number_of_rooms', true );
		if ( ! empty( $num_rooms ) ) {
			$schema['numberOfRooms'] = intval( $num_rooms );
		}
		
		// Add pet policy
		$pets_allowed = get_post_meta( $post->ID, '_bw_schema_pets_allowed', true );
		if ( $pets_allowed !== '' ) {
			$schema['petsAllowed'] = ( $pets_allowed === 'yes' );
		}
		
		// Add available languages
		$languages = get_post_meta( $post->ID, '_bw_schema_available_languages', true );
		if ( ! empty( $languages ) && is_array( $languages ) ) {
			$schema['availableLanguage'] = array_filter( $languages );
		}
		
		return $schema;
	}
	
	/**
	 * Add attorney-specific properties
	 */
	private function add_attorney_properties( $schema, $post ) {
		// Add practice areas
		$practice_areas = get_post_meta( $post->ID, '_bw_schema_practice_areas', true );
		if ( ! empty( $practice_areas ) && is_array( $practice_areas ) ) {
			$schema['knowsAbout'] = array_filter( $practice_areas );
		}
		
		// Add bar admissions
		$bar_admissions = get_post_meta( $post->ID, '_bw_schema_bar_admissions', true );
		if ( ! empty( $bar_admissions ) && is_array( $bar_admissions ) ) {
			$admissions = array();
			foreach ( $bar_admissions as $admission ) {
				if ( ! empty( $admission ) ) {
					$admissions[] = array(
						'@type' => 'Certification',
						'name' => 'Bar Admission - ' . $admission,
						'issuedBy' => array(
							'@type' => 'Organization',
							'name' => $admission . ' State Bar',
						),
					);
				}
			}
			if ( ! empty( $admissions ) ) {
				$schema['hasCredential'] = $admissions;
			}
		}
		
		// Add awards and recognitions
		$awards = get_post_meta( $post->ID, '_bw_schema_awards', true );
		if ( ! empty( $awards ) && is_array( $awards ) ) {
			$schema['award'] = array_filter( $awards );
		}
		
		// Add education
		$education = get_post_meta( $post->ID, '_bw_schema_attorney_education', true );
		if ( ! empty( $education ) && is_array( $education ) ) {
			$alumni = array();
			foreach ( $education as $edu ) {
				if ( ! empty( $edu['school'] ) ) {
					$alumni_item = array(
						'@type' => 'EducationalOrganization',
						'name' => $edu['school'],
					);
					if ( ! empty( $edu['degree'] ) ) {
						$alumni_item['degree'] = $edu['degree'];
					}
					$alumni[] = $alumni_item;
				}
			}
			if ( ! empty( $alumni ) ) {
				$schema['alumniOf'] = $alumni;
			}
		}
		
		return $schema;
	}
	
	/**
	 * Add restaurant-specific properties
	 */
	private function add_restaurant_properties( $schema, $post ) {
		// Add cuisine types
		$cuisine = get_post_meta( $post->ID, '_bw_schema_serves_cuisine', true );
		if ( ! empty( $cuisine ) && is_array( $cuisine ) ) {
			$schema['servesCuisine'] = array_filter( $cuisine );
		}
		
		// Add menu URL
		$menu_url = get_post_meta( $post->ID, '_bw_schema_menu_url', true );
		if ( ! empty( $menu_url ) ) {
			$schema['hasMenu'] = $menu_url;
		}
		
		// Add reservation info
		$accepts_reservations = get_post_meta( $post->ID, '_bw_schema_accepts_reservations', true );
		if ( $accepts_reservations === 'yes' ) {
			$schema['acceptsReservations'] = true;
			
			$reservation_url = get_post_meta( $post->ID, '_bw_schema_reservation_url', true );
			if ( ! empty( $reservation_url ) ) {
				$schema['potentialAction'] = array(
					'@type' => 'ReserveAction',
					'target' => array(
						'@type' => 'EntryPoint',
						'urlTemplate' => $reservation_url,
					),
				);
			}
		}
		
		return $schema;
	}
	
	/**
	 * Add medical business properties
	 */
	private function add_medical_properties( $schema, $post ) {
		// Add medical specialties
		$specialties = get_post_meta( $post->ID, '_bw_schema_medical_specialties', true );
		if ( ! empty( $specialties ) && is_array( $specialties ) ) {
			$schema['medicalSpecialty'] = array_filter( $specialties );
		}
		
		// Add available services
		$services = get_post_meta( $post->ID, '_bw_schema_medical_services', true );
		if ( ! empty( $services ) && is_array( $services ) ) {
			$available_services = array();
			foreach ( $services as $service ) {
				if ( ! empty( $service ) ) {
					$available_services[] = array(
						'@type' => 'MedicalProcedure',
						'name' => $service,
					);
				}
			}
			if ( ! empty( $available_services ) ) {
				$schema['availableService'] = $available_services;
			}
		}
		
		// Add hospital affiliation
		$affiliations = get_post_meta( $post->ID, '_bw_schema_hospital_affiliations', true );
		if ( ! empty( $affiliations ) && is_array( $affiliations ) ) {
			$hospitals = array();
			foreach ( $affiliations as $affiliation ) {
				if ( ! empty( $affiliation ) ) {
					$hospitals[] = array(
						'@type' => 'Hospital',
						'name' => $affiliation,
					);
				}
			}
			if ( ! empty( $hospitals ) ) {
				$schema['hospitalAffiliation'] = $hospitals;
			}
		}
		
		return $schema;
	}
	
	/**
	 * Add financial service properties
	 */
	private function add_financial_properties( $schema, $post ) {
		// Add service types
		$services = get_post_meta( $post->ID, '_bw_schema_financial_services', true );
		if ( ! empty( $services ) && is_array( $services ) ) {
			$schema['knowsAbout'] = array_filter( $services );
		}
		
		// Add certifications
		$certifications = get_post_meta( $post->ID, '_bw_schema_financial_certifications', true );
		if ( ! empty( $certifications ) && is_array( $certifications ) ) {
			$certs = array();
			foreach ( $certifications as $cert ) {
				if ( ! empty( $cert ) ) {
					$certs[] = array(
						'@type' => 'EducationalOccupationalCredential',
						'name' => $cert,
					);
				}
			}
			if ( ! empty( $certs ) ) {
				$schema['hasCredential'] = $certs;
			}
		}
		
		return $schema;
	}
	
	/**
	 * Add real estate agent properties
	 */
	private function add_real_estate_properties( $schema, $post ) {
		// Add service areas
		$service_areas = get_post_meta( $post->ID, '_bw_schema_service_areas', true );
		if ( ! empty( $service_areas ) && is_array( $service_areas ) ) {
			$areas = array();
			foreach ( $service_areas as $area ) {
				if ( ! empty( $area ) ) {
					$areas[] = array(
						'@type' => 'City',
						'name' => $area,
					);
				}
			}
			if ( ! empty( $areas ) ) {
				$schema['areaServed'] = $areas;
			}
		}
		
		// Add license number
		$license = get_post_meta( $post->ID, '_bw_schema_license_number', true );
		if ( ! empty( $license ) ) {
			$schema['hasCredential'] = array(
				'@type' => 'EducationalOccupationalCredential',
				'name' => 'Real Estate License',
				'credentialCategory' => 'license',
				'identifier' => $license,
			);
		}
		
		// Add specializations
		$specializations = get_post_meta( $post->ID, '_bw_schema_real_estate_specializations', true );
		if ( ! empty( $specializations ) && is_array( $specializations ) ) {
			$schema['knowsAbout'] = array_filter( $specializations );
		}
		
		return $schema;
	}
}