<?php
/**
 * access-lib.php
 * -----------------------------------------------------------------
 * Shared helper functions for the manual "interim" access system —
 * used while waiting for Lemon Squeezy to go live. Tracks visitor
 * emails and a simple trial/active status in a JSON file on the
 * server, so access can be granted manually from admin/index.php
 * after you confirm payment via WhatsApp/email.
 *
 * This is NOT meant to be a long-term licensing system — once Lemon
 * Squeezy is live and webhooks are wired up, this can be retired.
 * -----------------------------------------------------------------
 */

// Same placement pattern as groq-secret.php / anthropic-secret.php:
// OUTSIDE public_html, in the account home directory.
define('ACCESS_DATA_DIR', '/home/caracuanbiz/clyde-dashboard-data');
define('ACCESS_DATA_FILE', ACCESS_DATA_DIR . '/access.json');

function access_ensure_storage() {
    if (!is_dir(ACCESS_DATA_DIR)) {
        @mkdir(ACCESS_DATA_DIR, 0700, true);
    }
    if (!is_file(ACCESS_DATA_FILE)) {
        file_put_contents(ACCESS_DATA_FILE, json_encode(new stdClass()), LOCK_EX);
    }
}

function access_load_all() {
    access_ensure_storage();
    $fp = fopen(ACCESS_DATA_FILE, 'r');
    if (!$fp) return [];
    flock($fp, LOCK_SH);
    $contents = stream_get_contents($fp);
    flock($fp, LOCK_UN);
    fclose($fp);
    $data = json_decode($contents, true);
    return is_array($data) ? $data : [];
}

function access_save_all($data) {
    access_ensure_storage();
    $fp = fopen(ACCESS_DATA_FILE, 'c');
    if (!$fp) return false;
    flock($fp, LOCK_EX);
    ftruncate($fp, 0);
    rewind($fp);
    fwrite($fp, json_encode($data, JSON_PRETTY_PRINT));
    fflush($fp);
    flock($fp, LOCK_UN);
    fclose($fp);
    return true;
}

function access_normalize_email($email) {
    return strtolower(trim((string)$email));
}

// Returns the record for an email, creating a fresh "trial" record if
// it doesn't exist yet.
function access_get_or_create($email) {
    $email = access_normalize_email($email);
    if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return null;
    }
    $all = access_load_all();
    if (!isset($all[$email])) {
        $all[$email] = [
            'email'        => $email,
            'status'       => 'trial', // 'trial' | 'active'
            'first_seen'   => gmdate('c'),
            'activated_at' => null,
            'notes'        => '',
        ];
        access_save_all($all);
    }
    return $all[$email];
}

function access_set_status($email, $status, $notes = null) {
    $email = access_normalize_email($email);
    $all = access_load_all();
    if (!isset($all[$email])) {
        $all[$email] = [
            'email'        => $email,
            'status'       => 'trial',
            'first_seen'   => gmdate('c'),
            'activated_at' => null,
            'notes'        => '',
        ];
    }
    $all[$email]['status'] = $status === 'active' ? 'active' : 'trial';
    $all[$email]['activated_at'] = $status === 'active' ? gmdate('c') : null;
    if ($notes !== null) {
        $all[$email]['notes'] = $notes;
    }
    access_save_all($all);
    return $all[$email];
}