<?php

namespace AcademyProCalendar\Events\Mettings;

use AcademyProCalendar\Events\QueryAbstract;

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

class Meet extends QueryAbstract {


	public string $select    = " p.ID,p.post_title,p.post_type,
            m1.meta_value as meeting_type, 
            JSON_UNQUOTE(JSON_EXTRACT(m.meta_value, '$.meetingDate')) as start_date, 
            JSON_UNQUOTE(JSON_EXTRACT(m.meta_value, '$.meetingDuration')) as duration, 
            JSON_UNQUOTE(JSON_EXTRACT(m.meta_value, '$.meetingTimezone')) as timezone";
	public string $count_col = 'p.ID';

	public string $after_query    = 'GROUP BY p.ID';
	public int $per_page       = 0;
	public string $order_direction = 'DESC';

	public function __construct( int $year, int $month, array $ids ) {
		global $wpdb;
		$this->select .= ", (SELECT display_name FROM {$wpdb->users} WHERE ID = p.post_author) as host,
        'Google Meet' as platform_type";
		$this->table  = $wpdb->posts . ' p';
		$this->join   = "
            INNER JOIN {$wpdb->postmeta} m 
                ON p.ID = m.post_id
            INNER JOIN {$wpdb->postmeta} m1 
                ON p.ID = m1.post_id

        ";

		$this->where[]  = 'p.ID IN (' . implode( ',', array_fill( 0, count( $ids ), '%d' ) ) . ')';
		$this->args = $ids;

		$this->where[]  = 'p.post_type = %s';
		$this->args[]   = 'academy_meeting';

		$this->where[]  = 'm1.meta_key = %s';
		$this->args[]   = 'academy_meeting_type';

		$this->where[]  = 'm1.meta_value = %s';
		$this->args[]   = 'google_meet';

		$this->where[]  = 'm.meta_key = %s';
		$this->args[]   = 'academy_meeting_response';

		$this->where[]  = "YEAR(STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(m.meta_value, '$.meetingDate')), '%%Y-%%m-%%dT%%H:%%i:%%s')) = %d";
		$this->args[]   = $year;

		$this->where[]  = "MONTH(STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(m.meta_value, '$.meetingDate')), '%%Y-%%m-%%dT%%H:%%i:%%s')) = %d";
		$this->args[]   = $month;

		$this->order_by  = 'start_date';
	}
}
