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

$users = getAllUsers();
$user = $users[0];
$gmail = $user['fampay_gmail'];
$pass = decryptData($user['fampay_app_password_encrypted']);

$conn = connectFamAppGmail($gmail, $pass);
if (!$conn['success']) {
    die("IMAP Error: " . $conn['error']);
}

$inbox = $conn['inbox'];
$date = date('d-M-Y', time() - 86400);
$emails = imap_search($inbox, 'FROM "no-reply@famapp.in" SINCE "' . $date . '"', SE_UID);

if (!$emails) {
    echo "No emails found.\n";
} else {
    rsort($emails);
    $count = 0;
    foreach ($emails as $uid) {
        if ($count++ > 5) break;
        $header = imap_headerinfo($inbox, imap_msgno($inbox, $uid));
        $body = getEmailBodyDecoded($inbox, $uid);
        
        echo "Email Time: " . date('Y-m-d H:i:s', $header->udate) . "\n";
        echo "Subject: " . $header->subject . "\n";
        // Extract amount if possible
        if (preg_match('/received[^0-9]{0,15}([\d,]+\.?\d*)\s*from/iu', $body, $m)) {
            echo "Parsed Amount: " . $m[1] . "\n";
        } else {
            echo "Parsed Amount: NONE MATCHED\n";
        }
        echo "--------------------------\n";
    }
}
imap_close($inbox);
