<?php
/**
 * Created by PhpStorm.
 * File: hooks.php
 * Project: grilabs-woocommerce-parasut
 * Year: 2018
 */

function cancelOrderParasut( $order_id, $old_status, $new_status ) {

	$oto_aktarim_statuses     = get_option( 'grilabsparasut_oto_aktar_statuses' );
	$oto_resmilestir_statuses = get_option( 'grilabsparasut_oto_resmilestir_statuses' );

	if ( is_array($oto_aktarim_statuses) && in_array( $new_status, $oto_aktarim_statuses ) ) {
		try {
			order_id_ile_parasute_siparis_gonder( $order_id );
		} catch ( Exception $e ) {
			ParasutLog::log( sprintf( "Fatura aktarımında bir sorun oluştu. Detaylar: %s", $e->getMessage() ) );
		}
	}

	if ( is_array( $oto_resmilestir_statuses ) && ! empty( $new_status ) && in_array( $new_status, $oto_resmilestir_statuses ) ) {
		try {
			grilabsparasut_create_earchive( $order_id );
		} catch ( Exception $e ) {
			ParasutLog::log( sprintf( "Fatura resmileştirilirken bir sorun oluştu. Detaylar: %s", $e->getMessage() ) );
		}
	}

}

add_action( 'woocommerce_order_status_changed', 'cancelOrderParasut', 10, 3 );

function new_order_created_hook( $order_id ) {

	$auto_order_transfer = get_option( 'grilabsparasut_oto_aktar' );
	$auto_formal_invoice = get_option( 'grilabsparasut_oto_resmilestir' );
	$has_parasut_id      = get_parasut_invoice_id( $order_id );

	if ( ( $auto_order_transfer == 'no' and $auto_formal_invoice == 'no' ) OR $has_parasut_id ) {
		return;
	}

	// $order = wc_get_order( $order_id );
	// $items = $order->get_items();

	if ( $auto_formal_invoice == 'yes' ) {
		// formal
	}
	if ( $auto_order_transfer == 'yes' ) {
		try {
			order_id_ile_parasute_siparis_gonder( $order_id );
		} catch ( Exception $e ) {
			ParasutLog::log( sprintf( "Sipariş esnasında fatura aktarımında bir sorun oluştu. Detaylar: %s", $e->getMessage() ) );
		}

	}
}

if ( ! function_exists( 'gl_parasut_woocommerce_order_status_completed' ) ) {
	function gl_parasut_woocommerce_order_status_completed( $order_id, $old_status, $new_status ) {
		if($new_status == 'completed')
			send_formal_invoice_email( $order_id );
	}
}

add_action( 'woocommerce_order_status_changed', 'gl_parasut_woocommerce_order_status_completed', 10, 3 );

add_filter( 'woocommerce_email_attachments', function ( $attachments, $id, $order, $_this ) {
	if ( $id == 'gl_invoice_share' ) {
		$pdf_url = $order->get_meta( '_parasut_earchive_pdf', true );
		if ( $pdf_url ) {
			$upload_dir   = wp_upload_dir();
			$pdf_base_dir = $upload_dir['basedir'];

			$pdf_file = $pdf_base_dir . DIRECTORY_SEPARATOR . 'invoices' . DIRECTORY_SEPARATOR . $pdf_url;
			if(isset($pdf_file) && file_exists($pdf_file))
				$attachments[] = $pdf_file;
		}
	}
	return $attachments;
}, 10, 4 );