<?php
/**
 * check-access.php
 * -----------------------------------------------------------------
 * Public endpoint called by the dashboard. Given an email, it:
 *  - creates a record for that email if it's new (status: "trial")
 *  - returns the current status ("trial" or "active")
 *
 * The dashboard calls this when the visitor hits the free-trial wall
 * and enters their email, and again on later visits to silently
 * refresh whether the admin has activated them yet.
 * -----------------------------------------------------------------
 */

require_once __DIR__ . '/access-lib.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');      // tighten to your own domain once live
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed. Use POST.']);
    exit;
}

$payload = json_decode(file_get_contents('php://input'), true);
$email = is_array($payload) ? ($payload['email'] ?? '') : '';

$record = access_get_or_create($email);
if (!$record) {
    http_response_code(400);
    echo json_encode(['error' => 'A valid email address is required.']);
    exit;
}

echo json_encode([
    'email'        => $record['email'],
    'status'       => $record['status'],
    'activated_at' => $record['activated_at'],
]);