<?php
/**
 * Meeting Reminder Cron Job
 * --------------------------------------------------
 * Sends email + WhatsApp reminders to attendees
 * before a meeting's scheduled time.
 */

define('ROOT_PATH', dirname(__DIR__));
define('APP_BASE', ROOT_PATH);

date_default_timezone_set('UTC');

if (PHP_SAPI !== 'cli') {
    $secretFile = ROOT_PATH . '/cron/.secret';
    $secret     = is_file($secretFile) ? trim((string) file_get_contents($secretFile)) : '';
    $given      = $_GET['secret'] ?? '';

    if ($secret === '' || $secret === 'CHANGE_THIS_TO_A_RANDOM_SECRET_KEY' || !hash_equals($secret, $given)) {
        http_response_code(403);
        exit('Forbidden');
    }
}

spl_autoload_register(function ($class): void {
    $class        = ltrim($class, '\\');
    $relativePath = str_replace('\\', '/', $class) . '.php';
    $relativePath = str_replace(['Core/', 'System/', 'App/'], ['core/', 'system/', 'app/'], $relativePath);
    $file         = ROOT_PATH . '/' . $relativePath;

    if (file_exists($file)) {
        require_once $file;
    }
});

use Core\System\Env;

Env::bootstrap(ROOT_PATH);

foreach (glob(ROOT_PATH . '/core/app/Helpers/*.php') ?: [] as $helper) {
    require_once $helper;
}


$service = new \Core\App\Services\MeetingReminderService();
$result  = $service->run(PHP_SAPI === 'cli' ? 'cron_cli' : 'cron_http');

if (PHP_SAPI !== 'cli') {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
}

exit(0);
