<?php

namespace AcademyProCalendar\Events\Mettings;

use AcademyProCalendar\Events\QueryAbstract;

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

class MeetingData extends QueryAbstract {

	public string $select    = 'pm.meta_value, pm.post_id';
	public string $count_col = 'p.ID';

	public int $per_page       = 0;
	public string $order_direction = 'DESC';
	public ?string $order_by     = 'p.ID';

	public function __construct() {
		global $wpdb;

		$this->table  = $wpdb->postmeta . ' pm';
		$this->join   = "
            INNER JOIN {$wpdb->posts} p
    	        ON p.ID = pm.post_id
            INNER JOIN {$wpdb->posts} pe
                ON p.ID = pe.post_parent AND 
                   pe.post_type = %s AND 
                   pe.post_author = '%d'
            WHERE 
                pm.meta_key = %s AND 
                pm.meta_value LIKE %s
        ";

		$this->args[]   = 'academy_enrolled';
		$this->args[]   = get_current_user_id();
		$this->args[]   = 'academy_course_curriculum';
		$this->args[]   = '%\"type\";s:7:\"meeting\"%';
	}
	public static function get( int $year, int $month ) : array {
		$ins = new self();
		$data = $ins->get_events_data();
		$ids = [];
		$post_ids = [];

		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value 
		foreach ( $data['data'] ?? [] as ['meta_value' => $item,'post_id' => $post_id] ) {
			foreach ( maybe_unserialize( $item ) ?? [] as $curriculum ) {
				foreach ( $curriculum['topics'] ?? [] as $c ) {
					if ( ( 'meeting' === $c['type'] ?? '' ) &&
						! empty( $c['id'] ?? '' )
					) {
						$ids[] = $c['id'];
						$post_ids[ $c['id'] ] = $post_id;
					}
				}
			}
		}
		$output = [];
		if ( ! empty( $ids ) ) {

			$output['meet'] = ( new Meet( $year, $month, $ids ) )
				->get_events_data();

			$output['zoom'] = ( new Zoom( $year, $month, $ids ) )
				->get_events_data();

			foreach ( [ 'meet', 'zoom' ] as $item ) {
				foreach ( $output[ $item ]['data'] as $key => $m ) {
					$output[ $item ]['data'][ $key ]['link'] = isset( $post_ids[ $m['ID'] ] ) ? get_permalink( $post_ids[ $m['ID'] ] ) : '';

					$start_dt = new \DateTime( $m['start_date'], new \DateTimeZone( $m['timezone'] ) );
					$output[ $item ]['data'][ $key ]['start_date'] = $start_dt->format( 'c' ); // store formatted

					if ( 'meet' === $item ) {
						$end_dt = clone $start_dt;
						$end_dt->modify( "+{$m['duration']} minutes" );

						$output[ $item ]['data'][ $key ]['end_date'] = $end_dt->format( 'c' );

						$intv = $start_dt->diff( $end_dt );
						$output[ $item ]['data'][ $key ]['duration'] = sprintf(
							'%d %s %d %s %d %s',
							( $intv->days * 24 ) + $intv->h,
							__( 'hr', 'academy-pro' ),
							$intv->i,
							__( 'min', 'academy-pro' ),
							$intv->s,
							__( 's', 'academy-pro' )
						);
					} else {
						$end_dt = clone $start_dt;
						$end_dt->modify( "+{$m['duration']} minutes" );

						$output[ $item ]['data'][ $key ]['end_date'] = $end_dt->format( 'c' );
						$output[ $item ]['data'][ $key ]['duration'] = sprintf(
							'%d %s',
							$m['duration'],
							__( 'min', 'academy-pro' )
						);
					}//end if
				}//end foreach
			}//end foreach
		}//end if
		return $output;
	}
}
