<?php
/**
 * Rig N Dig - API Helper
 */

function apiResponse($success, $message, $data = [], $code = 200) {
    // Keep header as application/json if not already set
    if (!headers_sent()) {
        header('Content-Type: application/json');
    }
    http_response_code($code);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ]);
    exit;
}

function getBearerToken() {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    if ($authHeader) {
        if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            return $matches[1];
        }
    }
    return null;
}

function generateApiToken($userId) {
    $hash = hash_hmac('sha256', (string)$userId, APP_SECRET);
    return $userId . ':' . $hash;
}

function authenticateAPI() {
    $token = getBearerToken();
    if (!$token) {
        apiResponse(false, 'Authorization token required', [], 401);
    }
    
    $parts = explode(':', $token);
    if (count($parts) !== 2) {
        apiResponse(false, 'Invalid token format', [], 401);
    }
    
    $userId = (int)$parts[0];
    $hash = $parts[1];
    
    $expectedHash = hash_hmac('sha256', (string)$userId, APP_SECRET);
    if (!hash_equals($expectedHash, $hash)) {
        apiResponse(false, 'Invalid or expired token', [], 401);
    }
    
    $user = Database::fetchOne("SELECT id, company_name, contact_name, email, phone, status FROM customers WHERE id = ? AND status = 'active'", [$userId]);
    if (!$user) {
        apiResponse(false, 'User not found or inactive', [], 401);
    }
    
    return $user;
}

/**
 * polyfill for getallheaders if not exists
 */
if (!function_exists('getallheaders')) {
    function getallheaders() {
        $headers = [];
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}
