<?php
/**
 * The public-facing functionality of the plugin.
 *
 * @package    Cloudi7_ID_Card_Generator
 * @subpackage Cloudi7_ID_Card_Generator/public
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Cloudi7_ICG_Public
 *
 * Defines public-side hooks for enqueuing styles / scripts and
 * registering shortcodes.
 */
class Cloudi7_ICG_Public {

	/**
	 * The plugin version.
	 *
	 * @var string $version
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @param string $version The current version of the plugin.
	 */
	public function __construct( $version ) {
		$this->version = $version;
	}

	/**
	 * Register the stylesheets for the public-facing side of the site.
	 *
	 * @return void
	 */
	public function enqueue_styles() {
		wp_enqueue_style(
			'cloudi7-icg-public',
			Cloudi7_ICG_PLUGIN_URL . 'assets/css/cloudi7-icg-public.css',
			array(),
			$this->version,
			'all'
		);
		
		wp_enqueue_style(
			'cloudi7-icg-card',
			Cloudi7_ICG_PLUGIN_URL . 'assets/css/card.css',
			array(),
			$this->version,
			'all'
		);

		// Template Specific Styles
		$skin = get_option( 'cloudi7_icg_template_skin', 'modern' );
		wp_enqueue_style(
			'cloudi7-icg-template-style',
			Cloudi7_ICG_PLUGIN_URL . 'templates/' . $skin . '/style.css',
			array( 'cloudi7-icg-card' ),
			$this->version,
			'all'
		);
	}

	/**
	 * Register the JavaScript for the public-facing side of the site.
	 *
	 * @return void
	 */
	public function enqueue_scripts() {
		wp_enqueue_script(
			'cloudi7-icg-html2canvas',
			Cloudi7_ICG_PLUGIN_URL . 'assets/js/libs/html2canvas.min.js',
			array(),
			'1.4.1',
			true
		);

		wp_enqueue_script(
			'cloudi7-icg-public',
			Cloudi7_ICG_PLUGIN_URL . 'assets/js/cloudi7-icg-public.js',
			array( 'jquery', 'cloudi7-icg-html2canvas' ),
			$this->version,
			true
		);
	}

