<?php


namespace Elex\MultiVendor\Controller;

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

use Elex\MultiVendor\Model\Payment;
use Elex\MultiVendor\Model\AdminPayment;
use Elex\MultiVendor\Model\Vendor;

class PaymentController {
	public static function init() {
		$self = new self();
		add_action( 'elex_mv_account_data_page', array( $self, 'mv_payment_tab_content' ) );
		add_action( 'elex_mv_settlement_history_page', array( $self, 'mv_settlement_tab_content' ) );
		add_action( 'wp_ajax_elex_mv_vendor_payment_mail', array( self::class, 'elex_mv_vendor_payment_mail' ) );
		add_action( 'wp_ajax_elex_mv_vendor_settlement_history_data', array( self::class, 'elex_mv_vendor_settlement_history_data' ) );
		add_action( 'wp_ajax_elex_mv_vendor_payment_export', array( self::class, 'elex_mv_vendor_payment_export' ) );
	}
	public static function get_store_id() {
		$vendor   = Vendor::load( wp_get_current_user() );
		$store    = $vendor->get_store();
		$store_id = $store->get_id();
		return $store_id;
	}
	public static function mv_payment_tab_content() {
		$store_id = self::get_store_id(); 
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/payments/account-data.php';
	}
	public static function mv_settlement_tab_content() {
		$store_id = self::get_store_id(); 
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/payments/settlement-history.php';
	}
	public static function elex_mv_vendor_payment_mail() {
	
		check_ajax_referer( 'elex_mv_payment_nonce', 'vendor_payment_nonce' );
		
		$paypal_email = isset( $_POST['elex_vendor_paypal_mail'] ) ? sanitize_text_field( wp_unslash( $_POST['elex_vendor_paypal_mail'] ) ) : '';
		$store_id     = isset( $_POST['store_id'] ) ? sanitize_text_field( wp_unslash( $_POST['store_id'] ) ) : '';
		update_post_meta( $store_id, 'elex_mv_paypal_email', $paypal_email );

		wp_send_json_success();
	}
	public static function elex_mv_vendor_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 );
		}
		$vendor_id               = get_current_user_id();
		$settlement_history_data = array(
			'vendor_id' => isset( $vendor_id ) ? sanitize_text_field( $vendor_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 call to filter data
		 * 
		 * @since 1.0.0
		 * @param $settlement_history_data
		 */
		$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 call to filter data
		 * 
		 * @since 1.0.0
		 * @param $settlement_history_data
		 */
		$records_filtered = $adminpayment->apply_filters( $settlement_history_data )->count();
		$data             = $adminpayment->vendor_settlement_history( $settlement_history_data );
		$response         = array(
			'data'            => $data,
			'recordsFiltered' => $records_filtered,
			'recordsTotal'    => $total_records,
		);
		wp_send_json( $response );
	}
	public static function elex_mv_vendor_payment_export() {
		if ( ! current_user_can( 'elex_mv_vendor' ) && ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'Forbidden', 403 );
		}
		if ( ! isset( $_POST['elex_mv_vendor_payment_export_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['elex_mv_vendor_payment_export_nonce'] ) ), 'elex_mv_vendor_payment_export' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
		$export_data  = array(
			'vendor_id'        => isset( $_POST['vendor_id'] ) ? sanitize_text_field( wp_unslash( $_POST['vendor_id'] ) ) : '',
			'file_format'      => isset( $_POST['file_format'] ) ? sanitize_text_field( wp_unslash( $_POST['file_format'] ) ) : '',
			'export_from_date' => isset( $_POST['from_date'] ) ? sanitize_text_field( wp_unslash( $_POST['from_date'] ) ) : '',
			'export_to_date'   => isset( $_POST['to_date'] ) ? sanitize_text_field( wp_unslash( $_POST['to_date'] ) ) : '',
			'settlement_mode'  => isset( $_POST['settlement_mode'] ) ? sanitize_text_field( wp_unslash( $_POST['settlement_mode'] ) ) : '',
			'length'           => 100,
		);
		$adminpayment = new AdminPayment();
		header( 'Content-Type: text/csv; charset=utf-8' ); //For .csv
		header( 'Content-Disposition: attachment; filename=settlement_history.csv' );
		$output            = fopen( 'php://output', 'w' );
		$array_for_headers = array( 'settlement_date', 'settlement_mode', 'transaction_id', 'vendor_amount' );
		/**
		 * Function call to filter data
		 * 
		 * @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 ) {
				$csv = array( 

					$history_data['settlement_date'],
					$history_data['settlement_mode'],
					$history_data['transaction_id'],
					$history_data['vendor_amount'], 
					
				);
				/**
				 * Function call to filter data for csv
				 * 
				 * @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;
	}
}
