<?php
/**
 * Public salon discovery storefront.
 *
 * Combines the venue profile, portfolio, popular services, verified booking
 * reviews, favourites, rebooking, and PWA installation into one indexable page.
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

class YATOON_Discovery {
    public function __construct() {
        add_shortcode( 'yatoon_discovery', array( $this, 'render' ) );
        add_action( 'admin_init', array( $this, 'maybe_create_page' ) );
        add_action( 'admin_notices', array( $this, 'draft_notice' ) );
        add_action( 'wp_ajax_yatoon_sync_favorites', array( $this, 'ajax_sync_favorites' ) );
        add_action( 'wp_ajax_nopriv_yatoon_sync_favorites', array( $this, 'ajax_sync_favorites' ) );
    }

    public function maybe_create_page() {
        if ( ! current_user_can( 'manage_options' ) || get_option( 'yatoon_discovery_page_id', 0 ) ) { return; }
        $existing = get_page_by_path( 'salon-discovery', OBJECT, 'page' );
        $page_id = $existing ? (int) $existing->ID : wp_insert_post( array(
            'post_title'   => __( 'Discover Our Salon', 'yatoon-booking-system' ),
            'post_name'    => 'salon-discovery',
            'post_content' => '[yatoon_discovery]',
            'post_status'  => 'draft',
            'post_type'    => 'page',
        ) );
        if ( $page_id && ! is_wp_error( $page_id ) ) {
            update_option( 'yatoon_discovery_page_id', $page_id, false );
        }
    }

    public function draft_notice() {
        $page_id = absint( get_option( 'yatoon_discovery_page_id', 0 ) );
        if ( ! $page_id || 'draft' !== get_post_status( $page_id ) || ! current_user_can( 'manage_options' ) ) { return; }
        $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
        if ( ! $screen || false === strpos( (string) $screen->id, 'yatoon' ) ) { return; }
        echo '<div class="notice notice-info"><p><strong>' . esc_html__( 'Your salon discovery page is ready.', 'yatoon-booking-system' ) . '</strong> ' . esc_html__( 'Review the venue details, portfolio, services, and verified reviews, then publish it when ready.', 'yatoon-booking-system' ) . ' <a href="' . esc_url( get_edit_post_link( $page_id ) ) . '">' . esc_html__( 'Review discovery page', 'yatoon-booking-system' ) . '</a></p></div>';
    }

    private function booking_url( $service_id = 0 ) {
        $url = (string) get_option( 'yatoon_book_new_url', get_option( 'yatoon_booking_page_url', '' ) );
        if ( ! $url ) {
            $page_id = absint( get_option( 'yatoon_booking_page_id', 0 ) );
            $url = $page_id ? get_permalink( $page_id ) : home_url( '/' );
        }
        return $service_id ? add_query_arg( 'yatoon_service', absint( $service_id ), $url ) : $url;
    }

    private function review_summary() {
        global $wpdb;
        $table = $wpdb->prefix . 'yatoon_reviews';
        if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) { return array( 0, 0 ); }
        $row = $wpdb->get_row( "SELECT COUNT(*) AS total, AVG(rating) AS average FROM {$table} WHERE status='approved' AND booking_id>0" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        return array( (int) ( $row->total ?? 0 ), round( (float) ( $row->average ?? 0 ), 1 ) );
    }

    private function popular_services() {
        global $wpdb;
        return (array) $wpdb->get_results( "SELECT s.*, COUNT(b.id) AS booking_count FROM {$wpdb->prefix}yatoon_services s LEFT JOIN {$wpdb->prefix}yatoon_bookings b ON b.service_id=s.id AND b.status NOT IN ('cancelled','cancelled_by_customer','no_show') WHERE s.is_active=1 GROUP BY s.id ORDER BY s.is_featured DESC, booking_count DESC, s.sort_order ASC, s.name ASC LIMIT 8" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    }

    private function recent_rebook() {
        if ( ! class_exists( 'YATOON_Customer_Portal' ) || ! YATOON_Customer_Portal::get_instance() ) { return null; }
        $customer = (array) YATOON_Customer_Portal::get_instance()->current_customer();
        $email = sanitize_email( $customer['email'] ?? '' );
        if ( ! $email ) { return null; }
        global $wpdb;
        return $wpdb->get_row( $wpdb->prepare( "SELECT b.service_id,s.name FROM {$wpdb->prefix}yatoon_bookings b JOIN {$wpdb->prefix}yatoon_services s ON s.id=b.service_id WHERE b.customer_email=%s AND b.status NOT IN ('cancelled','cancelled_by_customer','no_show') ORDER BY b.start_time DESC LIMIT 1", $email ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    }

    /** Stable, privacy-safe key for a verified portal identity. */
    private function customer_key() {
        if ( ! class_exists( 'YATOON_Customer_Portal' ) || ! YATOON_Customer_Portal::get_instance() ) { return ''; }
        $customer = (array) YATOON_Customer_Portal::get_instance()->current_customer();
        $identity = strtolower( trim( (string) ( $customer['email'] ?? $customer['phone'] ?? '' ) ) );
        return $identity ? hash_hmac( 'sha256', $identity, wp_salt( 'auth' ) ) : '';
    }

    /** Merge device favourites across browsers after verified customer sign-in. */
    public function ajax_sync_favorites() {
        check_ajax_referer( 'yatoon_discovery_nonce', 'nonce' );
        if ( function_exists( 'yatoon_public_rate_limit' ) ) { yatoon_public_rate_limit( 'favorite_sync', 30, 10 ); }
        $customer_key = $this->customer_key();
        if ( ! $customer_key ) { wp_send_json_error( array( 'message' => __( 'Sign in to sync favorites across devices.', 'yatoon-booking-system' ) ), 401 ); }
        global $wpdb;
        $table = $wpdb->prefix . 'yatoon_customer_favorites';
        $mode = sanitize_key( wp_unslash( $_POST['mode'] ?? 'list' ) );
        if ( 'replace' === $mode ) {
            $ids = json_decode( wp_unslash( $_POST['favorites'] ?? '[]' ), true );
            $ids = array_slice( array_values( array_unique( array_filter( array_map( 'absint', is_array( $ids ) ? $ids : array() ) ) ) ), 0, 50 );
            $valid = array();
            foreach ( $ids as $service_id ) {
                if ( $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}yatoon_services WHERE id=%d AND is_active=1", $service_id ) ) ) { $valid[] = $service_id; }
            }
            $wpdb->delete( $table, array( 'customer_key' => $customer_key ), array( '%s' ) );
            foreach ( $valid as $service_id ) {
                $wpdb->insert( $table, array( 'customer_key' => $customer_key, 'service_id' => $service_id, 'created_at' => current_time( 'mysql' ) ), array( '%s', '%d', '%s' ) );
            }
        }
        $favorites = array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT service_id FROM {$table} WHERE customer_key=%s ORDER BY created_at ASC", $customer_key ) ) );
        wp_send_json_success( array( 'favorites' => $favorites ) );
    }

    public function render() {
        // 4.6.1 V2: use the minified and RTL variants now that the build
        // pipeline produces them. This stylesheet had neither before, so an
        // Arabic or Hebrew site got an unflipped layout on the discovery page.
        $discovery_css = 'assets/css/discovery' . YATOON_ASSET_SUFFIX . ( is_rtl() ? '-rtl' : '' ) . '.css';
        if ( ! file_exists( SBS_PLUGIN_DIR . $discovery_css ) ) {
            $discovery_css = 'assets/css/discovery.css';
        }
        wp_enqueue_style( 'yatoon-discovery', SBS_PLUGIN_URL . $discovery_css, array(), SBS_VERSION . '.' . filemtime( SBS_PLUGIN_DIR . $discovery_css ) );
        wp_add_inline_style( 'yatoon-discovery', '.yatoon-discovery-locations{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}.yatoon-discovery-locations>a{display:grid;gap:5px;padding:18px;color:#172033;border:1px solid #e5e7eb;border-radius:16px;background:#fff;text-decoration:none}.yatoon-discovery-locations span{color:#667085;font-size:13px}.yatoon-discovery-locations b{margin-top:6px;color:#9d174d;font-size:13px}' );
        $discovery_js = 'assets/js/discovery' . ( file_exists( SBS_PLUGIN_DIR . 'assets/js/discovery.min.js' ) && ! ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '.min' : '' ) . '.js';
        wp_enqueue_script( 'yatoon-discovery', SBS_PLUGIN_URL . $discovery_js, array(), SBS_VERSION . '.' . filemtime( SBS_PLUGIN_DIR . $discovery_js ), true );
        wp_localize_script( 'yatoon-discovery', 'yatoonDiscovery', array(
            'storageKey' => 'yatoon_favorite_services_v1',
            'ajaxUrl'    => admin_url( 'admin-ajax.php' ),
            'nonce'      => wp_create_nonce( 'yatoon_discovery_nonce' ),
            'syncEnabled'=> (bool) $this->customer_key(),
            'saved'      => __( 'Saved to favorites', 'yatoon-booking-system' ),
            'removed'    => __( 'Removed from favorites', 'yatoon-booking-system' ),
        ) );

        $name       = get_option( 'yatoon_business_name', get_bloginfo( 'name' ) );
        $address    = get_option( 'yatoon_business_address', get_option( 'sbs_business_address', '' ) );
        $phone      = get_option( 'yatoon_business_phone', get_option( 'yatoon_contact_phone', '' ) );
        $description= get_option( 'yatoon_business_description', get_bloginfo( 'description' ) );
        $services   = $this->popular_services();
        $locations  = class_exists( 'YATOON_Locations' ) ? (array) YATOON_Locations::get_all( true ) : array();
        $rebook     = $this->recent_rebook();
        list( $review_count, $rating ) = $this->review_summary();
        $portal_url = class_exists( 'YATOON_Customer_Portal' ) ? YATOON_Customer_Portal::portal_url() : '';

        $schema = array(
            '@context'      => 'https://schema.org',
            '@type'         => 'BeautySalon',
            'name'          => $name,
            'description'   => wp_strip_all_tags( $description ),
            'url'           => home_url( '/' ),
            'telephone'     => $phone,
            'address'       => $address,
            'aggregateRating' => $review_count ? array( '@type' => 'AggregateRating', 'ratingValue' => $rating, 'reviewCount' => $review_count ) : null,
        );
        $schema = array_filter( $schema, static function ( $value ) { return null !== $value && '' !== $value; } );

        ob_start(); ?>
        <div class="yatoon-discovery" data-favorites-ready="1">
            <script type="application/ld+json"><?php echo wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></script>
            <section class="yatoon-discovery-hero">
                <span class="yatoon-discovery-kicker"><?php esc_html_e( 'Book local. Feel your best.', 'yatoon-booking-system' ); ?></span>
                <h1><?php echo esc_html( $name ); ?></h1>
                <?php if ( $description ) : ?><p><?php echo esc_html( $description ); ?></p><?php endif; ?>
                <div class="yatoon-discovery-trust">
                    <?php if ( $review_count ) : ?><span aria-label="<?php echo esc_attr( sprintf( __( '%1$s out of 5 from %2$d verified appointments', 'yatoon-booking-system' ), $rating, $review_count ) ); ?>">★ <?php echo esc_html( $rating ); ?> · <?php echo esc_html( sprintf( _n( '%d verified appointment', '%d verified appointments', $review_count, 'yatoon-booking-system' ), $review_count ) ); ?></span><?php endif; ?>
                    <?php if ( $address ) : ?><span>⌖ <?php echo esc_html( $address ); ?></span><?php endif; ?>
                    <?php if ( $phone ) : ?><a href="tel:<?php echo esc_attr( preg_replace( '/[^0-9+]/', '', $phone ) ); ?>">☎ <?php echo esc_html( $phone ); ?></a><?php endif; ?>
                </div>
                <div class="yatoon-discovery-actions">
                    <a class="yatoon-discovery-primary" href="<?php echo esc_url( $this->booking_url() ); ?>"><?php esc_html_e( 'Book an appointment', 'yatoon-booking-system' ); ?></a>
                    <?php if ( $portal_url ) : ?><a href="<?php echo esc_url( $portal_url ); ?>"><?php esc_html_e( 'My appointments', 'yatoon-booking-system' ); ?></a><?php endif; ?>
                    <button type="button" class="yatoon-install-app" hidden><?php esc_html_e( 'Install customer app', 'yatoon-booking-system' ); ?></button>
                </div>
                <?php if ( $rebook ) : ?><a class="yatoon-rebook-card" href="<?php echo esc_url( $this->booking_url( $rebook->service_id ) ); ?>"><span><?php esc_html_e( 'Your recent service', 'yatoon-booking-system' ); ?></span><strong><?php echo esc_html( $rebook->name ); ?></strong><b><?php esc_html_e( 'Book again', 'yatoon-booking-system' ); ?> →</b></a><?php endif; ?>
            </section>

            <?php if ( count( $locations ) > 1 ) : ?><section class="yatoon-discovery-section"><div class="yatoon-discovery-heading"><div><span><?php esc_html_e( 'Near you', 'yatoon-booking-system' ); ?></span><h2><?php esc_html_e( 'Choose a salon location', 'yatoon-booking-system' ); ?></h2></div></div><div class="yatoon-discovery-locations"><?php foreach ( $locations as $location ) : ?><a href="<?php echo esc_url( add_query_arg( 'yatoon_location', $location->slug ?: $location->id, $this->booking_url() ) ); ?>"><strong><?php echo esc_html( $location->name ); ?></strong><?php if ( ! empty( $location->address ) ) : ?><span><?php echo esc_html( $location->address ); ?></span><?php endif; ?><b><?php esc_html_e( 'View availability', 'yatoon-booking-system' ); ?> →</b></a><?php endforeach; ?></div></section><?php endif; ?>

            <?php if ( $services ) : ?><section class="yatoon-discovery-section"><div class="yatoon-discovery-heading"><div><span><?php esc_html_e( 'Popular nearby', 'yatoon-booking-system' ); ?></span><h2><?php esc_html_e( 'Client favorites', 'yatoon-booking-system' ); ?></h2></div><p><?php esc_html_e( 'Save services on this device and come back whenever you are ready.', 'yatoon-booking-system' ); ?></p></div><div class="yatoon-discovery-services">
                <?php foreach ( $services as $service ) : ?><article class="yatoon-discovery-service" data-service-id="<?php echo esc_attr( $service->id ); ?>">
                    <?php if ( $service->image_url ) : ?><img src="<?php echo esc_url( $service->image_url ); ?>" alt="<?php echo esc_attr( $service->name ); ?>" loading="lazy"><?php endif; ?>
                    <button type="button" class="yatoon-favorite" data-favorite-service="<?php echo esc_attr( $service->id ); ?>" aria-pressed="false" aria-label="<?php echo esc_attr( sprintf( __( 'Save %s to favorites', 'yatoon-booking-system' ), $service->name ) ); ?>">♡</button>
                    <div><h3><?php echo esc_html( $service->name ); ?></h3><p><?php echo esc_html( wp_trim_words( $service->description, 16 ) ); ?></p><span><?php echo esc_html( $service->duration_minutes ); ?> min · <?php echo esc_html( sprintf( __( 'From %s', 'yatoon-booking-system' ), class_exists( 'YATOON_Tax' ) ? YATOON_Tax::format_money( $service->price ) : strtoupper( get_option( 'yatoon_currency', 'USD' ) ) . ' ' . number_format_i18n( (float) $service->price, 2 ) ) ); ?></span><a href="<?php echo esc_url( $this->booking_url( $service->id ) ); ?>"><?php esc_html_e( 'Book', 'yatoon-booking-system' ); ?> →</a></div>
                </article><?php endforeach; ?>
            </div></section><?php endif; ?>

            <section class="yatoon-discovery-section"><div class="yatoon-discovery-heading"><div><span><?php esc_html_e( 'Our work', 'yatoon-booking-system' ); ?></span><h2><?php esc_html_e( 'Salon portfolio', 'yatoon-booking-system' ); ?></h2></div></div><?php echo do_shortcode( '[yatoon_gallery mode="grid" limit="12" cols="4" captions="1"]' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></section>
            <section class="yatoon-discovery-section"><div class="yatoon-discovery-heading"><div><span><?php esc_html_e( 'Explore', 'yatoon-booking-system' ); ?></span><h2><?php esc_html_e( 'Services and pricing', 'yatoon-booking-system' ); ?></h2></div></div><?php echo do_shortcode( '[yatoon_service_menu]' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></section>
            <?php if ( shortcode_exists( 'yatoon_reviews' ) ) : ?><section class="yatoon-discovery-section"><div class="yatoon-discovery-heading"><div><span><?php esc_html_e( 'Real visits', 'yatoon-booking-system' ); ?></span><h2><?php esc_html_e( 'Verified client reviews', 'yatoon-booking-system' ); ?></h2></div><p><?php esc_html_e( 'Every verified badge is tied to a completed appointment in this booking system.', 'yatoon-booking-system' ); ?></p></div><?php echo do_shortcode( '[yatoon_reviews limit="6" min_rating="1"]' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></section><?php endif; ?>
        </div>
        <?php return ob_get_clean();
    }
}
