<?php
/**
 * WidgetRegisterForm.
 *
 * Displays WPrequal widget in widget areas.
 *
 * @since 1.1
 */

namespace WPrequal;

use WP_Widget;

if ( ! defined( 'ABSPATH' ) ) {
    wp_die( 'Access denied!!' );
}

class WidgetRegisterForm extends WP_Widget {

    /** constructor */
    public function __construct() {
        parent::__construct(
            'wprequal_register_form',
            __( 'WPrequal Register Form', 'wprequal' ),
            array( 'description' => __( 'Add a register form', 'wprequal' ), )
        );
    }

    /** @see WP_Widget::widget */
    public function widget( $args, $instance ) {

        echo wp_kses_post( $args['before_widget'] );

        if ( ! empty( $instance['title'] ) ) {
            echo wp_kses_post( $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'] );
        }

        if ( ! empty( $instance['content'] ) ) {
            printf( '<div>%s</div>', wp_kses_post( $instance['content'] ) );
        }

        $post_id = isset( $instance['post_id'] ) ? $instance['post_id'] : false;

        do_action( 'wprequal_register_form', $post_id );

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

    }

    /**
     * Back-end widget form.
     *
     * @param array $instance Previously saved values from database.
     *
     * @see WP_Widget::form()
     *
     */
    public function form( $instance ) {

        $post_id = isset( $instance['post_id'] ) ? $instance['post_id'] : '';

        view( 'contact/widget', 'register-form', [
            'title'        => ! empty( $instance['title'] ) ? $instance['title'] : '',
            'content'      => ! empty( $instance['content'] ) ? $instance['content'] : '',
            'title_id'     => $this->get_field_id( 'title' ),
            'content_id'   => $this->get_field_id( 'content' ),
            'title_name'   => $this->get_field_name( 'title' ),
            'content_name' => $this->get_field_name( 'content' ),
            'post_id'      => $post_id,
            'args_name'    => $this->get_field_name( 'post_id' )
        ] );

    }

    /**
     * Sanitize widget form values as they are saved.
     *
     * @param array $new_instance Values just sent to be saved.
     * @param array $old_instance Previously saved values from database.
     *
     * @return array Updated safe values to be saved.
     * @see WP_Widget::update()
     *
     */
    public function update( $new_instance, $old_instance ) {
        $instance            = array();
        $instance['title']   = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : '';
        $instance['content'] = ( ! empty( $new_instance['content'] ) ) ? wp_kses_post( $new_instance['content'] ) : '';
        $instance['post_id'] = intval( $new_instance['post_id'] );

        return $instance;
    }

}