<?php
/**
 * Server-side render for playard/field-list block.
 *
 * @var array<string,mixed> $attributes
 * @var string              $content
 * @var WP_Block            $block
 */
if ( ! defined( 'ABSPATH' ) ) exit;

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

global $wpdb;

// ── Read attributes ──────────────────────────────────────────────────────────
$cols             = max( 1, min( 4, (int) ( $attributes['columns']          ?? 3       ) ) );
$card_style       = sanitize_key( (string) ( $attributes['cardStyle']       ?? 'card'  ) );
$show_photo       = (bool) ( $attributes['showPhoto']       ?? true  );
$show_sports      = (bool) ( $attributes['showSports']      ?? true  );
$show_price       = (bool) ( $attributes['showPrice']       ?? true  );
$show_description = (bool) ( $attributes['showDescription'] ?? false );
$show_button      = (bool) ( $attributes['showButton']      ?? true  );
$btn_text         = sanitize_text_field( (string) ( $attributes['buttonText']   ?? 'Book Now' ) );
$btn_style_key    = sanitize_key( (string) ( $attributes['buttonStyle']     ?? 'primary' ) );
$btn_action       = sanitize_key( (string) ( $attributes['buttonAction']    ?? 'link'    ) );
$booking_url      = esc_url( sanitize_url( (string) ( $attributes['bookingPage'] ?? '' ) ) );

// ── Style attributes ─────────────────────────────────────────────────────────
$img_height     = sanitize_key( (string) ( $attributes['imgHeight']      ?? 'medium' ) );
$card_radius    = sanitize_key( (string) ( $attributes['cardRadius']     ?? 'soft'   ) );
$card_shadow    = sanitize_key( (string) ( $attributes['cardShadow']     ?? 'soft'   ) );
$spacing        = sanitize_key( (string) ( $attributes['spacing']        ?? 'normal' ) );
$title_size_raw = (int) ( $attributes['titleSize'] ?? 0 );

$card_bg      = sanitize_hex_color( (string) ( $attributes['cardBg']          ?? '' ) ) ?: '#FFFFFF';
$border_color = sanitize_hex_color( (string) ( $attributes['cardBorderColor'] ?? '' ) );
$title_color  = sanitize_hex_color( (string) ( $attributes['titleColor']      ?? '' ) ) ?: '#0F172A';
$price_color  = sanitize_hex_color( (string) ( $attributes['priceColor']      ?? '' ) ) ?: '#3B82F6';
$badge_bg     = sanitize_hex_color( (string) ( $attributes['badgeBg']         ?? '' ) ) ?: '#EFF6FF';
$badge_color  = sanitize_hex_color( (string) ( $attributes['badgeColor']      ?? '' ) ) ?: '#1E40AF';

// Computed values from maps
$img_pb = [ 'short' => '42%', 'medium' => '58%', 'tall' => '78%' ][ $img_height ] ?? '58%';

$radius_val = [ 'none' => '0px', 'soft' => '14px', 'round' => '22px' ][ $card_radius ] ?? '14px';


$sp            = [ 'compact' => 0, 'normal' => 1, 'spacious' => 2 ][ $spacing ] ?? 1;
$body_padding  = [ '12px 14px', '16px 18px', '24px 28px' ][ $sp ];
$foot_padding  = [ '0 14px 12px', '0 18px 16px', '0 28px 24px' ][ $sp ];
$body_gap      = [ '4px', '8px', '14px' ][ $sp ];

$title_size    = $title_size_raw > 0 ? $title_size_raw . 'px' : '17px';
$border_css    = $border_color ? '1px solid ' . $border_color : 'none';

$btn_preset = [
	'primary' => 'background:#0F172A;color:#fff;border:none;',
	'accent'  => 'background:#3B82F6;color:#fff;border:none;',
	'outline' => 'background:transparent;color:#0F172A;border:2px solid #0F172A;',
];
$btn_css = $btn_preset[ $btn_style_key ] ?? $btn_preset['primary'];

$is_list = $card_style === 'list';

// ── Query fields ─────────────────────────────────────────────────────────────
$fields = $wpdb->get_results(
	"SELECT id, name, description, sports, photos, base_price
	 FROM {$wpdb->prefix}playard_fields
	 WHERE status = 'active'
	 ORDER BY sort_order ASC, id ASC"
);

