<?php

class Sas_Subscription{
    public function __construct() {
        add_action('init', array($this, 'sas_subscription' ));
		add_action('init', array($this, 'submit_post' ));
        $this->config = json_decode( $this->config, true );
		$this->process_cpts();
		add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ] );
		add_action( 'save_post', [ $this, 'save_post' ] );
    }

    public function sas_subscription() {
        $supports = array(
            'revisions',
            'post-formats',
        );
    
        $labels = array(
            'name' => _x('Subscriptions', 'plural'),
            'singular_name' => _x('Subscription', 'singular'),
            'menu_name' => _x('Subscriptions', 'admin menu'),
            'name_admin_bar' => _x('Subscriptions', 'admin bar'),
            'add_new' => _x('Add new', 'add new'),
            'add_new_item' => __('Add new email'),
            'new_item' => __('New email'),
            'edit_item' => __('Edit email'),
            'view_item' => __('View email'),
            'all_items' => __('All subscriptions'),
            'search_items' => __('Search email'),
            'not_found' => __('No subscriptions found'),
        );
    
        $args = array(
            'supports' => $supports,
            'labels' => $labels,
            'public' => true,
            'query_var' => true,
            'rewrite' => array('slug' => 'subscriptions'),
            'hierarchical' => false,
            'show_in_menu' => true,
            'menu_position' => 4,
            'menu_icon'   => 'dashicons-email',
        );
    
        register_post_type('sas-subscription', $args);
    }

    private $config = '
        {
            "title":"Email",
            "prefix":"sas_subscription_email",
            "domain":"subscription_email",
            "class_name":"Subscription_Email",
            "post-type":["post"],
            "context":"normal",
            "priority":"default",
            "cpt":"sas-subscription",
            "fields":[
                {
                    "type":"text",
                    "label":"Email",
                    "id":"sas_subscription_email"
                }
            ]
        }
	';

	public function process_cpts() {
		if ( !empty( $this->config['cpt'] ) ) {
			if ( empty( $this->config['post-type'] ) ) {
				$this->config['post-type'] = [];
			}
			$parts = explode( ',', $this->config['cpt'] );
			$parts = array_map( 'trim', $parts );
			$this->config['post-type'] = array_merge( $this->config['post-type'], $parts );
		}
	}

	public function add_meta_boxes() {
		foreach ( $this->config['post-type'] as $screen ) {
			add_meta_box(
				sanitize_title( $this->config['title'] ),
				$this->config['title'],
				[ $this, 'add_meta_box_callback' ],
				$screen,
				$this->config['context'],
				$this->config['priority']
			);
		}
	}

	public function save_post( $post_id ) {
		foreach ( $this->config['fields'] as $field ) {
			switch ( $field['type'] ) {
				default:
					if ( isset( $_POST[ $field['id'] ] ) ) {
						$sanitized = sanitize_text_field( $_POST[ $field['id'] ] );
						update_post_meta( $post_id, $field['id'], $sanitized );
					}
			}
		}
	}

	public function add_meta_box_callback() {
		$this->fields_table();
	}

	private function fields_table() {
		?><table class="form-table" role="presentation">
			<tbody><?php
				foreach ( $this->config['fields'] as $field ) {
					?><tr>
						<td><?php $this->field( $field ); ?></td>
					</tr><?php
				}
			?></tbody>
		</table><?php
	}

	private function label( $field ) {
		switch ( $field['type'] ) {
			default:
				printf(
					'<label class="" for="%s">%s</label>',
					$field['id'], $field['label']
				);
		}
	}

	private function field( $field ) {
		switch ( $field['type'] ) {
			default:
				$this->input( $field );
		}
	}

	private function input( $field ) {
		printf(
			'<input class="regular-text %s" id="%s" name="%s" %s type="%s" value="%s">',
			isset( $field['class'] ) ? $field['class'] : '',
			$field['id'], $field['id'],
			isset( $field['pattern'] ) ? "pattern='{$field['pattern']}'" : '',
			$field['type'],
			$this->value( $field )
		);
	}

	private function value( $field ) {
		global $post;
		if ( metadata_exists( 'post', $post->ID, $field['id'] ) ) {
			$value = get_post_meta( $post->ID, $field['id'], true );
		} else if ( isset( $field['default'] ) ) {
			$value = $field['default'];
		} else {
			return '';
		}
		return str_replace( '\u0027', "'", $value );
	}

	public function submit_post(){
		if( 'POST' == $_SERVER['REQUEST_METHOD'] && isset($_POST['action']) && $_POST['action'] == "subscribe") {

			$email = $_POST['email'];
		
			$new_post = array(
				'post_title'    => $email,
				'post_status'   => 'publish',
				'post_type' => 'sas-subscription'
			);
		
			$pid = wp_insert_post($new_post);
			add_post_meta($pid, 'sas_subscription_email', $email, true);
		}
	}
}