<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://profiles.wordpress.org/gohelkunjan
 * @since      1.0.0
 *
 * @package    KG_Digital_Catalog_For_WooCommerce
 * @subpackage KG_Digital_Catalog_For_WooCommerce/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    KG_Digital_Catalog_For_WooCommerce
 * @subpackage KG_Digital_Catalog_For_WooCommerce/admin
 * @author     gohelkunjan 
 */
class KGDC_Admin {
	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $kgdc_plugin_name;
	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $kgdc_version;
	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {
		$this->kgdc_plugin_name = $plugin_name;
		$this->kgdc_version = $version;

	}
	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function kgdc_enqueue_styles() {
		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in KGDC_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The KGDC_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
		wp_enqueue_style( $this->kgdc_plugin_name, plugin_dir_url( __FILE__ ) . 'css/kg-digital-catalog-for-woocommerce-admin.css', array(), $this->kgdc_version, 'all' );
		wp_enqueue_style( 'thickbox' );
	}
	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function kgdc_enqueue_scripts( $hook ) {
		if ( ! did_action( 'wp_enqueue_media' ) ) {
			wp_enqueue_media();
		}
		wp_enqueue_script( $this->kgdc_plugin_name, plugin_dir_url( __FILE__ ) . 'js/easy_wpcp.js', array( 'jquery' ), $this->kgdc_version, false );
		wp_enqueue_script( 'thickbox' );    	 

		// Localize script with AJAX URL and nonce for secure requests
		wp_localize_script( $this->kgdc_plugin_name, 'kgdc_admin', array(
			'ajax_url' => admin_url( 'admin-ajax.php' ),
			'email_nonce' => wp_create_nonce( 'kgdc_email_user_action' ),
			'export_nonce' => wp_create_nonce( 'kgdc_export_all_nonce' ),
		) );

		// Enqueue history page script specifically if on the relevant admin page
		if ( 'edit-kgdc_pdf_history' === $hook || 'pdf-catalog_page_catalog_options' === $hook ) {
			wp_enqueue_script( 'kgdc-admin-history', plugin_dir_url( __FILE__ ) . 'js/kgdc-admin-history.js', array( 'jquery' ), $this->kgdc_version, true );
			wp_localize_script( 'kgdc-admin-history', 'kgdc_admin_history', array(
				'sending'           => __( 'Sending...', 'kg-digital-catalog-for-woocommerce' ),
				'send_now'          => __( 'Send Catalog Now', 'kg-digital-catalog-for-woocommerce' ),
				'unexpected_error'  => __( 'Unexpected error', 'kg-digital-catalog-for-woocommerce' ),
				'request_failed'    => __( 'Request failed', 'kg-digital-catalog-for-woocommerce' ),
				'select_customer'   => __( 'Please select at least one customer.', 'kg-digital-catalog-for-woocommerce' ),
			) );
		}
	}
	public function kgdc_pdf_catalog_register_settings() {

		add_option( 'kgdc_pdfexport_options_group', 'This is my option value.' );
		register_setting( 'kgdc_pdfexport_options_group', 'kgdc_compnay_name', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'kgdc_pdfexport_options_group', 'kgdc_compnay_link', array( 'sanitize_callback' => 'esc_url_raw' ) );
		register_setting( 'kgdc_pdfexport_options_group', 'kgdc_compnay_logo', array( 'sanitize_callback' => 'esc_url_raw' ) );
		register_setting( 'kgdc_pdfexport_options_group', 'kgdc_compnay_address', array( 'sanitize_callback' => 'sanitize_textarea_field' ) );
		register_setting( 'kgdc_pdfexport_options_group', 'kgdc_email_id', array( 'sanitize_callback' => 'sanitize_email' ) );
		register_setting( 'kgdc_pdfexport_options_group', 'kgdc_phone_number', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'kgdc_pdfexport_options_group', 'kgdc_pdf_layout_type', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'kgdc_pdfexport_options_group', 'kgdc_coupan_code', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'kgdc_pdfexport_options_group', 'kgdc_button_text', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'kgdc_pdfexport_options_group', 'kgdc_disable_logo', array( 'sanitize_callback' => 'absint' ) );
	}
	public function kgdc_pdf_catelog_options_page() {
		
		if ( is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
			add_submenu_page( 'edit.php?post_type=kgdc_pdf_history', 'WooCommerce Products Catalog Settings', 'Settings', 'manage_options', 'catalog_options', 'kgdc_pdf_options_page' );
		} else {
			add_options_page('WooCommerce Products Catalog Settings', 'Settings', 'manage_options', 'catalog_options', 'kgdc_pdf_options_page');
		}
	}
}
function kgdc_pdf_options_page(){
	include dirname( __FILE__ ) . '/partials/kg-digital-catalog-for-woocommerce-admin-history.php';
	include dirname( __FILE__ ) . '/partials/kg-digital-catalog-for-woocommerce-admin-display.php';
}

