#!/usr/bin/env php
<?php
/**
 * Cron environment check – run this to verify cron scripts can run
 * Usage: php cron/cron-check.php
 * Or from project root: php cron/cron-check.php
 */

if (php_sapi_name() !== 'cli') {
    die("Run from command line: php cron/cron-check.php\n");
}

$baseDir = dirname(__DIR__);
chdir($baseDir);
echo "Project root: " . getcwd() . "\n";

// 1. Config and DB
try {
    require_once $baseDir . '/config/app.php';
    require_once $baseDir . '/config/database.php';
    echo "Config and database: OK (PDO connected)\n";
} catch (Throwable $e) {
    echo "ERROR Config/DB: " . $e->getMessage() . "\n";
    exit(1);
}

// 2. Settings (used by birthday/event cron)
try {
    require_once $baseDir . '/includes/settings.php';
    $v = getSetting('birthday_sms', '');
    echo "Settings: OK\n";
} catch (Throwable $e) {
    echo "ERROR Settings: " . $e->getMessage() . "\n";
    exit(1);
}

// 3. Birthday script dependencies
try {
    require_once $baseDir . '/includes/birthdays.php';
    $todayMonth = (int) date('n');
    $todayDay = (int) date('j');
    $members = getMembersWithBirthdayOn($pdo, $todayMonth, $todayDay);
    echo "Birthday wishes: OK (" . count($members) . " birthday(s) today)\n";
} catch (Throwable $e) {
    echo "ERROR Birthday helpers: " . $e->getMessage() . "\n";
    exit(1);
}

// 4. Log directory
$logDir = $baseDir . '/logs';
if (!is_dir($logDir)) {
    echo "Note: logs/ directory missing – cron will only write to stderr. Create with: mkdir -p " . $logDir . "\n";
} elseif (!is_writable($logDir)) {
    echo "Note: logs/ exists but is not writable – cron will only write to stderr.\n";
} else {
    echo "Logs directory: OK (writable)\n";
}

// 5. PHP path for crontab (cron often has minimal PATH)
$phpPath = 'php';
if (defined('PHP_BINARY') && PHP_BINARY !== '') {
    $phpPath = PHP_BINARY;
} elseif (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' && @is_executable('/usr/bin/php')) {
    $phpPath = '/usr/bin/php';
}
echo "\nSuggested cron command:\n";
echo "  0 8 * * * cd " . $baseDir . " && " . $phpPath . " cron/birthday-wishes.php\n";
echo "\nIf cron does nothing, use the FULL path to php. Find it by running: which php\n";
echo "Then in crontab use that path instead of 'php'.\n";
echo "\nTest birthday script now: cd " . $baseDir . " && " . $phpPath . " cron/birthday-wishes.php\n";
exit(0);
