<?php


namespace Elex\MultiVendor\Controller;

if ( ! defined( 'ABSPATH' ) ) {
exit;
}

use Elex\MultiVendor\Model\AdminPayment;
use Elex\MultiVendor\Model\SiteSettings;

class AdminPaymentController {

	public static function init() {
		$self = new self();
		
		add_action( 'admin_menu', array( $self, 'elex_mv_payment_menu' ) );
		add_action( 'wp_ajax_elex_mv_payment_settlement', array( $self, 'elex_mv_payment_settlement' ) );
		add_action( 'wp_ajax_elex_mv_vendors_search_fields', array( $self, 'elex_mv_vendors_search_fields' ) );
		add_action( 'wp_ajax_nopriv_elex_mv_vendors_search_fields', array( $self, 'elex_mv_vendors_search_fields' ) );
		add_action( 'wp_ajax_elex_mv_settlement_history_data', array( self::class, 'elex_mv_settlement_history_data' ) );
		add_action( 'wp_ajax_elex_mv_export_settlement_vendor', array( self::class, 'elex_mv_export_settlement_vendor' ) );
	}
	public static function elex_mv_payment_menu() {
		$self          = new self();
		$site_settings = SiteSettings::load();

		if ( $site_settings->is_setup_finished( 'is_setup_finished' ) ) {
			add_submenu_page( 'elex-multi-vendor-for-woocommerce-dashboard', 'Elex Multi Vendor', 'Payments', 'admin_vendor_access', 'elex-multi-vendor-for-woocommerce-payments', array( $self, 'admin_payment_manage_page' ), 4 );
		}
	}
	public function elex_mv_vendors_search_fields() {
		if ( ! isset( $_POST['_ajax_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_ajax_nonce'] ) ), 'mv_nonce' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
	
		$vendors_data   = array();
		$vendors_result = array();
		if ( isset( $_POST['search'] ) && ! empty( $_POST['search'] ) ) {
			$filters = array(
				'role'    => 'elex_mv_vendor',
				'orderby' => 'user_nicename',
				's'       => sanitize_text_field( wp_unslash( $_POST['search'] ) ),
				'order'   => 'ASC',
			);
			// The Query
			$adminpayment = new AdminPayment();
			$vendors      = $adminpayment->vendor_payments( $filters );
	
					// User Loop
			foreach ( $vendors as $user ) {
				$vendors_data['id']   = $user->ID;
				$vendors_data['text'] = get_post_meta( $user->ID, 'elex_mv_user_name', true );
				$vendors_result[]     = $vendors_data;
			}       
		}
	  
		wp_send_json_success( $vendors_result ); 
	}
	public function admin_payment_manage_page() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		// Fetch and sanitize inputs safely from $_GET.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only pagination and filter parameters on access-controlled admin page.
		$raw_page_num   = isset( $_GET['page_num'] ) ? sanitize_text_field( wp_unslash( $_GET['page_num'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only pagination and filter parameters on access-controlled admin page.
		$raw_search     = isset( $_GET['search_term'] ) ? sanitize_text_field( wp_unslash( $_GET['search_term'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only pagination and filter parameters on access-controlled admin page.
		$raw_filter     = isset( $_GET['filter'] ) ? sanitize_text_field( wp_unslash( $_GET['filter'] ) ) : '';

		// Initialize base query filters
		$vendor_per_page = 10;
		$current_page    = ! empty( $raw_page_num ) ? absint( $raw_page_num ) : 1;

		$filters = array(
			'orderby'     => 'ID',
			'numberposts' => $vendor_per_page, // How many per page
			'paged'       => $current_page, // What page to get, starting from 1.
			'order'       => 'ASC',
		);

		$GET_search_term = '';
		$GET_filter      = '';

		if ( ! empty( $raw_search ) ) {
			$GET_search_term = $filters['s'] = $raw_search;
		}
		if ( ! empty( $raw_filter ) && 'all' !== $raw_filter ) {
			$GET_filter = $filters['settlement_status'] = $raw_filter;
		}
		/**
		 * Filters vendor
		 * 
		 * @since 1.0.0
		 * @param $filters
		 */
		$filters = apply_filters( 'elex_mv_vendors', $filters );

		$adminpayment  = new AdminPayment();
		$vendors       = $adminpayment->vendor_payments( $filters );
		$total_vendors = $adminpayment->payment_total_count( $filters ); // How many users we have in total (beyond the current page)
		$num_pages     = ceil( $total_vendors / $vendor_per_page ); // How many pages of users we will need
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/admin-payments/admin-payment-table.php';
	}

	public static function elex_mv_payment_settlement() {
		global $wpdb;
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'Forbidden', 403 );
		}
		if ( ! isset( $_POST['elex_mv_payment_settlement_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['elex_mv_payment_settlement_nonce'] ) ), 'elex_mv_payment_settlement' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
		$settlement_data = array(
			'vendor_id'         => isset( $_POST['vendor_id'] ) ? sanitize_text_field( wp_unslash( $_POST['vendor_id'] ) ) : '',
			'vendor_name'       => isset( $_POST['vendor_name'] ) ? sanitize_text_field( wp_unslash( $_POST['vendor_name'] ) ) : '',
			'settlement_amount' => isset( $_POST['settlement_amount'] ) ? sanitize_text_field( wp_unslash( $_POST['settlement_amount'] ) ) : '',
			'commission_amount' => isset( $_POST['commission_amount'] ) ? sanitize_text_field( wp_unslash( $_POST['commission_amount'] ) ) : '',
			'settlement_date'   => isset( $_POST['settlement_date'] ) ? sanitize_text_field( wp_unslash( $_POST['settlement_date'] ) ) : '',
			'settlement_mode'   => isset( $_POST['settlement_mode'] ) ? sanitize_text_field( wp_unslash( $_POST['settlement_mode'] ) ) : '',
			'transaction_id'    => isset( $_POST['transaction_id'] ) ? sanitize_text_field( wp_unslash( $_POST['transaction_id'] ) ) : '-',
			'note'              => isset( $_POST['note'] ) ? sanitize_text_field( wp_unslash( $_POST['note'] ) ) : '-',

		);

		$validation_errors = self::elex_mv_form_settlement_validation( $settlement_data );
		if ( isset( $validation_errors['errors'] ) && count( $validation_errors['errors'] ) ) {
			wp_send_json_error( $validation_errors['errors'] );
		}

		$adminpayment = new AdminPayment();
		$table_name   = $wpdb->base_prefix . 'elex_mv_payment_settlement_history';
		$adminpayment->insert_settlement_history_data( $settlement_data, $table_name );
		$adminpayment->update_vendor_amount_after_settlement( $settlement_data );
		$adminpayment->update_last_settlement_date( $settlement_data );

		
				$user_id = get_post_meta( $settlement_data['vendor_id'], 'elex_mv_user_id', true );
				$email   = get_post_meta( $settlement_data['vendor_id'], 'elex_mv_email', true );

				$user = get_user_by( 'ID', $user_id );

				$date_fomat   = get_option( 'date_format' );
				$display_name = $user ? $user->display_name : 'Unknown Vendor';

				$subject = '  Successful Receipt of Your Vendor Payment for ' . gmdate( 'M Y', strtotime( $settlement_data['settlement_date'] ) );
				$body    = 'Dear ' . $display_name . ',<br>
	
				We hope this message finds you well.<br>

				We are delighted to inform you that the payment settlement for the month of ' . gmdate( 'M', strtotime( $settlement_data['settlement_date'] ) ) . ' has been successfully processed, and your earnings are now available in your account. Your dedication and hard work as a vendor on [Your Multi-Vendor Site] have been duly rewarded.<br><br>
				
				Payment Settlement Date:' . gmdate( $date_fomat, strtotime( $settlement_data['settlement_date'] ) ) . '<br>
				Payment Amount: ' . $settlement_data['settlement_amount'] . '<br>
				Payment Method: ' . $settlement_data['settlement_mode'] . '<br>
				
				To know more about your earnings, please log in to your vendor dashboard on ' . $settlement_data['vendor_name'] . ' and navigate to the "Payments" > "Settlements" section. There, you will find a detailed breakdown of your payment, including the transaction history.<br>
				
				We sincerely appreciate your contributions to our platform and the exceptional products and services you provide to our customers. Your commitment to excellence is invaluable to us, and we are committed to ensuring a seamless and efficient payment process.<br>
				
				
				Once again, thank you for being a part of our thriving vendor community. We look forward to another successful month of collaboration and growth on  ' . get_bloginfo( 'name' ) . '<br>
				
				Best Regards<br>';
	
					
			  
	
				$headers   = array();
				$headers[] = 'Content-type: text/html; charset=utf-8';
				$headers[] = 'From:' . get_bloginfo( 'admin_email' );
				wp_mail( $email, $subject, $body, $headers );


				$user_id = get_post_meta( $settlement_data['vendor_id'], 'elex_mv_user_id', true );

				$user = get_user_by( 'ID', $user_id );

		if ( $user instanceof \WP_User ) {
				$date_fomat = get_option( 'date_format' );

				$subject = '  Successful Vendor Payment Settlement for ' . gmdate( 'M Y', strtotime( $settlement_data['settlement_date'] ) );
				$body    = 'Dear ' . get_bloginfo( 'name' ) . ',<br>

				We hope this message finds you well.<br>

				We are pleased to inform you that the vendor payment settlement for the month of ' . gmdate( 'M', strtotime( $settlement_data['settlement_date'] ) ) . ' has been completed. The vendor earnings have been disbursed successfully, and our financial records are up to date.<br>

				Vendor: ' . $user->display_name . '<br>
				Payment Settlement Amount (Currency):  ' . $settlement_data['settlement_amount'] . '<br>
				Payment Settlement Date: ' . gmdate( $date_fomat, strtotime( $settlement_data['settlement_date'] ) ) . '<br>

				This timely settlement ensures that our valued vendors receive their earnings promptly, contributing to their satisfaction and continued commitment to our multi-vendor platform.<br>

				If you need to review any settlement details or access payment records, please log in to your administrator dashboard on [Your Multi-Vendor Site] and navigate to the "Payments" section.<br>

				We appreciate your diligence in managing the payment settlement process, which is crucial to maintaining strong vendor relationships and the overall success of our platform.<br>


				Best regards<br>
				';

				$headers   = array();
				$headers[] = 'Content-type: text/html; charset=utf-8';
				$headers[] = 'From:' . get_bloginfo( 'admin_email' );
				wp_mail( get_bloginfo( 'admin_email' ), $subject, $body, $headers );
		}
				
				wp_send_json_success();
	}

	public static function elex_mv_form_settlement_validation( $settlement_data ) {
		$data = array(
			'message' => __( 'Empty Fields' , 'elex-multi-vendor-for-woocommerce' ),
			'errors'  => array(),
		);
		if ( ! isset( $settlement_data['settlement_amount'] ) || empty( $settlement_data['settlement_amount'] ) || 1 > $settlement_data['settlement_amount'] ) {
			$data['errors']['settlement_amount'][] = __( 'Please enter settlement amount.', 'elex-multi-vendor-for-woocommerce' );
		}
		
	
		/**
		 * Fires for validation of settlement form
		 * 
		 * @since 1.0.0
		 * @param $data
		 */
		$data = apply_filters( 'elex_mv_form_settlement_validation', $data );
		return $data;
	}

	public static function elex_mv_settlement_history_data() {

		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'mv_nonce' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
	
		$settlement_history_data = array(
			'vendor_id' => isset( $_POST['id'] ) ? sanitize_text_field( wp_unslash( $_POST['id'] ) ) : '',
			'start'     => isset( $_POST['start'] ) ? sanitize_text_field( wp_unslash( $_POST['start'] ) ) : 0,
			'length'    => isset( $_POST['length'] ) ? sanitize_text_field( wp_unslash( $_POST['length'] ) ) : 0,
		);
	  
		$adminpayment = new AdminPayment();
		/**
		 * Function to filter the settlement history
		 * 
		 * @since 1.0.0
		 * @param $filters
		 */
		$total_records                           = $adminpayment->apply_filters( $settlement_history_data )->count();
		$settlement_history_data['search_value'] = isset( $_POST['search']['value'] ) ? sanitize_text_field( wp_unslash( $_POST['search']['value'] ) ) : '';
		/**
		 * Function to filter the settlement history
		 * 
		 * @since 1.0.0
		 * @param $filters
		 */
		$records_filtered = $adminpayment->apply_filters( $settlement_history_data )->count();
		$data             = $adminpayment->vendor_settlement_history( $settlement_history_data );
	

		$date_fomat = get_option( 'date_format' ); 

		foreach ( $data as $key => &$value ) {
			$value['settlement_date'] = esc_html( gmdate( $date_fomat , strtotime( $value['settlement_date'] ) ) );
		}
		$response = array(
			'data'            => $data,
			'recordsFiltered' => $records_filtered,
			'recordsTotal'    => $total_records,
		);
		wp_send_json( $response );
	}
   
	public static function elex_mv_export_settlement_vendor() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'Forbidden', 403 );
		}

		if ( ! isset( $_POST['elex_mv_export_settlement_vendor_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['elex_mv_export_settlement_vendor_nonce'] ) ), 'elex_mv_export_settlement_vendor' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}

		$export_data = array(
			'vendor_id'        => isset( $_POST['vendors_settlement_csv'] ) ? map_deep( wp_unslash( $_POST['vendors_settlement_csv'] ), 'sanitize_text_field' ) : array( 'all' ),
			'file_format'      => isset( $_POST['elex-multi-vendor-for-woocommerce-vendor_file_format_csv'] ) ? sanitize_text_field( wp_unslash( $_POST['elex-multi-vendor-for-woocommerce-vendor_file_format_csv'] ) ) : '',
			'export_from_date' => isset( $_POST['export_from_date'] ) ? sanitize_text_field( wp_unslash( $_POST['export_from_date'] ) ) : '',
			'export_to_date'   => isset( $_POST['export_to_date'] ) ? sanitize_text_field( wp_unslash( $_POST['export_to_date'] ) ) : '',
			'length'           => 10,
		);

	
		$adminpayment = new AdminPayment();
		header( 'Content-Type: text/csv; charset=utf-8' ); //For .csv
		header( 'Content-Disposition: attachment; filename=Settlement_History( ' . implode( '', $export_data['vendor_id'] ) . ')-[' . $export_data['export_from_date'] . ']-[' . $export_data['export_to_date'] . '].csv' );
		$output            = fopen( 'php://output', 'w' );
		$array_for_headers = array( 'Vendor Name', 'Settlement Date', 'Settlement Mode', 'Transaction ID', 'Vendor Earning', 'Commission Amount' );
		/**
		 * Fires filyter hook for export csv headers
		 * 
		 * @since 1.0.0
		 * @param $array_for_headers
		 */
		$array_for_headers = apply_filters( 'elex_mv_csv_header_settlement_history_for_export', $array_for_headers );
		fputcsv( $output, $array_for_headers );
		$page_no = 1;
		
		$vendor_settlement_data = $adminpayment->vendor_settlement_history( $export_data );

		while ( count( $vendor_settlement_data ) > 0 ) {


			foreach ( $vendor_settlement_data as $history_data ) {
				$display_name = get_post_meta( $history_data['vendor_id'], 'elex_mv_user_name' , true );
				$csv          = array( 
					
					$display_name,
					$history_data['settlement_date'],
					$history_data['settlement_mode'],
					$history_data['transaction_id'],
					$history_data['vendor_amount'], 
					$history_data['commission_amount'], 
					
				);

			

			/**
			 * 
			 * Fires hook for csv data of settlement history
			 * 
			 * @since 1.0.0
			 * @param $csv
			 */
				$csv = apply_filters( 'elex_mv_csv_settlement_history_for_export', $csv );
				fputcsv( $output, $csv );
			}

			++$page_no;
			$export_data['start']   = ( $page_no - 1 ) * $export_data['length'];
			$vendor_settlement_data = $adminpayment->vendor_settlement_history( $export_data );
		}

		// Since we are streaming data directly to the browser for file download, we used core PHP functions.
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
		fclose( $output );
		die;
	}   
}
