<?php
// ============================================================
// Elegant Work — Token Auth Helper
// Token is always passed in POST body as 'token'
// ============================================================

require_once __DIR__ . '/db.php';

/**
 * Validate token from POST and return user array.
 * Dies with 401 if invalid.
 */
function requireAuth(): array {
    $token = trim($_POST['token'] ?? '');
    if (empty($token)) {
        apiError('Authentication required.', 401);
    }

    $db = getDB();
    $stmt = $db->prepare("
        SELECT u.*, ut.id AS token_record_id, ut.expires_at
        FROM user_tokens ut
        JOIN users u ON u.id = ut.user_id
        WHERE ut.token = ?
          AND ut.expires_at > NOW()
          AND u.is_active = 1
        LIMIT 1
    ");
    $stmt->execute([$token]);
    $user = $stmt->fetch();

    if (!$user) {
        apiError('Invalid or expired token. Please log in again.', 401);
    }

    // Refresh token last_used
    $db->prepare("UPDATE user_tokens SET last_used = NOW() WHERE id = ?")->execute([$user['token_record_id']]);

    // Strip sensitive fields
    unset($user['password_hash']);
    return $user;
}

/**
 * Require a specific role. Role IDs: 1=Admin, 2=Dev, 3=QA, 4=Tech, 5=HR
 */
function requireRole(array $allowedRoles): array {
    $user = requireAuth();
    if (!in_array((int)$user['role_id'], $allowedRoles)) {
        apiError('Insufficient permissions.', 403);
    }
    return $user;
}

/**
 * Standard success response
 */
function apiSuccess($data = [], string $message = 'Success', int $code = 200): void {
    http_response_code($code);
    echo json_encode([
        'success' => true,
        'message' => $message,
        'data'    => $data,
        'errors'  => []
    ]);
    exit;
}

/**
 * Standard error response
 */
function apiError(string $message = 'An error occurred.', int $code = 400, array $errors = []): void {
    http_response_code($code);
    echo json_encode([
        'success' => false,
        'message' => $message,
        'data'    => null,
        'errors'  => $errors
    ]);
    exit;
}

/**
 * Get POST value with optional default
 */
function post(string $key, $default = null) {
    if (!isset($_POST[$key]) || $_POST[$key] === '') return $default;
    $val = $_POST[$key];
    // Auto-decode JSON arrays/objects (sent from JS API.post for array values)
    if (is_string($val) && strlen($val) > 1 && ($val[0] === '[' || $val[0] === '{')) {
        $decoded = json_decode($val, true);
        if (json_last_error() === JSON_ERROR_NONE) return $decoded;
    }
    return $val;
}

/**
 * Paginate query results
 */
function getPagination(): array {
    $page  = max(1, (int)(post('page', 1)));
    $limit = min(100, max(1, (int)(post('limit', 25))));
    $offset = ($page - 1) * $limit;
    return ['page' => $page, 'limit' => $limit, 'offset' => $offset];
}

// CORS & JSON headers
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}
