<?php
/**
 * Ayyash Social Share.
 *
 * @package Ayyash
 * @author ThemeRox
 * @since 2.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	die();
}

if ( ! class_exists( 'Ayyash_Social_Share' ) ) {
	class Ayyash_Social_Share {

		/**
		 * Ayyash_Social_Share constructor.
		 *
		 * @return void
		 */
		public function __construct() {
			add_action('ayyash_content_single_before_entry_footer_content', [ $this, 'social_share_content' ]);
			add_action('wp_ajax_ayyash_social_share_count', [ $this, 'ayyash_social_share_count' ]);
		}

		/**
		 * Social Share Platforms
		 *
		 * @return string[][]
		 */

		public function social_share_platforms() {
			//social share url
			$facebook_url  = 'https://facebook.com/sharer.php/?u=' . esc_url( get_permalink() );
			$twitter_url   = 'https://twitter.com/intent/tweet/?url=' . esc_url( get_permalink() );
			$pinterest_url = 'https://pinterest.com/pin/create/button/?url=' . esc_url( get_permalink() );

			return array(
				array(
					'name' => 'facebook',
					'link' => $facebook_url,
					'icon' => 'ai ai-facebook',
				),
				array(
					'name' => 'twitter',
					'link' => $twitter_url,
					'icon' => 'ai ai-twitter',
				),
				array(
					'name' => 'pinterest',
					'link' => $pinterest_url,
					'icon' => 'ai ai-pinterest',
				),
			);
		}

		/**
		 * Social Share Content
		 *
		 * @return void
		 */
		public function social_share_content() {
			global $post;
			?>
			<div class="ayyash-post-social-share d-flex align-items-center">
				<div class="social-count">
					<i class="ai ai-heart"  aria-hidden="true"></i>
					<span>
						<?php
						$post_count = get_post_meta( $post->ID, 'ayyash_post_share_count', true );
						echo esc_html( 0 === strlen( $post_count ) ? 0 : $post_count );
						?>
					</span>
				</div><!--count number -->

				<div class="social-share-media d-flex">
					<?php
					foreach ( $this->social_share_platforms() as $social ) :
						printf(
							'<a data-bs-toggle="tooltip" data-bs-placement="bottom" title="%1$s" data-original-title="%1$s" class="social-icon" href="%2$s" target="_blank">
					<i class="%3$s" aria-hidden="false"></i><span class="sr-only">%1$s</span>
				</a>',
							esc_attr( $social['name'] ),
							esc_url( $social['link'] ),
							esc_attr( $social['icon'] )
						);
					endforeach;
					?>
				</div><!-- social share media -->
			</div>
			<?php
		}

		/**
		 * Total Share Count
		 */
		public function ayyash_social_share_count() {
			if ( ! isset($_POST['nonce']) || wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), basename(__FILE__)) ) {
				return;
			}

			$post_id           = intval( isset( $_POST['post_id'] ) ? sanitize_text_field( wp_unslash( $_POST['post_id'] ) ) : '' );
			$count_meta_key    = 'ayyash_post_share_count';
			$total_share_count = self::social_share_facebook_count() + self::social_share_twitter_count() + self::social_share_pinterest_count();

			if ( metadata_exists('post', $post_id, $count_meta_key ) ) {
				if ( (int) $count_meta_key !== $total_share_count ) {
					update_post_meta($post_id, $count_meta_key, $total_share_count);
				}
			} else {
				add_post_meta($post_id, $count_meta_key, $total_share_count);
			}
		}

		/**
		 * Facebook Social Count
		 *
		 * @return int
		 */
		private function social_share_facebook_count() {
			$access_token = '758149252144880|17676432be538f924eecb6cf703ce184'; //@TODO needs to add customizer settings
			$url          = 'https://graph.facebook.com/v12.0/?id=' . esc_url ( get_permalink() ) . '&fields=engagement&access_token=' . $access_token;
			$response = wp_remote_get( $url ); // phpcs:ignore

			if ( is_array( $response ) && ! is_wp_error( $response ) ) {
				$body = $response['body']; // use the content
				$json = json_decode( $body );
				$data = isset( $json->engagement ) ? $json->engagement->share_count : 0;
			} else {
				$data = 0;
			}
			return $data;
		}

		/**
		 * Facebook Social Count
		 *
		 * @return int
		 */
		private function social_share_twitter_count() {
			//@TODO temporary handled with opensharecount.com
			$url      = 'https://opensharecount.com/count.json?url=' . esc_url ( get_permalink() );
			$response = wp_remote_get( $url ); // phpcs:ignore

			if ( is_array( $response ) && ! is_wp_error( $response ) ) {
				$body = $response['body']; // use the content
				$json = json_decode( $body );
				$data = isset( $json->count ) ? $json->count : 0;
			} else {
				$data = 0;
			}
			return $data;
		}

		/**
		 * Pinterest Social Count
		 *
		 * @return int
		 */
		private function social_share_pinterest_count() {
			$url      = 'https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=' . esc_url( get_permalink() );
			$response = wp_remote_get( $url ); // phpcs:ignore

			if ( is_array( $response ) && ! is_wp_error( $response ) ) {
				$body = $response['body']; // use the content
				preg_match( '/\((.*?)\)/', $body, $match );
				$json = json_decode( $match[1] );
				$data = isset( $json->count ) ? $json->count : 0;
			} else {
				$data = 0;
			}
			return $data;
		}
	}
	new Ayyash_Social_Share();
}