if ( empty( $fields ) ) {
	echo '<p style="color:#94A3B8;font-size:14px;padding:16px 0;">'
	   . esc_html__( 'No active fields found.', 'playard' )
	   . '</p>';
	return;
}

$uid = 'pfl-' . wp_rand( 1000, 9999 );

// Build scoped CSS in a buffer, then emit via wp_add_inline_style() —
// WordPress.org forbids raw inline <style> tags in markup.
ob_start();
?>
/* ── Grid ─────────────────────────────────────────────────── */
.<?php echo esc_attr($uid); ?> .py-grid{display:grid;grid-template-columns:repeat(<?php echo esc_attr($cols); ?>,1fr);gap:20px;}

/* ── Card ─────────────────────────────────────────────────── */
.<?php echo esc_attr($uid); ?> .py-card{
  background:<?php echo esc_attr($card_bg); ?>;
  border:<?php echo esc_attr($border_css); ?>;
  border-radius:<?php echo esc_attr($radius_val); ?>;
  overflow:hidden;
  display:flex;
  flex-direction:column;
}

/* Image wrap */
.<?php echo esc_attr($uid); ?> .py-card__img-wrap{
  position:relative;
  width:100%;
  padding-bottom:<?php echo esc_attr($img_pb); ?>;
  overflow:hidden;
  background:#F1F5F9;
  flex-shrink:0;
}
.<?php echo esc_attr($uid); ?> .py-card__img{
  position:absolute;
  inset:0;
  width:100%;
  height:100%;
  object-fit:cover;
  display:block;
}
.<?php echo esc_attr($uid); ?> .py-card__img-ph{
  position:absolute;
  inset:0;
  display:flex;
  align-items:center;
  justify-content:center;
  flex-direction:column;
  gap:8px;
  background:linear-gradient(135deg,#F1F5F9 0%,#E2E8F0 100%);
}
.<?php echo esc_attr($uid); ?> .py-card__img-ph svg{opacity:.4;}
.<?php echo esc_attr($uid); ?> .py-card__img-ph span{
  font-size:11px;font-weight:600;color:#94A3B8;letter-spacing:.5px;text-transform:uppercase;
}

/* Card body */
.<?php echo esc_attr($uid); ?> .py-card__body{
  padding:<?php echo esc_attr($body_padding); ?>;
  flex:1;
  display:flex;
  flex-direction:column;
  gap:<?php echo esc_attr($body_gap); ?>;
}
.<?php echo esc_attr($uid); ?> .py-card__name{
  font-size:<?php echo esc_attr($title_size); ?>;
  font-weight:700;
  color:<?php echo esc_attr($title_color); ?>;
  margin:0;
  line-height:1.25;
}
.<?php echo esc_attr($uid); ?> .py-card__desc{
  font-size:13px;
  color:#64748B;
  margin:0;
  line-height:1.5;
}
.<?php echo esc_attr($uid); ?> .py-card__badges{display:flex;flex-wrap:wrap;gap:4px;margin:0;}
.<?php echo esc_attr($uid); ?> .py-card__badge{
  font-size:11px;
  font-weight:600;
  padding:3px 9px;
  border-radius:99px;
  background:<?php echo esc_attr($badge_bg); ?>;
  color:<?php echo esc_attr($badge_color); ?>;
  text-transform:capitalize;
  letter-spacing:.2px;
}
.<?php echo esc_attr($uid); ?> .py-card__price-row{display:flex;align-items:baseline;gap:4px;margin:0;}
.<?php echo esc_attr($uid); ?> .py-card__price{
  font-size:20px;
  font-weight:800;
  color:<?php echo esc_attr($price_color); ?>;
  line-height:1;
}
.<?php echo esc_attr($uid); ?> .py-card__price-label{
  font-size:12px;
  font-weight:500;
  color:#94A3B8;
}

/* Card footer */
.<?php echo esc_attr($uid); ?> .py-card__foot{padding:<?php echo esc_attr($foot_padding); ?>;}
.<?php echo esc_attr($uid); ?> .py-card__btn{
  display:block;
  text-align:center;
  padding:11px 0;
  border-radius:9px;
  __PLAYARD_BTN_CSS__
  font-size:14px;
  font-weight:600;
  text-decoration:none;
  cursor:pointer;
  width:100%;
  transition:opacity .15s,transform .1s;
  font-family:inherit;
}
.<?php echo esc_attr($uid); ?> .py-card__btn:hover{opacity:.88;transform:scale(.985);}

/* ── List rows ─────────────────────────────────────────────── */
.<?php echo esc_attr($uid); ?> .py-list{display:flex;flex-direction:column;gap:10px;}
.<?php echo esc_attr($uid); ?> .py-row{
  display:flex;
  align-items:center;
  gap:16px;
  padding:<?php echo esc_attr($body_padding); ?>;
  background:<?php echo esc_attr($card_bg); ?>;
  border:<?php echo esc_attr($border_css !== 'none' ? $border_css : '1px solid #E2E8F0'); ?>;
  border-radius:<?php echo esc_attr($radius_val); ?>;
}
.<?php echo esc_attr($uid); ?> .py-row__dot{
  width:10px;height:10px;border-radius:50%;
  background:<?php echo esc_attr($price_color); ?>;
  flex-shrink:0;
}
.<?php echo esc_attr($uid); ?> .py-row__info{flex:1;min-width:0;}
.<?php echo esc_attr($uid); ?> .py-row__name{
  font-size:<?php echo esc_attr($title_size); ?>;
  font-weight:700;
  color:<?php echo esc_attr($title_color); ?>;
  margin:0;
}
.<?php echo esc_attr($uid); ?> .py-row__meta{font-size:12px;color:#64748B;margin:3px 0 0;}
.<?php echo esc_attr($uid); ?> .py-row__right{display:flex;align-items:center;gap:12px;flex-shrink:0;}
.<?php echo esc_attr($uid); ?> .py-row__price{
  font-size:16px;
  font-weight:800;
  color:<?php echo esc_attr($price_color); ?>;
  white-space:nowrap;
}
.<?php echo esc_attr($uid); ?> .py-row__price span{font-size:11px;font-weight:500;color:#94A3B8;}
.<?php echo esc_attr($uid); ?> .py-row__btn{
  padding:8px 18px;
  border-radius:8px;
  __PLAYARD_BTN_CSS__
  font-size:13px;
  font-weight:600;
  text-decoration:none;
  white-space:nowrap;
  cursor:pointer;
  transition:opacity .15s;
  font-family:inherit;
}
.<?php echo esc_attr($uid); ?> .py-row__btn:hover{opacity:.85;}

@media(max-width:700px){
  .<?php echo esc_attr($uid); ?> .py-grid{grid-template-columns:1fr;}
  .<?php echo esc_attr($uid); ?> .py-row{flex-wrap:wrap;}
  .<?php echo esc_attr($uid); ?> .py-row__right{width:100%;justify-content:space-between;}
}
<?php
$playard_css    = ob_get_clean();
// Inject the button style (safe static preset) into the buffered CSS, then
// deliver everything through wp_add_inline_style() — no echo, no <style> tag.
$playard_css    = str_replace( '__PLAYARD_BTN_CSS__', $btn_css, $playard_css );
$playard_handle = 'playard-field-list-block';
wp_register_style( $playard_handle, false, [], PLAYARD_VERSION );
wp_enqueue_style( $playard_handle );
wp_add_inline_style( $playard_handle, $playard_css );
?>
<div class="<?php echo esc_attr($uid); ?>">

<?php if ( $is_list ) : ?>
  <div class="py-list">
  <?php foreach ( $fields as $field ) :
    $sports  = ! empty( $field->sports ) ? json_decode( (string) $field->sports, true ) : [];
    $price   = (float) ( $field->base_price ?? 0 );
    $btn_url = $booking_url ?: get_permalink();
    if ( $btn_action === 'modal' ) {
      $mc = playard_get_frontend_config();
      $mc['fields'] = (string) $field->id;
      $mc_json = wp_json_encode( $mc );
    }
  ?>
    <div class="py-row">
      <div class="py-row__dot"></div>
      <div class="py-row__info">
        <p class="py-row__name"><?php echo esc_html( $field->name ); ?></p>
        <?php if ( $show_sports && is_array( $sports ) && ! empty( $sports ) ) : ?>
          <p class="py-row__meta"><?php echo esc_html( implode( ' · ', $sports ) ); ?></p>
        <?php endif; ?>
        <?php if ( $show_description && ! empty( $field->description ) ) : ?>
          <p class="py-row__meta"><?php echo esc_html( mb_substr( (string) $field->description, 0, 100 ) . ( mb_strlen( (string) $field->description ) > 100 ? '…' : '' ) ); ?></p>
        <?php endif; ?>
      </div>
      <div class="py-row__right">
        <?php if ( $show_price && $price > 0 ) : ?>
          <p class="py-row__price">$<?php echo esc_html( number_format( $price, 0 ) ); ?> <span>/ slot</span></p>
        <?php endif; ?>
        <?php if ( $show_button ) : ?>
          <?php if ( $btn_action === 'modal' ) : ?>
            <button type="button" class="py-row__btn" data-playard-modal-trigger="1" data-config="<?php echo esc_attr( $mc_json ?? '{}' ); ?>"><?php echo esc_html( $btn_text ); ?></button>
          <?php else : ?>
            <a class="py-row__btn" href="<?php echo esc_url( $btn_url ); ?>"><?php echo esc_html( $btn_text ); ?></a>
          <?php endif; ?>
        <?php endif; ?>
      </div>
    </div>
  <?php endforeach; ?>
  </div>

<?php else : ?>
  <div class="py-grid">
  <?php foreach ( $fields as $field ) :
    $sports  = ! empty( $field->sports ) ? json_decode( (string) $field->sports, true ) : [];
    $photos  = ! empty( $field->photos ) ? json_decode( (string) $field->photos, true ) : [];
    $photo   = is_array( $photos ) && ! empty( $photos[0] ) ? esc_url_raw( (string) $photos[0] ) : '';
    $price   = (float) ( $field->base_price ?? 0 );
    $btn_url = $booking_url ?: get_permalink();
    if ( $btn_action === 'modal' ) {
      $mc = playard_get_frontend_config();
      $mc['fields'] = (string) $field->id;
      $mc_json = wp_json_encode( $mc );
    }
  ?>
    <article class="py-card">

      <?php if ( $show_photo ) : ?>
        <div class="py-card__img-wrap">
          <?php if ( $photo ) : ?>
            <img class="py-card__img" src="<?php echo esc_url( $photo ); ?>" alt="<?php echo esc_attr( $field->name ); ?>" loading="lazy" />
          <?php else : ?>
            <div class="py-card__img-ph">
              <svg width="36" height="36" fill="none" viewBox="0 0 24 24" stroke="#CBD5E1" stroke-width="1.2">
                <rect x="3" y="3" width="18" height="18" rx="2"/>
                <circle cx="8.5" cy="8.5" r="1.5"/>
                <path d="m21 15-5-5L5 21"/>
              </svg>
              <span>No photo</span>
            </div>
          <?php endif; ?>
        </div>
      <?php endif; ?>

      <div class="py-card__body">
        <h3 class="py-card__name"><?php echo esc_html( $field->name ); ?></h3>

        <?php if ( $show_description && ! empty( $field->description ) ) : ?>
          <p class="py-card__desc"><?php echo esc_html( mb_substr( (string) $field->description, 0, 90 ) . ( mb_strlen( (string) $field->description ) > 90 ? '…' : '' ) ); ?></p>
        <?php endif; ?>

        <?php if ( $show_sports && is_array( $sports ) && ! empty( $sports ) ) : ?>
          <div class="py-card__badges">
            <?php foreach ( array_slice( $sports, 0, 4 ) as $sport ) : ?>
              <span class="py-card__badge"><?php echo esc_html( $sport ); ?></span>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>

        <?php if ( $show_price && $price > 0 ) : ?>
          <div class="py-card__price-row">
            <span class="py-card__price">$<?php echo esc_html( number_format( $price, 0 ) ); ?></span>
            <span class="py-card__price-label">/ slot</span>
          </div>
        <?php endif; ?>
      </div>

      <?php if ( $show_button ) : ?>
        <div class="py-card__foot">
          <?php if ( $btn_action === 'modal' ) : ?>
            <button type="button" class="py-card__btn" data-playard-modal-trigger="1" data-config="<?php echo esc_attr( $mc_json ?? '{}' ); ?>"><?php echo esc_html( $btn_text ); ?></button>
          <?php else : ?>
            <a class="py-card__btn" href="<?php echo esc_url( $btn_url ); ?>"><?php echo esc_html( $btn_text ); ?></a>
          <?php endif; ?>
        </div>
      <?php endif; ?>

    </article>
  <?php endforeach; ?>
  </div>
<?php endif; ?>

</div>
