<?php
function mec_find_wordpress_base_path_ar()
{
    $dir = dirname(__FILE__);

    do
    {
        if (
            (file_exists($dir . '/wp-load.php') || is_link($dir . '/wp-load.php')) &&
            (file_exists($dir . '/wp-settings.php') || is_link($dir . '/wp-settings.php'))
        ) return $dir;
    }
    while ($dir = realpath($dir . '/..'));

    return null;
}

define('BASE_PATH', mec_find_wordpress_base_path_ar() . '/');
if (!defined('WP_USE_THEMES')) define('WP_USE_THEMES', false);

global $wp, $wp_query, $wp_the_query, $wp_rewrite, $wp_did_header;
require BASE_PATH . 'wp-load.php';

function mec_ar_parse_hours($hours)
{
    if (is_array($hours)) $hours = implode(',', $hours);
    if (!is_string($hours) || trim($hours) === '') return [];

    $parsed = [];
    foreach (explode(',', $hours) as $hour)
    {
        $hour = (int) trim($hour, ", \t\n\r\0\x0B");
        if ($hour <= 0) continue;

        $parsed[$hour] = $hour;
    }

    $parsed = array_values($parsed);
    sort($parsed, SORT_NUMERIC);

    return $parsed;
}

function mec_ar_get_event_hours_overrides($main)
{
    $q = new WP_Query();
    $event_ids = $q->query([
        'post_type' => $main->get_main_post_type(),
        'posts_per_page' => -1,
        'post_status' => 'any',
        'fields' => 'ids',
        'meta_query' => [
            [
                'key' => 'mec_notifications',
                'compare' => 'EXISTS',
            ],
        ],
    ]);

    if (!is_array($event_ids) || !count($event_ids)) return [];

    $overrides = [];
    foreach ($event_ids as $event_id)
    {
        $event_notifications = get_post_meta($event_id, 'mec_notifications', true);
        if (!is_array($event_notifications)) continue;

        $attendee_report = $event_notifications['attendee_report'] ?? [];
        if (!is_array($attendee_report) || empty($attendee_report['status'])) continue;

        $hours = mec_ar_parse_hours($attendee_report['hours'] ?? '');
        if (!count($hours)) continue;

        $overrides[(int) $event_id] = $hours;
    }

    return $overrides;
}

function mec_ar_can_send_for_hour($event_id, $hour, $global_hours, $event_hours_overrides)
{
    $event_id = (int) $event_id;
    $hour = (int) $hour;

    if (isset($event_hours_overrides[$event_id]) && count($event_hours_overrides[$event_id]))
    {
        return in_array($hour, $event_hours_overrides[$event_id], true);
    }

    return in_array($hour, $global_hours, true);
}

$main = MEC::getInstance('app.libraries.main');

// Blogs
$blogs = [1];

// Current Blog ID
$multisite = function_exists('is_multisite') && is_multisite();
$current_blog_id = get_current_blog_id();

// Database
$db = $main->getDB();

// Multisite
if ($multisite) $blogs = $db->select("SELECT `blog_id` FROM `#__blogs`", 'loadColumn');

$sent_reports = 0;
$now = current_time('Y-m-d H:00');

foreach ($blogs as $blog)
{
    // Switch to Blog
    if ($multisite) switch_to_blog($blog);

    // MEC Notifications
    $notifications = $main->get_notifications();

    // MEC Settings
    $settings = $main->get_settings();

    // Booking is disabled
    if (!isset($settings['booking_status']) || !$settings['booking_status']) continue;

    // Status
    $status = isset($notifications['attendee_report']['status']) && $notifications['attendee_report']['status'];

    // Attendee Report Email is disabled
    if (!$status) continue;

    // Check Last Run Date & Time
    $latest_run = get_option('mec_attendee_report_last_run_datetime', null);
    if ($latest_run && strtotime($latest_run) > strtotime('-1 Hour', strtotime($now))) continue;

    // Global hours
    $global_hours = mec_ar_parse_hours($notifications['attendee_report']['hours'] ?? '');

    // Event-level overrides are evaluated with replace-global semantics.
    $event_hours_overrides = mec_ar_get_event_hours_overrides($main);
    $override_hours_flat = [];
    foreach ($event_hours_overrides as $event_hours) $override_hours_flat = array_merge($override_hours_flat, $event_hours);
    $override_hours_flat = array_values(array_unique($override_hours_flat));

    // We iterate on the union of global and override hours, then filter per event below.
    $hours = array_values(array_unique(array_merge($global_hours, $override_hours_flat)));
    sort($hours, SORT_NUMERIC);

    // No valid hours at all
    if (!count($hours)) continue;

    /**
     * Notification Sender Library
     */
    $notif = $main->getNotifications();

    foreach ($hours as $hour)
    {
        // It's time of the hour that we're going to check
        $time = strtotime('+' . $hour . ' hours', strtotime($now));
        $tstart = floor($time / 3600) * 3600;
        $tend = $time + 3600;

        $mec_dates = $db->select("SELECT `post_id`, `tstart`, `tend` FROM `#__mec_dates` WHERE `tstart` >= $tstart AND `tstart` < $tend", 'loadObjectList');
        if (!count($mec_dates)) continue;

        foreach ($mec_dates as $mec_date)
        {
            if (!get_post($mec_date->post_id)) continue;

            // Event custom hours replace global hours; invalid/empty custom hours fall back to global.
            if (!mec_ar_can_send_for_hour($mec_date->post_id, $hour, $global_hours, $event_hours_overrides)) continue;

            $result = $notif->attendee_report($mec_date->post_id, $mec_date->tstart . ':' . $mec_date->tend);
            if ($result) $sent_reports++;
        }
    }

    // Last Run
    update_option('mec_attendee_report_last_run_datetime', $now, 'no');
}

// Switch to Current Blog
if ($multisite) switch_to_blog($current_blog_id);

echo sprintf(esc_html__('%s notification(s) sent.', 'mec'), $sent_reports);
exit;
