<?php
namespace AcademyProGroupPlus\Dashboard\Ajax\Frontend;

use Academy\Classes\AbstractAjaxHandler;
use Academy\Classes\Sanitizer;
use AcademyProGroupPlus\Db\Models\{
	Group,
	Team
};
use AcademyProGroupPlus\Roles\{
	GroupOrganizer,
	TeamOrganizer
};
use WP_User;
use AcademyProGroupPlus\Interfaces\Ajax\Frontend\TeamHandlerInterface;

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


class EcommerceInegration extends AbstractAjaxHandler {


	protected $namespace = 'academy_pro_group_plus/frontend/ecommerce';
	public function __construct() {
		$this->actions = array(
			'get_groups' => [
				'callback'             => [ $this, 'get_groups' ],
				'allow_visitor_action' => true,
			],
			'add_to_cart' => [
				'callback'             => [ $this, 'add_to_cart' ],
				'allow_visitor_action' => true,
			],
		);
	}

	public function get_groups( $payload_data ) : void {
		$payload = Sanitizer::sanitize_payload([

			'group_id'        => 'integer',

			'per_page'        => 'integer',
			'current_page'    => 'integer',
			'order_by'        => 'string',
			'search'          => 'string',
			'order_direction' => 'string',
		], $payload_data);
		$join = '';
		$conditions = [];
		$args = [];

		if ( ! current_user_can( 'manage_options' ) ) {
			// current user is group organizer
			// show  own groups
			$join = 'INNER JOIN ' . Group::add_prefix( 'group_organizers' ) . ' ugr
                    ON g.id = ugr.group_id';
			$conditions[] = 'ugr.organizer_id = %d';
			$args[]       = get_current_user_id();
		}

		if ( ! empty( $search = $payload['search'] ?? '' ) ) {
			$conditions[] = 'g.name LIKE %s';
			$args[]       = "%{$search}%";
		}

		wp_send_json_success(
			$data = Group::ins()->get_advance(
				'g.*', // select rows
				'g.id', // select count for pagination
				'g', // main table alias
				$join,  // join clause
				$conditions, // where condition
				$args,   // where condition args
				'',   // after where, before order & limit query
				$payload['per_page'] ?? 20,
				$payload['current_page'] ?? 1,
				$payload['order_by'] ?? null,
				$payload['order_direction'] ?? 'DESC'
			),
			empty( $data ) && ( $payload['per_page'] ?? 20 ) == 1 ? 404 : 200
		);
	}

	public function add_to_cart( $payload ) : void {
		$engine = $GLOBALS['academy_settings']->monetization_engine;
		if ( empty( $engine ) ) {
			wp_send_json_error( __( 'No payment system found.', 'academy-pro' ) );
		}

		$action = "academy_pro/group_plus/{$engine}/add_to_cart";
		if ( ! has_action( $action ) ) {
			wp_send_json_error( __( 'Something went wrong.', 'academy-pro' ) );
		}
		do_action( $action, $payload );
	}
}