add_action( 'wp_ajax_kgdc_email_user', 'kgdc_email_user' );

function kgdc_email_user() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( __( 'Forbidden', 'kg-digital-catalog-for-woocommerce' ), 403 );
	}

	check_ajax_referer( 'kgdc_email_user_action', 'security' );

	// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
	$customers = isset( $_POST['customer_id'] ) ? (array) wp_unslash( $_POST['customer_id'] ) : array();
	$customers = array_map( 'intval', $customers );

	$emails = array();
	foreach ( $customers as $customer_id ) {
		$user_info = get_userdata( $customer_id );
		if ( $user_info && ! empty( $user_info->user_email ) ) {
			$emails[] = sanitize_email( $user_info->user_email );
		}
	}

	if ( empty( $emails ) ) {
		wp_send_json_error( __( 'No recipients specified', 'kg-digital-catalog-for-woocommerce' ) );
	}

	$cname = get_option('kgdc_compnay_name');
	if ( empty($cname) ) {
		$cname = get_bloginfo('name');
	}
	
	$admin_email = get_option('kgdc_email_id');
	if ( empty($admin_email) ) {
		$admin_email = get_option('admin_email');
	}

	$company_link = get_option('kgdc_compnay_link');
	$company_phone = get_option('kgdc_phone_number');
	$company_address = get_option('kgdc_compnay_address');

	/* translators: %s: Company Name */
	$subject = sprintf( __( 'Your New Products Catalog from %s', 'kg-digital-catalog-for-woocommerce' ), $cname );
	
	$footer_html = '<table width="100%" cellpadding="0" cellspacing="0" border="0" style="font-size: 13px; color: #888; line-height: 1.6; margin-top: 5px;"><tr>';
	
	// Left Column: Address
	$footer_html .= '<td width="50%" valign="top" style="text-align: left; padding-right: 15px; border-right: 1px solid #eee;">';
	$footer_html .= '<p style="margin: 0 0 6px 0; font-weight: bold; font-size: 15px; color: #333;">' . esc_html($cname) . '</p>';
	if ( !empty($company_address) ) {
		$footer_html .= '<p style="margin: 0;">' . nl2br(esc_html($company_address)) . '</p>';
	}
	$footer_html .= '</td>';

	// Right Column: Contact Info
	$footer_html .= '<td width="50%" valign="top" style="text-align: right; padding-left: 15px;">';
	if ( !empty($company_phone) ) {
		$footer_html .= '<p style="margin: 0 0 6px 0;"><strong>' . esc_html__('Phone:', 'kg-digital-catalog-for-woocommerce') . '</strong> ' . esc_html($company_phone) . '</p>';
	}
	if ( !empty($admin_email) ) {
		$footer_html .= '<p style="margin: 0 0 6px 0;"><strong>' . esc_html__('Email:', 'kg-digital-catalog-for-woocommerce') . '</strong> <a href="mailto:' . esc_attr($admin_email) . '" style="color: #0a5fa5; text-decoration: none;">' . esc_html($admin_email) . '</a></p>';
	}
	if ( !empty($company_link) ) {
		$footer_html .= '<p style="margin: 0;"><strong>' . esc_html__('Web:', 'kg-digital-catalog-for-woocommerce') . '</strong> <a href="' . esc_url($company_link) . '" style="color: #0a5fa5; text-decoration: none;">' . esc_html($company_link) . '</a></p>';
	}
	$footer_html .= '</td>';

	$footer_html .= '</tr></table>';

	// Create a professional HTML template
	$html_content = '
	<div style="font-family: Arial, sans-serif; max-width: 650px; margin: 0 auto; padding: 25px; border: 1px solid #e0e0e0; border-radius: 8px; background-color: #ffffff;">
		<div style="text-align: center; margin-bottom: 30px; border-bottom: 2px solid #f0f0f0; padding-bottom: 20px;">
			<h1 style="color: #2c3e50; margin: 0 0 10px 0; font-size: 26px;">' . esc_html($cname) . '</h1>
			<p style="color: #7f8c8d; font-size: 16px; margin: 0;">' . esc_html__('Digital Products Catalog', 'kg-digital-catalog-for-woocommerce') . '</p>
		</div>
		<div style="margin-bottom: 35px; line-height: 1.6; color: #444; font-size: 15px;">
			<p>' . esc_html__('Hello,', 'kg-digital-catalog-for-woocommerce') . '</p>
			<p>' . esc_html__('We are pleased to share our latest digital products catalog with you. Please find the high-quality PDF specifically attached to this email.', 'kg-digital-catalog-for-woocommerce') . '</p>
			<p>' . esc_html__('Feel free to reach out to our team directly using the contact methods below if you have any questions or would like to place an order.', 'kg-digital-catalog-for-woocommerce') . '</p>
		</div>
		<div style="border-top: 1px solid #eee; padding-top: 20px;">
			' . $footer_html . '
		</div>
	</div>';

	$url = isset( $_POST['pdfname'] ) ? esc_url_raw( wp_unslash( $_POST['pdfname'] ) ) : '';
	$upload_dir = wp_upload_dir();
	$file_path = $url ? $upload_dir['basedir'] . '/' . basename( $url ) : '';

	$headers = array();
	$headers[] = 'Content-Type: text/html; charset=UTF-8';
	$headers[] = 'From: ' . esc_html($cname) . ' <' . sanitize_email($admin_email) . '>';

	$attachments = array();
	if ( $file_path && is_file( $file_path ) ) {
		$attachments[] = $file_path;
	}

	$sent = wp_mail( $emails, $subject, $html_content, $headers, $attachments );

	if ( $sent ) {
		wp_send_json_success( __( 'Mail sent.', 'kg-digital-catalog-for-woocommerce' ) );
	}

	wp_send_json_error( __( 'Mail sending failed.', 'kg-digital-catalog-for-woocommerce' ) );
}

