<?php
/**
 * Shared API helpers for SufarmaERP Migrated APIs
 */

header('Content-Type: application/json; charset=utf-8');

/**
 * Parse JSON from request body
 */
function json_input(): array {
    $raw = file_get_contents('php://input');
    $data = json_decode($raw, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        json_error('JSON inválido: ' . json_last_error_msg(), 400);
    }
    return $data ?? [];
}

/**
 * Validate required fields exist and are non-empty
 */
function require_fields(array $data, array $fields): void {
    foreach ($fields as $f) {
        if (!isset($data[$f]) || (is_string($data[$f]) && trim($data[$f]) === '')) {
            json_error("Campo requerido faltante: $f", 400);
        }
    }
}

/**
 * Send success JSON response
 */
function json_success($data = [], string $message = 'OK'): void {
    echo json_encode([
        'success' => true,
        'message' => $message,
        'data'    => $data,
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * Send error JSON response
 */
function json_error(string $message = 'Error', int $code = 500): void {
    http_response_code($code);
    echo json_encode([
        'success' => false,
        'message' => $message,
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * Ensure request method is POST
 */
function require_post(): void {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        json_error('Método no permitido', 405);
    }
}

/**
 * Get the "General" location ID, creating it if needed
 */
function get_general_id(PDO $pdo): int {
    $stmt = $pdo->query("SELECT id FROM lugarcompra WHERE nombre = 'General' LIMIT 1");
    $row = $stmt->fetch();
    if ($row) return (int) $row['id'];

    $pdo->exec("INSERT INTO lugarcompra (nombre) VALUES ('General')");
    return (int) $pdo->lastInsertId();
}
