<?php
/**
 * Class Noesia Cs Impact Map Module.
 *
 * @package Noesia_Commerce_Suite
 */

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

/**
 * Class implementation.
 */
class Noesia_CS_Impact_Map_Module extends Noesia_CS_Admin_Module {
	/**
	 * Handles the related plugin operation.
	 */
	public function __construct() {
		$this->key         = 'impact-map';
		$this->label       = __( 'Impact Map', 'noesia-commerce-suite' );
		$this->icon        = '◎';
		$this->description = __( 'Cached aggregated public proof of business reach.', 'noesia-commerce-suite' );
		$this->view        = 'modules/impact-map/views/admin.php';
		$this->primary     = false;
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $context Context.
	 */
	public function prepare_data( $context = array() ) {
		$impact_map_service  = $this->service( 'impact_map_service' );
		$snapshot            = $impact_map_service && method_exists( $impact_map_service, 'get_snapshot' ) ? $impact_map_service->get_snapshot() : array();
		$admin               = isset( $context['admin'] ) ? $context['admin'] : null;
		$group_by            = isset( $snapshot['group_by'] ) ? sanitize_key( $snapshot['group_by'] ) : sanitize_key( $this->setting( 'impact_map_group_by', 'country' ) );
		if ( ! in_array( $group_by, array( 'city', 'region', 'country' ), true ) ) {
			$group_by = 'country';
		}
		$map_asset = $this->detect_dark_map_asset();

		return array(
			'snapshot'     => $snapshot,
			'group_by'     => $group_by,
			'group_label'  => $admin && method_exists( $admin, 'impact_group_label' ) ? $admin->impact_group_label( $group_by ) : ucfirst( $group_by ),
			'areas'        => $admin && method_exists( $admin, 'prepare_impact_areas_for_display' ) ? $admin->prepare_impact_areas_for_display( $snapshot, $group_by, 10 ) : array(),
			'map_asset'    => $map_asset,
		);
	}

	/**
	 * Handles the related plugin operation.
	 */
	private function detect_dark_map_asset() {
		$asset = array(
			'found'  => false,
			'path'   => 'assets/images/impact-map/world-map-dark.jpg',
			'file'   => '',
		);

		if ( ! defined( 'NOESIA_CS_PATH' ) ) {
			return $asset;
		}

		foreach ( array( 'webp', 'jpg', 'jpeg', 'png' ) as $extension ) {
			$relative = 'assets/images/impact-map/world-map-dark.' . $extension;
			if ( file_exists( NOESIA_CS_PATH . $relative ) ) {
				$asset['found']  = true;
				$asset['path']   = $relative;
				$asset['file']   = basename( $relative );
				break;
			}
		}

		return $asset;
	}

}
