<?php
/**
 * Business Hours Widget and Shortcode
 *
 * Displays business hours from the Business Listing settings.
 */

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

/**
 * Business Hours Widget
 */
class BLM_Hours_Widget extends WP_Widget {

    /**
     * Constructor
     */
    public function __construct() {
        parent::__construct(
            'blm_hours_widget',
            __( 'Business Hours', 'id-business-listing' ),
            array(
                'description' => __( 'Display your business hours from Business Listing.', 'id-business-listing' ),
                'classname'   => 'blm-hours-widget',
            )
        );
    }

    /**
     * Front-end display
     */
    public function widget( $args, $instance ) {
        $title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'Business Hours', 'id-business-listing' );
        $title = apply_filters( 'widget_title', $title, $instance, $this->id_base );

        $show_closed   = isset( $instance['show_closed'] ) ? (bool) $instance['show_closed'] : true;
        $highlight_today = isset( $instance['highlight_today'] ) ? (bool) $instance['highlight_today'] : true;
        $time_format   = ! empty( $instance['time_format'] ) ? $instance['time_format'] : '12';

        // Widget args are pre-escaped by WordPress core.
        echo wp_kses_post( $args['before_widget'] );

        if ( $title ) {
            echo wp_kses_post( $args['before_title'] ) . esc_html( $title ) . wp_kses_post( $args['after_title'] );
        }

        // Render method returns pre-escaped HTML.
        echo wp_kses_post( BLM_Hours_Display::render( array(
            'show_closed'     => $show_closed,
            'highlight_today' => $highlight_today,
            'time_format'     => $time_format,
        ) ) );

        echo wp_kses_post( $args['after_widget'] );
    }

    /**
     * Back-end widget form
     */
    public function form( $instance ) {
        $title           = ! empty( $instance['title'] ) ? $instance['title'] : __( 'Business Hours', 'id-business-listing' );
        $show_closed     = isset( $instance['show_closed'] ) ? (bool) $instance['show_closed'] : true;
        $highlight_today = isset( $instance['highlight_today'] ) ? (bool) $instance['highlight_today'] : true;
        $time_format     = ! empty( $instance['time_format'] ) ? $instance['time_format'] : '12';
        ?>
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">
                <?php esc_html_e( 'Title:', 'id-business-listing' ); ?>
            </label>
            <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
                   name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"
                   type="text" value="<?php echo esc_attr( $title ); ?>">
        </p>
        <p>
            <input class="checkbox" type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'show_closed' ) ); ?>"
                   name="<?php echo esc_attr( $this->get_field_name( 'show_closed' ) ); ?>"
                   <?php checked( $show_closed ); ?>>
            <label for="<?php echo esc_attr( $this->get_field_id( 'show_closed' ) ); ?>">
                <?php esc_html_e( 'Show closed days', 'id-business-listing' ); ?>
            </label>
        </p>
        <p>
            <input class="checkbox" type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'highlight_today' ) ); ?>"
                   name="<?php echo esc_attr( $this->get_field_name( 'highlight_today' ) ); ?>"
                   <?php checked( $highlight_today ); ?>>
            <label for="<?php echo esc_attr( $this->get_field_id( 'highlight_today' ) ); ?>">
                <?php esc_html_e( 'Highlight today', 'id-business-listing' ); ?>
            </label>
        </p>
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'time_format' ) ); ?>">
                <?php esc_html_e( 'Time format:', 'id-business-listing' ); ?>
            </label>
            <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'time_format' ) ); ?>"
                    name="<?php echo esc_attr( $this->get_field_name( 'time_format' ) ); ?>">
                <option value="12" <?php selected( $time_format, '12' ); ?>><?php esc_html_e( '12-hour (9:00 AM)', 'id-business-listing' ); ?></option>
                <option value="24" <?php selected( $time_format, '24' ); ?>><?php esc_html_e( '24-hour (09:00)', 'id-business-listing' ); ?></option>
            </select>
        </p>
        <?php
    }

    /**
     * Save widget settings
     */
    public function update( $new_instance, $old_instance ) {
        $instance = array();
        $instance['title']           = sanitize_text_field( $new_instance['title'] );
        $instance['show_closed']     = ! empty( $new_instance['show_closed'] );
        $instance['highlight_today'] = ! empty( $new_instance['highlight_today'] );
        $instance['time_format']     = in_array( $new_instance['time_format'], array( '12', '24' ), true ) ? $new_instance['time_format'] : '12';
        return $instance;
    }
}

/**
 * Business Hours Display Helper
 */
class BLM_Hours_Display {

