<?php

namespace BWFAN\Exporter;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

/***
 * Class Automation_Exporter
 *
 * @package Autonami
 */
class Cart extends Base {

	private $db_export_row = [];
	private $export_id = 0;
	private $export_meta = [];
	private $user_id = 0;
	private $current_pos = 0;
	private $carts = [];
	private $count = 0;
	private $halt = 0;

	/**
	 * Class constructor
	 */
	public function __construct() {
		$this->type = 'cart';
	}

	/**
	 * Handle cart export
	 *
	 * @param $user_id
	 *
	 * @return void
	 */
	public function handle_export( $user_id, $export_id = 0 ) {
		$this->export_id = $export_id;
		$this->user_id   = $user_id;
		$this->maybe_get_export( $this->export_id );

		//$filename = 'cart-export-' . time() . '.csv';

		$this->current_pos = absint( $this->db_export_row['offset'] );

		$this->populate_carts();
		$this->start_time = time();

		while ( ( ( time() - $this->start_time ) < 30 ) && ! BWFCRM_Common::memory_exceeded() && ( 0 === $this->halt ) ) {
			/** Populate contacts when previous contacts are done exporting */
			if ( $this->count >= count( $this->carts ) ) {
				/**
				 * Fetch next set of contacts to export
				 */
				$this->populate_carts();
			}
			$this->export_cart();
			$this->update_offset();
		}

		if ( $this->get_percent_completed() >= 100 ) {
			$this->end_export( 3, '' );
		}
	}


	public function maybe_get_export( $export_id ) {
		if ( is_array( $this->db_export_row ) && ! empty( $this->db_export_row ) && absint( $this->db_export_row['id'] ) === absint( $export_id ) ) {
			return;
		}

		$this->export_id     = absint( $export_id );
		$this->db_export_row = BWFAN_Model_Import_Export::get( $this->export_id );
		$this->export_meta   = ! empty( $this->db_export_row['meta'] ) ? json_decode( $this->db_export_row['meta'], true ) : array();
	}


	public function maybe_insert_data_in_table() {
		if ( ! file_exists( BWFCRM_EXPORT_DIR . '/' ) ) {
			wp_mkdir_p( BWFCRM_EXPORT_DIR );
		}
		$file_name = 'cart-export-' . time() . '.csv';
		$file      = fopen( BWFCRM_EXPORT_DIR . '/' . $file_name, "wb" );
		if ( empty( $file ) ) {
			/** Unable to open file, should return and show a message */
			return 0;
		}
		$labels = [ 'email', 'user_id', 'created_time', 'items', 'total', 'currency', 'checkout_data', 'checkout_page_id' ];

		$count = \BWFAN_Recoverable_Carts::get_abandoned_carts( '', '', '', '', '', true );

		fputcsv( $file, $labels );
		fclose( $file );

		BWFAN_Model_Import_Export::insert( array(
			'offset'        => 0,
			'type'          => 2,
			'status'        => 1,
			'count'         => $count['total_count'],
			'meta'          => wp_json_encode( array(
				'title' => 'cart',
				'file'  => $file_name
			) ),
			'created_date'  => current_time( 'mysql', 1 ),
			'last_modified' => current_time( 'mysql', 1 )
		) );

		$export_id = BWFAN_Model_Import_Export::insert_id();

		if ( empty( $export_id ) ) {
			/** Unable to insert row in DB */
			wp_delete_file( BWFCRM_EXPORT_DIR . '/' . $file_name );

			return 0;
		}

		return $export_id;
	}

	public function populate_carts() {
		$this->carts = \BWFAN_Recoverable_Carts::get_abandoned_carts( '', '', $this->current_pos, 100 );
	}

	public function export_cart() {
		$this->count = 0;

		/** Check if contacts are empty */
		if ( empty( $this->carts ) ) {
			$this->end_export( 2, 'Carts not found' );

			$this->halt = 1;

			return;
		}

		$file = fopen( BWFCRM_EXPORT_DIR . '/' . $this->export_meta['file'], "a" );
		foreach ( $this->carts as $cart ) {
			$csvData = [
				$cart['email'],
				$cart['user_id'],
				$cart['created_time'],
				$cart['items'],
				$cart['total'],
				$cart['currency'],
				$cart['checkout_data'],
				$cart['checkout_page_id']
			];

			if ( ! empty( $file ) ) {
				fputcsv( $file, $csvData );
			}
			$this->count ++;
		}
		if ( ! empty( $file ) ) {
			fclose( $file );
		}
		$this->current_pos = $this->current_pos + $this->count;
	}

	/**
	 * Finish exporting to file
	 *
	 * @param int $status
	 * @param string $status_message
	 */
	public function end_export( $status = 3, $status_message = '' ) {
		if ( empty( $this->export_id ) ) {
			return;
		}

		BWFAN_Core()->exporter->unschedule_export_action( [
			'type'      => $this->type,
			'user_id'   => $this->user_id,
			'export_id' => $this->export_id
		] );

		if ( ! empty( $status_message ) ) {
			BWFAN_Core()->logger->log( $status_message, 'export_contacts_crm' );
		} else if ( 3 === $status ) {
			$status_message = 'cart exported. Export ID: ' . $this->export_id;
		}

		$this->db_export_row['status']   = $status;
		$this->export_meta['status_msg'] = $status_message;
		BWFAN_Model_Import_Export::update( array(
			"status" => $status,
			"meta"   => wp_json_encode( $this->export_meta )
		), array(
			'id' => absint( $this->export_id )
		) );
	}

	/**
	 * Update DB offset
	 */
	public function update_offset() {
		$this->db_export_row['offset'] = $this->current_pos;
		BWFAN_Model_Import_Export::update( array( "offset" => $this->current_pos ), array( 'id' => absint( $this->export_id ) ) );
		if ( $this->get_percent_completed() >= 100 ) {
			$this->end_export();
		}
	}

	/**
	 * Return percent completed
	 *
	 * @return int
	 */
	public function get_percent_completed() {
		$start_pos = isset( $this->db_export_row['offset'] ) && ! empty( absint( $this->db_export_row['offset'] ) ) ? absint( $this->db_export_row['offset'] ) : 1;

		return absint( min( round( ( ( $start_pos / $this->db_export_row['count'] ) * 100 ) ), 100 ) );
	}
}

/**
 * Register exporter
 */
BWFAN_Core()->exporter->register_exporter( 'automation', 'BWFAN\Exporter\Automation' );