<?php
/**
 * MCAuth.inc
 * Thin session / authentication helper for the OBC Mega-Checklists system.
 *
 * Assumes the main OBC login system already calls session_start() and stores
 * the logged-in member's numeric ID in $_SESSION['member_id'].
 *
 * If your login system uses a different session key, change SESSION_KEY below.
 */

define('SESSION_KEY', 'member_id');   // adjust if your login uses a different key

/**
 * Start the session (safe to call multiple times).
 */
function obc_session_start(): void {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
}

/**
 * Return the current member's ID (positive integer) or null if not logged in.
 */
function obc_member_id(): ?int {
    obc_session_start();
    $id = $_SESSION[SESSION_KEY] ?? null;
    return (is_numeric($id) && (int)$id > 0) ? (int)$id : null;
}

/**
 * Return true only if the session holds a valid, active member.
 * Optionally verifies against the DB (pass $conn to enable).
 */
function obc_is_logged_in(?mysqli $conn = null): bool {
    $id = obc_member_id();
    if ($id === null) return false;
    if ($conn === null) return true;

    // Verify the member still exists and is active
    $stmt = $conn->prepare(
        "SELECT 1 FROM obc_members WHERE id = ? AND status = 'A' LIMIT 1"
    );
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $stmt->store_result();
    $ok = $stmt->num_rows === 1;
    $stmt->close();
    return $ok;
}

/**
 * Convenience: emit a JSON error and exit (used in AJAX handlers).
 */
function obc_json_auth_error(): never {
    http_response_code(401);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'not_logged_in']);
    exit;
}