// Register Custom Post Type
function kgdc_pdf_post_type() {

  $labels = array(
	'name'                  => _x( 'PDF Catalog', 'Post Type General Name', 'kg-digital-catalog-for-woocommerce' ),
	'singular_name'         => _x( 'PDF Catalog', 'Post Type Singular Name', 'kg-digital-catalog-for-woocommerce' ),
	'menu_name'             => __( 'PDF Catalog', 'kg-digital-catalog-for-woocommerce' ),
	'name_admin_bar'        => __( 'PDF Catalog', 'kg-digital-catalog-for-woocommerce' ),
	'archives'              => __( 'Item Archives', 'kg-digital-catalog-for-woocommerce' ),
	'attributes'            => __( 'Item Attributes', 'kg-digital-catalog-for-woocommerce' ),
	'parent_item_colon'     => __( 'Parent Item:', 'kg-digital-catalog-for-woocommerce' ),
	'all_items'             => __( 'PDF History', 'kg-digital-catalog-for-woocommerce' ),
	'add_new_item'          => __( 'Add New Item', 'kg-digital-catalog-for-woocommerce' ),
	'add_new'               => __( 'Add New', 'kg-digital-catalog-for-woocommerce' ),
	'new_item'              => __( 'New Item', 'kg-digital-catalog-for-woocommerce' ),
	'edit_item'             => __( 'Edit Item', 'kg-digital-catalog-for-woocommerce' ),
	'update_item'           => __( 'Update Item', 'kg-digital-catalog-for-woocommerce' ),
	'view_item'             => __( 'View Item', 'kg-digital-catalog-for-woocommerce' ),
	'view_items'            => __( 'View Items', 'kg-digital-catalog-for-woocommerce' ),
	'search_items'          => __( 'Search Item', 'kg-digital-catalog-for-woocommerce' ),
	'not_found'             => __( 'Not found', 'kg-digital-catalog-for-woocommerce' ),
	'not_found_in_trash'    => __( 'Not found in Trash', 'kg-digital-catalog-for-woocommerce' ),
	'featured_image'        => __( 'Featured Image', 'kg-digital-catalog-for-woocommerce' ),
	'set_featured_image'    => __( 'Set featured image', 'kg-digital-catalog-for-woocommerce' ),
	'remove_featured_image' => __( 'Remove featured image', 'kg-digital-catalog-for-woocommerce' ),
	'use_featured_image'    => __( 'Use as featured image', 'kg-digital-catalog-for-woocommerce' ),
	'insert_into_item'      => __( 'Insert into item', 'kg-digital-catalog-for-woocommerce' ),
	'uploaded_to_this_item' => __( 'Uploaded to this item', 'kg-digital-catalog-for-woocommerce' ),
	'items_list'            => __( 'Items list', 'kg-digital-catalog-for-woocommerce' ),
	'items_list_navigation' => __( 'Items list navigation', 'kg-digital-catalog-for-woocommerce' ),
	'filter_items_list'     => __( 'Filter items list', 'kg-digital-catalog-for-woocommerce' ),
  );
  $args = array(
	'label'                 => __( 'Product PDF', 'kg-digital-catalog-for-woocommerce' ),
	'description'           => __( 'Product pdf', 'kg-digital-catalog-for-woocommerce' ),
    'labels'                => $labels,
    'supports'              => array( 'title', 'custom-fields' ),
    'hierarchical'          => false,
    'public'                => true,
    'show_ui'               => true,
    'show_in_menu'          => true,
    'menu_icon'             => 'dashicons-pdf',
    'menu_position'         => null,
    'show_in_admin_bar'     => true,
    'show_in_nav_menus'     => true,
    'can_export'            => true,
    'has_archive'           => false,
    'exclude_from_search'   => false,
    'publicly_queryable'    => true,
    'capability_type'       => 'page',
    'capabilities' => array(
    	'create_posts' => false,
    ),
  	'map_meta_cap' => true,    
  );
	register_post_type( 'kgdc_pdf_history', $args );
}
add_action( 'init', 'kgdc_pdf_post_type', 0 );

function kgdc_change_link( $permalink, $post ) {
	if ( isset( $post->post_type ) && 'kgdc_pdf_history' === $post->post_type ) {
		$meta = get_post_meta( $post->ID, 'kgdc_pdf_history', true );
		if ( $meta ) {
			$permalink = $meta;
		}
	}
	return $permalink;
}
add_filter( 'post_type_link', 'kgdc_change_link', 10, 2 );

add_filter( 'post_row_actions', 'kgdc_remove_row_actions', 10, 2 );
function kgdc_remove_row_actions( $actions, $post ) {
	$screen = get_current_screen();
	if ( ! $screen || ! isset( $screen->post_type ) || 'kgdc_pdf_history' !== $screen->post_type ) {
		return $actions;
	}
	if ( isset( $actions['edit'] ) ) {
		unset( $actions['edit'] );
	}
	if ( isset( $actions['inline hide-if-no-js'] ) ) {
		unset( $actions['inline hide-if-no-js'] );
	}
	return $actions;
}