    /**
     * Render business hours HTML
     *
     * @param array $atts Attributes
     * @return string HTML output
     */
    public static function render( $atts = array() ) {
        $defaults = array(
            'show_closed'     => true,
            'highlight_today' => true,
            'time_format'     => '12',
            'class'           => '',
        );

        $atts = wp_parse_args( $atts, $defaults );

        $data = get_option( 'blm_business_data', array() );

        // Check for 24/7
        if ( ! empty( $data['open_247'] ) ) {
            $class = 'blm-hours-display';
            if ( ! empty( $atts['class'] ) ) {
                $class .= ' ' . esc_attr( $atts['class'] );
            }
            return '<div class="' . $class . '"><p class="blm-hours-247">' . esc_html__( 'Open 24 hours a day, 7 days a week', 'id-business-listing' ) . '</p></div>';
        }

        $hours = isset( $data['hours'] ) ? $data['hours'] : array();

        if ( empty( $hours ) ) {
            return '<div class="blm-hours-display"><p class="blm-hours-none">' . esc_html__( 'Hours not available', 'id-business-listing' ) . '</p></div>';
        }

        $days = array(
            'monday'    => __( 'Monday', 'id-business-listing' ),
            'tuesday'   => __( 'Tuesday', 'id-business-listing' ),
            'wednesday' => __( 'Wednesday', 'id-business-listing' ),
            'thursday'  => __( 'Thursday', 'id-business-listing' ),
            'friday'    => __( 'Friday', 'id-business-listing' ),
            'saturday'  => __( 'Saturday', 'id-business-listing' ),
            'sunday'    => __( 'Sunday', 'id-business-listing' ),
        );

        $today = strtolower( current_time( 'l' ) );

        $class = 'blm-hours-display';
        if ( ! empty( $atts['class'] ) ) {
            $class .= ' ' . esc_attr( $atts['class'] );
        }

        $output = '<div class="' . $class . '">';
        $output .= '<ul class="blm-hours-list">';

        foreach ( $days as $day_key => $day_label ) {
            $day_data = isset( $hours[ $day_key ] ) ? $hours[ $day_key ] : array();
            $is_open  = ! empty( $day_data['open'] );

            // Skip closed days if show_closed is false
            if ( ! $is_open && ! $atts['show_closed'] ) {
                continue;
            }

            $is_today = ( $day_key === $today );
            $row_class = 'blm-hours-row';
            if ( $is_today && $atts['highlight_today'] ) {
                $row_class .= ' blm-hours-today';
            }
            if ( ! $is_open ) {
                $row_class .= ' blm-hours-closed';
            }

            $output .= '<li class="' . esc_attr( $row_class ) . '">';
            $output .= '<span class="blm-hours-day">' . esc_html( $day_label ) . '</span>';

            if ( $is_open ) {
                $open_time  = isset( $day_data['open_time'] ) ? $day_data['open_time'] : '09:00';
                $close_time = isset( $day_data['close_time'] ) ? $day_data['close_time'] : '17:00';

                $open_formatted  = self::format_time( $open_time, $atts['time_format'] );
                $close_formatted = self::format_time( $close_time, $atts['time_format'] );

                $output .= '<span class="blm-hours-time">' . esc_html( $open_formatted ) . ' &ndash; ' . esc_html( $close_formatted ) . '</span>';
            } else {
                $output .= '<span class="blm-hours-time blm-hours-closed-text">' . esc_html__( 'Closed', 'id-business-listing' ) . '</span>';
            }

            $output .= '</li>';
        }

        $output .= '</ul>';
        $output .= '</div>';

        return $output;
    }

    /**
     * Format time string
     *
     * @param string $time   Time in H:i format
     * @param string $format '12' or '24'
     * @return string Formatted time
     */
    private static function format_time( $time, $format = '12' ) {
        if ( empty( $time ) ) {
            return '';
        }

        $timestamp = strtotime( $time );
        if ( false === $timestamp ) {
            return $time;
        }

        if ( '24' === $format ) {
            return gmdate( 'H:i', $timestamp );
        }

        return gmdate( 'g:i A', $timestamp );
    }
}

/**
 * Register widget
 */
function blm_register_hours_widget() {
    register_widget( 'BLM_Hours_Widget' );
}
add_action( 'widgets_init', 'blm_register_hours_widget' );

/**
 * Business Hours Shortcode
 *
 * Usage: [business_hours]
 * Attributes:
 *   - show_closed: "yes" or "no" (default: "yes")
 *   - highlight_today: "yes" or "no" (default: "yes")
 *   - time_format: "12" or "24" (default: "12")
 *   - class: Additional CSS class
 *
 * @param array $atts Shortcode attributes
 * @return string HTML output
 */
function blm_business_hours_shortcode( $atts ) {
    $atts = shortcode_atts(
        array(
            'show_closed'     => 'yes',
            'highlight_today' => 'yes',
            'time_format'     => '12',
            'class'           => '',
        ),
        $atts,
        'business_hours'
    );

    return BLM_Hours_Display::render( array(
        'show_closed'     => ( 'yes' === strtolower( $atts['show_closed'] ) ),
        'highlight_today' => ( 'yes' === strtolower( $atts['highlight_today'] ) ),
        'time_format'     => $atts['time_format'],
        'class'           => $atts['class'],
    ) );
}
add_shortcode( 'business_hours', 'blm_business_hours_shortcode' );
