<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

$users = getAllUsers();
if (empty($users)) {
    die("No users found");
}
$user = $users[0]; // Get the first user
echo "Checking for user: " . $user['email'] . "\n";

$appPassword = decryptData($user['fampay_app_password_encrypted']);
$conn = connectFamAppGmail($user['fampay_gmail'], $appPassword);
if (!$conn['success']) {
    die("IMAP Error: " . $conn['error']);
}
$inbox = $conn['inbox'];

$sinceDate = date('d-M-Y', time() - 86400);
$emails = imap_search($inbox, 'FROM "no-reply@famapp.in" SINCE "' . $sinceDate . '"', SE_UID);
if (!$emails) {
    echo "No emails found from no-reply@famapp.in\n";
    
    // Check any recent emails
    $all = imap_search($inbox, 'SINCE "' . $sinceDate . '"', SE_UID);
    if ($all) {
        rsort($all);
        $count = 0;
        foreach($all as $uid) {
            if ($count++ > 5) break;
            $header = imap_headerinfo($inbox, imap_msgno($inbox, $uid));
            echo "Email from: " . $header->fromaddress . " | Subject: " . $header->subject . "\n";
        }
    }
} else {
    rsort($emails);
    $uid = $emails[0];
    $header = imap_headerinfo($inbox, imap_msgno($inbox, $uid));
    echo "LATEST MATCH:\nFrom: " . $header->fromaddress . "\nSubject: " . $header->subject . "\n";
    $body = getEmailBodyDecoded($inbox, $uid);
    echo "\n--- BODY ---\n" . substr($body, 0, 500) . "\n...";
}
imap_close($inbox);
