<?php
// HTTPS API for the 1mcl.xyz staff portal. Serves pre-generated per-mailbox
// snapshots (written by mail_api_snapshot.php via root cron every 5 min).
// Never touches per-user IMAP passwords.

header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: private, no-store');

$tokenFile = '/etc/mail_api/token.conf';
$snapshotDir = '/var/lib/mail_api/snapshots';

function fail($code, $message) {
    http_response_code($code);
    echo json_encode(array('ok' => false, 'message' => $message), JSON_UNESCAPED_UNICODE);
    exit;
}

if (!is_file($tokenFile)) fail(503, 'API token not configured.');
$expectedToken = trim((string)file_get_contents($tokenFile));
if ($expectedToken === '') fail(503, 'API token not configured.');

$authHeader = '';
if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
    $authHeader = $_SERVER['HTTP_AUTHORIZATION'];
} elseif (function_exists('apache_request_headers')) {
    $h = apache_request_headers();
    if (isset($h['Authorization'])) $authHeader = $h['Authorization'];
}
if (!preg_match('/^Bearer\s+(.+)$/i', trim($authHeader), $m) || !hash_equals($expectedToken, trim($m[1]))) {
    fail(401, 'Unauthorized.');
}

$mailbox = isset($_GET['mailbox']) ? strtolower(trim((string)$_GET['mailbox'])) : '';
if (!preg_match('/^([a-z0-9](?:[a-z0-9.]*[a-z0-9])?)@1m-cl\.com$/', $mailbox, $m)) {
    fail(422, 'Invalid mailbox.');
}
$user = $m[1];
if (!preg_match('/^[a-z0-9][a-z0-9.]{0,63}$/', $user)) fail(422, 'Invalid mailbox.');

$snapshotFile = $snapshotDir . '/' . $user . '.json';
if (!is_file($snapshotFile)) {
    echo json_encode(array('ok' => true, 'messages' => array()), JSON_UNESCAPED_UNICODE);
    exit;
}
$data = json_decode((string)file_get_contents($snapshotFile), true);
$messages = is_array($data) && isset($data['messages']) ? $data['messages'] : array();

$limit = isset($_GET['limit']) ? max(1, min(30, (int)$_GET['limit'])) : 30;
if (count($messages) > $limit) $messages = array_slice($messages, 0, $limit);

echo json_encode(array('ok' => true, 'messages' => $messages), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
