<?php
/**
 * Livada SEO — Locations (Multi-LocalBusiness) View
 *
 * Lets the operator configure 1+ business locations, each emitted as its own
 * LocalBusiness JSON-LD node. Suitable for multi-camping operators, hotel
 * groups, or any business with several physical sites.
 *
 * @package Livada_SEO
 */

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

// Read locations from the dedicated option (fall back to legacy single-location).
$locations = get_option( 'livada_seo_locations', [] );
if ( ! is_array( $locations ) ) {
	$locations = [];
}

// When the option is empty AND a legacy LocalBusiness is configured, surface
// the legacy data as the first row so the user can edit it in place.
if ( empty( $locations ) && class_exists( 'Livada_SEO_Schema' ) ) {
	$legacy = Livada_SEO_Schema::get_locations();
	if ( ! empty( $legacy ) ) {
		$locations = $legacy;
	}
}

$schema_type_choices = [
	'LocalBusiness'    => __( 'Local Business (generic)',   'livada-seo' ),
	'Organization'     => __( 'Organization',               'livada-seo' ),
	'Campground'       => __( 'Campground',                 'livada-seo' ),
	'LodgingBusiness'  => __( 'Lodging Business (generic)', 'livada-seo' ),
	'Hotel'            => __( 'Hotel',                      'livada-seo' ),
	'BedAndBreakfast'  => __( 'Bed & Breakfast',            'livada-seo' ),
	'Resort'           => __( 'Resort',                     'livada-seo' ),
	'Hostel'           => __( 'Hostel',                     'livada-seo' ),
	'Motel'            => __( 'Motel',                      'livada-seo' ),
	'Restaurant'       => __( 'Restaurant',                 'livada-seo' ),
	'Store'            => __( 'Store',                      'livada-seo' ),
	'TouristAttraction'=> __( 'Tourist Attraction',         'livada-seo' ),
];

$days = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ];

/**
 * Renders one location row given a 0-based index and an associative array.
 * Used both for the existing rows and for the hidden template clone target.
 *
 * @param int                     $i     Index (use `__IDX__` for the template).
 * @param array<string,mixed>     $loc   Location data, may be empty.
 * @param array<string,string>    $types schema_type choices.
 * @param string[]                $days  Day list.
 * @param bool                    $tpl   Whether this is the hidden template row.
 */
