<?php
namespace BricksUltimate\ElementControls;

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class Forms {
	public function __construct() {
		//* Create the forms DB
		$this->create_forms_db();

		add_filter( "bricks/elements/form/controls", [ $this, 'add_form_controls' ], 10, 1 );

		//* Save the submitted forms data to database
		add_filter( 'bricks/form/response', [ $this, 'bu_save_form_entries_in_db'], 10, 2 );
		add_action( 'bricks/form/custom_action', [ $this, 'bu_save_entries_in_db' ] );
	}

	/**
	 * Adds title control in the form element
	 * 
	 * @param array $controls
	 * @return array $controls
	 */
	public function add_form_controls( $controls ) {
		$controls['form_title'] = [
			'tab'  			=> 'content',
			'type' 			=> 'text',
			'label' 		=> esc_html__('Form Title', 'bricksultimate'),
			'placeholder' 	=> esc_html__('Contact Form', 'bricksultimate'),
			'default' 		=> esc_html__('Contact Form', 'bricksultimate'),
		];

		return $controls;
	}

	/**
	 * Creates the DB for the bricks forms element
	 * 
	 * @return void
	 */
	function create_forms_db() {
		global $wpdb;
		$table_name = $wpdb->prefix.'brxe_forms';

		if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) {
			$charset_collate = $wpdb->get_charset_collate();

			$sql = "CREATE TABLE $table_name (
				id bigint(20) NOT NULL AUTO_INCREMENT,
				form_id varchar(20) NULL,
				form_value longtext NOT NULL,
				form_date datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
				PRIMARY KEY (id)
			) $charset_collate;";

			require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
			dbDelta( $sql );
		}
	}

	/**
	 * Saving the submitted data to database
	 * 
	 * @param array $response
	 * @param object $form
	 * 
	 * @return array
	 */
	public function bu_save_form_entries_in_db( $response, $form ) {
		$this->bu_save_entries_in_db( $form );

		return $response;
	}

	public function bu_save_entries_in_db( $form ) {
		global $wpdb;
		$table_name = $wpdb->prefix . 'brxe_forms';
		$index      = 0;

		$form_fields 	= $form->get_fields();
		$form_settings 	= $form->get_settings();
		$formData 		= [];

		foreach ( $form_fields as $key => $value ) {
			if ( strpos( $key, 'form-field-' ) === false ) {
				continue;
			}

			$label = 'Form Label';

			if ( ! empty( $form_settings['fields'][ $index ]['label'] ) ) {
				$label = $form_settings['fields'][ $index ]['label'];
			}

			$value = ! empty( $value ) && is_array( $value ) ? implode( ', ', $value ) : $value;

			$formData[ $label ] = $value;

			$index++;
		}

		$formData['formTitle'] 		= isset( $form_settings['form_title'] ) ? esc_html( $form_settings['form_title'] ) : 'Contact Form';
		$formData['postId'] 		= $form_fields['postId'];
		$formData['referrer'] 		= $form_fields['referrer'];
		$formData['form_status'] 	= 'unread';

		$wpdb->insert( $table_name, array(
			'form_id' 		=> $form_fields['formId'],
			'form_value'	=> serialize( $formData ),
			'form_date' 	=> current_time('Y-m-d H:i:s')
		) );
	}
}