	/**
	 * Render the [cloudi7_icg_verify] shortcode.
	 *
	 * @return string The form and verification result.
	 */
	public function render_cloudi7_icg_verify() {
		global $wpdb;
		$cloudi7_icg_table_name = $wpdb->prefix . 'cloudi7_icg_cards';
		$cloudi7_icg_output     = '';
		$cloudi7_icg_card       = null;
		$cloudi7_icg_error      = '';

		// Handle Direct Verification via URL (?verify_id=ID-00001)
		if ( isset( $_GET['verify_id'] ) ) {
			$cloudi7_icg_id_number = sanitize_text_field( wp_unslash( $_GET['verify_id'] ) );
			$cloudi7_icg_cache_key = 'cloudi7_icg_data_card_verify_' . sanitize_title( $cloudi7_icg_id_number );
			$cloudi7_icg_card = wp_cache_get( $cloudi7_icg_cache_key );
			if ( false === $cloudi7_icg_card ) {
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
				$cloudi7_icg_card = $wpdb->get_row( $wpdb->prepare( 
					"SELECT * FROM {$wpdb->prefix}cloudi7_icg_cards WHERE id_number = %s", 
					$cloudi7_icg_id_number 
				) );
				wp_cache_set( $cloudi7_icg_cache_key, $cloudi7_icg_card );
			}
			
			if ( ! $cloudi7_icg_card ) {
				$cloudi7_icg_error = esc_html__( 'Invalid ID Card Number.', 'cloudi7-id-card-generator' );
			}
		} 
		// Handle Form Submission
		elseif ( isset( $_POST['cloudi7_icg_verify_id'] ) ) {
			if ( ! isset( $_POST['cloudi7_icg_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['cloudi7_icg_nonce'] ) ), 'cloudi7_icg_verify_action' ) ) {
				$cloudi7_icg_error = esc_html__( 'Security verification failed.', 'cloudi7-id-card-generator' );
			} else {
				$cloudi7_icg_id_number = isset( $_POST['cloudi7_icg_id_number'] ) ? sanitize_text_field( wp_unslash( $_POST['cloudi7_icg_id_number'] ) ) : '';
				
				if ( empty( $cloudi7_icg_id_number ) ) {
					$cloudi7_icg_error = esc_html__( 'Please enter an ID number.', 'cloudi7-id-card-generator' );
				} else {
					$cloudi7_icg_cache_key = 'cloudi7_icg_data_card_verify_' . sanitize_title( $cloudi7_icg_id_number );
					$cloudi7_icg_card = wp_cache_get( $cloudi7_icg_cache_key );
					if ( false === $cloudi7_icg_card ) {
						// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
						$cloudi7_icg_card = $wpdb->get_row( $wpdb->prepare( 
							"SELECT * FROM {$wpdb->prefix}cloudi7_icg_cards WHERE id_number = %s", 
							$cloudi7_icg_id_number 
						) );
						wp_cache_set( $cloudi7_icg_cache_key, $cloudi7_icg_card );
					}

					if ( ! $cloudi7_icg_card ) {
						$cloudi7_icg_error = esc_html__( 'Invalid ID Card Number.', 'cloudi7-id-card-generator' );
					}
				}
			}
		}

		ob_start();
		include Cloudi7_ICG_PLUGIN_DIR . 'templates/verify-card.php';
		$cloudi7_icg_output = ob_get_clean();

		return $cloudi7_icg_output;
	}

	/**
	 * Handle the application form submission before page rendering.
	 * Hooked to template_redirect.
	 */
	public function handle_form_submission() {
		if ( ! isset( $_POST['cloudi7_icg_form_submitted'] ) ) {
			return;
		}

		if ( ! isset( $_POST['cloudi7_icg_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['cloudi7_icg_nonce'] ) ), 'cloudi7_icg_action' ) ) {
			set_transient( 'cloudi7_icg_form_error_' . get_current_user_id(), esc_html__( 'Security verification failed. Please try again.', 'cloudi7-id-card-generator' ), 30 );
			return;
		}

		global $wpdb;
		$cloudi7_icg_table_name = $wpdb->prefix . 'cloudi7_icg_applications';
		$cloudi7_icg_error = '';

		// Process Photo Upload
		$cloudi7_icg_photo_url = '';
		if ( ! empty( $_FILES['photo']['name'] ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
			
			$cloudi7_icg_upload = wp_handle_upload( $_FILES['photo'], array( 'test_form' => false ) );
			if ( isset( $cloudi7_icg_upload['url'] ) ) {
				$cloudi7_icg_photo_url = esc_url_raw( $cloudi7_icg_upload['url'] );
			} else {
				$cloudi7_icg_error = esc_html__( 'Photo upload failed: ', 'cloudi7-id-card-generator' ) . sanitize_text_field( $cloudi7_icg_upload['error'] );
			}
		}

		if ( empty( $cloudi7_icg_error ) ) {
			$cloudi7_icg_org_type = isset( $_POST['org_type'] ) ? sanitize_text_field( wp_unslash( $_POST['org_type'] ) ) : '';
			$cloudi7_icg_org_details = array();

			// Collect dynamic details based on type
			if ( 'School' === $cloudi7_icg_org_type ) {
				$cloudi7_icg_org_details['class'] = isset( $_POST['school_class'] ) ? sanitize_text_field( wp_unslash( $_POST['school_class'] ) ) : '';
				$cloudi7_icg_org_details['roll']  = isset( $_POST['school_roll'] ) ? sanitize_text_field( wp_unslash( $_POST['school_roll'] ) ) : '';
			} elseif ( 'Corporate' === $cloudi7_icg_org_type ) {
				$cloudi7_icg_org_details['department']  = isset( $_POST['dept'] ) ? sanitize_text_field( wp_unslash( $_POST['dept'] ) ) : '';
				$cloudi7_icg_org_details['designation'] = isset( $_POST['designation'] ) ? sanitize_text_field( wp_unslash( $_POST['designation'] ) ) : '';
				$cloudi7_icg_org_details['employee_id'] = isset( $_POST['emp_id'] ) ? sanitize_text_field( wp_unslash( $_POST['emp_id'] ) ) : '';
			} elseif ( 'Event' === $cloudi7_icg_org_type ) {
				$cloudi7_icg_org_details['role']         = isset( $_POST['event_role'] ) ? sanitize_text_field( wp_unslash( $_POST['event_role'] ) ) : '';
				$cloudi7_icg_org_details['organization'] = isset( $_POST['company'] ) ? sanitize_text_field( wp_unslash( $_POST['company'] ) ) : '';
			} elseif ( 'Club' === $cloudi7_icg_org_type ) {
				$cloudi7_icg_org_details['membership_id'] = isset( $_POST['member_id'] ) ? sanitize_text_field( wp_unslash( $_POST['member_id'] ) ) : '';
				$cloudi7_icg_org_details['membership_type'] = isset( $_POST['mem_type'] ) ? sanitize_text_field( wp_unslash( $_POST['mem_type'] ) ) : '';
			} elseif ( 'Media' === $cloudi7_icg_org_type ) {
				$cloudi7_icg_org_details['media_house'] = isset( $_POST['media_house'] ) ? sanitize_text_field( wp_unslash( $_POST['media_house'] ) ) : '';
				$cloudi7_icg_org_details['role']        = isset( $_POST['media_role'] ) ? sanitize_text_field( wp_unslash( $_POST['media_role'] ) ) : '';
			}

			// Clean and format data
			$cloudi7_icg_dob = ! empty( $_POST['dob'] ) ? sanitize_text_field( wp_unslash( $_POST['dob'] ) ) : null;
			
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
			$cloudi7_icg_inserted = $wpdb->insert( $cloudi7_icg_table_name, array(
				'name'         => isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '',
				'email'        => isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '',
				'phone'        => isset( $_POST['phone'] ) ? sanitize_text_field( wp_unslash( $_POST['phone'] ) ) : '',
				'photo'        => $cloudi7_icg_photo_url,
				'org_type'     => $cloudi7_icg_org_type,
				'org_details'  => wp_json_encode( $cloudi7_icg_org_details ),
				'dob'          => $cloudi7_icg_dob,
				'gov_id'       => isset( $_POST['gov_id'] ) ? sanitize_text_field( wp_unslash( $_POST['gov_id'] ) ) : '',
				'parent_name'  => isset( $_POST['parent_name'] ) ? sanitize_text_field( wp_unslash( $_POST['parent_name'] ) ) : '',
				'parent_phone' => isset( $_POST['parent_phone'] ) ? sanitize_text_field( wp_unslash( $_POST['parent_phone'] ) ) : '',
				'blood_group'  => isset( $_POST['blood_group'] ) ? sanitize_text_field( wp_unslash( $_POST['blood_group'] ) ) : '',
				'status'       => 'pending',
				'created_at'   => current_time( 'mysql' ),
			) );

			if ( false === $cloudi7_icg_inserted ) {
				$cloudi7_icg_error = esc_html__( 'Database Error: ', 'cloudi7-id-card-generator' ) . sanitize_text_field( $wpdb->last_error );
			} else {
				wp_cache_delete( 'cloudi7_icg_data_total_items_apps' );
				wp_cache_delete( 'cloudi7_icg_data_pending_apps_count' );
				
				$cloudi7_icg_redirect_url = add_query_arg( 'cloudi7_icg_app_success', '1', remove_query_arg( array( 'cloudi7_icg_app_success', 'cloudi7_icg_app_error' ) ) );
				wp_safe_redirect( esc_url_raw( $cloudi7_icg_redirect_url ) );
				exit;
			}
		}

		if ( ! empty( $cloudi7_icg_error ) ) {
			$cloudi7_icg_redirect_url = add_query_arg( 'cloudi7_icg_app_error', urlencode($cloudi7_icg_error), remove_query_arg( array( 'cloudi7_icg_app_success', 'cloudi7_icg_app_error' ) ) );
			wp_safe_redirect( esc_url_raw( $cloudi7_icg_redirect_url ) );
			exit;
		}
	}

	/**
	 * Render the [cloudi7_icg_apply] shortcode.
	 */
	public function render_cloudi7_icg_apply() {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$cloudi7_icg_error = isset( $_GET['cloudi7_icg_app_error'] ) ? sanitize_text_field( urldecode( wp_unslash( $_GET['cloudi7_icg_app_error'] ) ) ) : '';

		ob_start();
		include Cloudi7_ICG_PLUGIN_DIR . 'templates/apply-form.php';
		return ob_get_clean();
	}
}
