<?php
// api/api.php

// ====== DEBUG: SEMPRE DEVOLVER JSON ATÉ EM ERRO FATAL ======
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-App-Key');

function fatal_json($status, $msg, $detail = ''): void {
    http_response_code($status);
    echo json_encode([
        'error' => true,
        'message' => $msg,
        'detail' => $detail,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// captura WARNING/NOTICE como exception (opcional, mas ajuda)
set_error_handler(function ($severity, $message, $file, $line) {
    // respeita @
    if (!(error_reporting() & $severity)) return false;
    throw new ErrorException($message, 0, $severity, $file, $line);
});

// captura exceptions não tratadas
set_exception_handler(function ($e) {
    fatal_json(500, 'Unhandled exception', $e->getMessage());
});

// captura erro fatal (parse error em include, etc.)
register_shutdown_function(function () {
    $err = error_get_last();
    if (!$err) return;

    $type = $err['type'] ?? 0;
    // tipos fatais comuns
    $fatalTypes = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
    if (in_array($type, $fatalTypes, true)) {
        $msg = ($err['message'] ?? 'fatal');
        $file = ($err['file'] ?? '');
        $line = ($err['line'] ?? 0);
        fatal_json(500, 'Fatal error', $msg . " @ " . $file . ":" . $line);
    }
});

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

// ====== INCLUDE PRINCIPAL ======
require_once __DIR__ . '/../includes/functions.php';

// ====== “porteira” simples (opcional) ======
const APP_SHARED_KEY = 'MINHA_CHAVE_SECRETA_123456';

function is_valid_app_request(): bool {
    $key = '';
    if (!empty($_SERVER['HTTP_X_APP_KEY'])) {
        $key = trim((string)$_SERVER['HTTP_X_APP_KEY']);
    } elseif (isset($_POST['app_key'])) {
        $key = trim((string)$_POST['app_key']);
    } elseif (isset($_GET['app_key'])) {
        $key = trim((string)$_GET['app_key']);
    }
    return $key === APP_SHARED_KEY;
}

if (!is_valid_app_request()) {
    // 404 pra não “denunciar” o endpoint
    http_response_code(404);
    exit;
}

// ====== PARAMS ======
$action    = $_GET['action']    ?? $_POST['action']    ?? 'app_info';
$pkg       = str_in($_GET['pkg']       ?? $_POST['pkg']       ?? '');
$ver_code  = (int)($_GET['ver_code']   ?? $_POST['ver_code']   ?? 0);
$ver_name  = str_in($_GET['ver_name']  ?? $_POST['ver_name']  ?? '');
$device_id = str_in(
    $_GET['device']
    ?? $_POST['device']
    ?? $_GET['android_id']
    ?? $_POST['android_id']
    ?? $_GET['device_id']
    ?? $_POST['device_id']
    ?? ''
);

try {
    switch ($action) {

        case 'register_device': {
            json_response(['ok' => true, 'device' => $device_id, 'saved' => false, 'disabled' => true, 'ts' => time()], 200);
            break;
        }

        case 'app_info': {
            $data = build_app_info($pkg, $ver_code, $ver_name, $device_id);
            json_response($data, 200);
            break;
        }

        case 'dns_list': {
            $data = get_urls();
            json_response(['urls' => $data], 200);
            break;
        }

        case 'activate_client': {
            $code = str_in($_GET['code'] ?? $_POST['code'] ?? '');
            if ($code === '') {
                json_response(['ok' => false, 'message' => 'Informe o código de ativação.'], 400);
            }
            $data = build_client_login_response_for_device($code, $device_id);
            if (empty($data['ok'])) {
                json_response($data, 404);
            }
            json_response($data, 200);
            break;
        }

        case 'validate_saved_login': {
            $username = str_in($_GET['username'] ?? $_POST['username'] ?? '');
            $password = str_in($_GET['password'] ?? $_POST['password'] ?? '');
            $data = validate_saved_client_login($username, $password, $device_id);
            if (empty($data['ok'])) {
                json_response($data, 403);
            }
            json_response($data, 200);
            break;
        }

        case 'auto_trial':
        case 'start_trial': {
            $data = start_auto_trial($device_id);
            if (empty($data['ok'])) {
                json_response($data, 403);
            }
            json_response($data, 200);
            break;
        }

        case 'ping':
        default:
            json_response(['ok' => true, 'ts' => time()], 200);
    }

} catch (Throwable $e) {
    json_response([
        'error'   => true,
        'message' => 'Server error',
        'detail'  => $e->getMessage(),
    ], 500);
}