$render_row = function ( $i, array $loc, array $types, array $days, bool $tpl = false ) {
	$idx_attr  = $tpl ? '__IDX__' : (string) $i;
	$style_tpl = $tpl ? ' style="display:none;"' : '';
	$header_n  = $tpl ? '' : ( ' #' . ( (int) $i + 1 ) );
	$open_attr = ( $tpl || empty( $loc['name'] ) ) ? '' : ' open';

	$amenities     = is_array( $loc['amenities']     ?? null ) ? $loc['amenities']     : [];
	$opening_hours = is_array( $loc['opening_hours'] ?? null ) ? $loc['opening_hours'] : [];
	$same_as       = is_array( $loc['same_as']       ?? null ) ? $loc['same_as']       : [];
	$services      = is_array( $loc['services']      ?? null ) ? $loc['services']      : [];

	?>
	<details class="livada-repeater-row livada-repeater-row--block<?php echo $tpl ? ' livada-repeater-template' : ''; ?>"<?php echo $open_attr; echo $tpl ? ' aria-hidden="true"' : ''; echo $style_tpl; ?>>
		<summary class="livada-repeater-row__header" style="cursor:pointer;">
			<strong><?php esc_html_e( 'Location', 'livada-seo' ); ?><?php echo esc_html( $header_n ); ?> — <?php echo esc_html( $loc['name'] ?? __( '(new)', 'livada-seo' ) ); ?></strong>
			<button type="button" class="button-link livada-repeater-remove" aria-label="<?php esc_attr_e( 'Remove location', 'livada-seo' ); ?>">&#10005;</button>
		</summary>

		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'Name', 'livada-seo' ); ?> <span style="color:#d63638;">*</span></th>
					<td>
						<input type="text" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][name]" value="<?php echo esc_attr( $loc['name'] ?? '' ); ?>" class="regular-text" required>
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Schema type', 'livada-seo' ); ?></th>
					<td>
						<select name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][type]">
							<?php foreach ( $types as $value => $label ) : ?>
								<option value="<?php echo esc_attr( $value ); ?>"<?php selected( $loc['type'] ?? 'LocalBusiness', $value ); ?>>
									<?php echo esc_html( $label ); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Address', 'livada-seo' ); ?></th>
					<td>
						<input type="text" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][address]" value="<?php echo esc_attr( $loc['address'] ?? '' ); ?>" class="regular-text" placeholder="123 rue Example">
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'City', 'livada-seo' ); ?></th>
					<td>
						<input type="text" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][city]" value="<?php echo esc_attr( $loc['city'] ?? '' ); ?>" class="regular-text">
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Postal / Country', 'livada-seo' ); ?></th>
					<td>
						<input type="text" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][postal]" value="<?php echo esc_attr( $loc['postal'] ?? '' ); ?>" class="small-text" placeholder="04120">
						<input type="text" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][country]" value="<?php echo esc_attr( $loc['country'] ?? 'FR' ); ?>" class="small-text" maxlength="2" placeholder="FR" style="margin-left:8px;">
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Phone / Email', 'livada-seo' ); ?></th>
					<td>
						<input type="text"  name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][phone]" value="<?php echo esc_attr( $loc['phone'] ?? '' ); ?>" class="regular-text" placeholder="+33 …">
						<input type="email" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][email]" value="<?php echo esc_attr( $loc['email'] ?? '' ); ?>" class="regular-text" placeholder="email@…" style="margin-left:8px;">
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Website / Logo', 'livada-seo' ); ?></th>
					<td>
						<input type="url" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][url]" value="<?php echo esc_url( $loc['url'] ?? '' ); ?>" class="regular-text" placeholder="https://">
						<br>
						<input type="url" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][logo]" value="<?php echo esc_url( $loc['logo'] ?? '' ); ?>" class="regular-text" placeholder="<?php esc_attr_e( 'Logo URL', 'livada-seo' ); ?>" style="margin-top:4px;">
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Geo (lat / lng)', 'livada-seo' ); ?></th>
					<td>
						<input type="text" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][geo_lat]" value="<?php echo esc_attr( $loc['geo_lat'] ?? '' ); ?>" class="small-text" placeholder="43.8479">
						<input type="text" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][geo_lng]" value="<?php echo esc_attr( $loc['geo_lng'] ?? '' ); ?>" class="small-text" placeholder="6.5126" style="margin-left:8px;">
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Price range', 'livada-seo' ); ?></th>
					<td>
						<input type="text" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][price_range]" value="<?php echo esc_attr( $loc['price_range'] ?? '' ); ?>" class="small-text" placeholder="€€">
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Star rating', 'livada-seo' ); ?></th>
					<td>
						<input type="number" min="1" max="5" step="0.5" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][star_rating]" value="<?php echo esc_attr( $loc['star_rating'] ?? '' ); ?>" class="small-text" placeholder="4">
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Rooms / Pitches', 'livada-seo' ); ?></th>
					<td>
						<input type="number" min="0" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][number_of_rooms]" value="<?php echo esc_attr( $loc['number_of_rooms'] ?? '' ); ?>" class="small-text" placeholder="80">
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Pets allowed', 'livada-seo' ); ?></th>
					<td>
						<select name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][pets_allowed]">
							<option value=""<?php selected( $loc['pets_allowed'] ?? '', '' ); ?>><?php esc_html_e( '— Unspecified —', 'livada-seo' ); ?></option>
							<option value="1"<?php selected( $loc['pets_allowed'] ?? '', '1' ); ?>><?php esc_html_e( 'Yes', 'livada-seo' ); ?></option>
							<option value="0"<?php selected( $loc['pets_allowed'] ?? '', '0' ); ?>><?php esc_html_e( 'No', 'livada-seo' ); ?></option>
						</select>
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Check-in / out', 'livada-seo' ); ?></th>
					<td>
						<input type="time" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][checkin_time]"  value="<?php echo esc_attr( $loc['checkin_time']  ?? '' ); ?>" class="small-text">
						<input type="time" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][checkout_time]" value="<?php echo esc_attr( $loc['checkout_time'] ?? '' ); ?>" class="small-text" style="margin-left:8px;">
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Aggregate rating', 'livada-seo' ); ?></th>
					<td>
						<input type="number" min="1" max="5" step="0.1" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][rating_value]" value="<?php echo esc_attr( $loc['rating_value'] ?? '' ); ?>" class="small-text" placeholder="4.7">
						<input type="number" min="1" name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][review_count]" value="<?php echo esc_attr( $loc['review_count'] ?? '' ); ?>" class="small-text" placeholder="120" style="margin-left:8px;">
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Amenities', 'livada-seo' ); ?></th>
					<td>
						<textarea name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][amenities_csv]" rows="2" class="large-text" placeholder="<?php esc_attr_e( 'Pool, Wi-Fi, Restaurant, Pétanque, Playground, Bar', 'livada-seo' ); ?>"><?php
							// Render each entry as either a name string or "name|0" when explicitly disabled.
							$lines = [];
							foreach ( $amenities as $a ) {
								if ( is_string( $a ) ) {
									$lines[] = $a;
								} elseif ( is_array( $a ) ) {
									$n = (string) ( $a['name']  ?? '' );
									$v = (string) ( $a['value'] ?? '1' );
									if ( '' === $n ) { continue; }
									$lines[] = ( '0' === $v ) ? $n . '|0' : $n;
								}
							}
							echo esc_textarea( implode( ', ', $lines ) );
						?></textarea>
						<p class="description">
							<?php esc_html_e( 'Comma-separated list. Suffix any entry with "|0" to mark it as not available (e.g. "Air conditioning|0").', 'livada-seo' ); ?>
						</p>
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Same-as URLs', 'livada-seo' ); ?></th>
					<td>
						<textarea name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][same_as_csv]" rows="3" class="large-text" placeholder="https://www.facebook.com/&#10;https://www.instagram.com/"><?php
							echo esc_textarea( implode( "\n", array_map( 'strval', $same_as ) ) );
						?></textarea>
						<p class="description"><?php esc_html_e( 'One URL per line.', 'livada-seo' ); ?></p>
					</td>
				</tr>

				<tr>
					<th scope="row"><?php esc_html_e( 'Services', 'livada-seo' ); ?></th>
					<td>
						<textarea name="livada_seo_locations[<?php echo esc_attr( $idx_attr ); ?>][services_csv]" rows="3" class="large-text" placeholder="<?php esc_attr_e( 'Camping pitches | Tent + 2 pax + 1 car&#10;Mobile-home rental | 4 to 6 pax', 'livada-seo' ); ?>"><?php
							$lines = [];
							foreach ( $services as $s ) {
								if ( is_string( $s ) ) {
									$lines[] = $s;
								} elseif ( is_array( $s ) ) {
									$n = (string) ( $s['name']        ?? '' );
									$d = (string) ( $s['description'] ?? '' );
									if ( '' === $n ) { continue; }
									$lines[] = '' !== $d ? "$n | $d" : $n;
								}
							}
							echo esc_textarea( implode( "\n", $lines ) );
						?></textarea>
						<p class="description"><?php esc_html_e( 'One service per line. Optional description after a "|" pipe.', 'livada-seo' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>
	</details>
	<?php
};
?>
<div class="wrap livada-seo-wrap has-ls-hero">
<?php include LIVADA_SEO_PATH . 'includes/admin/views/_partials/header.php'; ?>
	<h1><?php esc_html_e( 'Locations (Multi-LocalBusiness)', 'livada-seo' ); ?></h1>

	<?php if ( isset( $_GET['updated'] ) ) : // phpcs:ignore ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Settings saved.', 'livada-seo' ); ?></p></div>
	<?php endif; ?>

	<p class="description" style="max-width:780px;">
		<?php esc_html_e( 'Each location is emitted as its own LocalBusiness JSON-LD node. The first location keeps the legacy "#localbusiness" anchor for backward compatibility; subsequent ones use "#localbusiness-2", "#localbusiness-3", … On a per-post basis you can attach any post to a specific location via the SEO metabox.', 'livada-seo' ); ?>
	</p>
	<p class="description" style="max-width:780px;">
		<strong><?php esc_html_e( 'Migration tip:', 'livada-seo' ); ?></strong>
		<?php esc_html_e( 'Saving this page once will migrate any legacy LocalBusiness data (Schema settings page) into the multi-location store. The legacy fields stay as a fallback until you remove them.', 'livada-seo' ); ?>
	</p>

	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<?php wp_nonce_field( 'livada_seo_save_locations' ); ?>
		<input type="hidden" name="action" value="livada_seo_save_locations">

		<div id="livada-locations-repeater" class="livada-repeater livada-repeater--block">
			<?php foreach ( $locations as $i => $loc ) : ?>
				<?php $render_row( (int) $i, is_array( $loc ) ? $loc : [], $schema_type_choices, $days, false ); ?>
			<?php endforeach; ?>

			<?php $render_row( 0, [], $schema_type_choices, $days, true ); ?>
		</div>

		<p>
			<button type="button" class="button livada-repeater-add" data-target="livada-locations-repeater">
				<?php esc_html_e( '+ Add Location', 'livada-seo' ); ?>
			</button>
		</p>

		<?php submit_button( __( 'Save Locations', 'livada-seo' ) ); ?>
	</form>
</div>
