<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);

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

require_once __DIR__ . '/config/koneksi.php';
require_once __DIR__ . '/config/jwt.php';
require_once __DIR__ . '/services/google_play_subscription_service.php';

$rawInput = file_get_contents('php://input');
gps_set_request_id($_SERVER['HTTP_X_REQUEST_ID'] ?? '');
gps_reserve_emergency_memory();
gps_register_shutdown_logger('verify_subscription');

$input = json_decode($rawInput, true);

gps_log('verify subscription request received', [
    'method' => $_SERVER['REQUEST_METHOD'] ?? '',
    'uri' => $_SERVER['REQUEST_URI'] ?? '',
    'remote_addr' => $_SERVER['REMOTE_ADDR'] ?? '',
    'content_type' => $_SERVER['CONTENT_TYPE'] ?? '',
    'content_length' => $_SERVER['CONTENT_LENGTH'] ?? '',
    'raw_input_length' => strlen((string)$rawInput),
    'input' => is_array($input) ? $input : gps_limit_string($rawInput),
    'json_error' => json_last_error_msg(),
]);

if (!is_array($input)) {
    gps_json_response(false, 'Request tidak valid', null, 400);
}

try {
    $mysqli = gps_get_db_connection();
    $authUser = gps_require_auth_user();

    gps_log('auth user resolved', [
        'auth_keys' => array_keys($authUser),
    ]);

    $companyId = gps_get_company_id_from_auth($authUser);
    $userId = gps_get_user_id_from_auth($authUser);

    if ($companyId === '') {
        gps_json_response(false, 'company_id tidak ditemukan di token login', null, 401);
    }

    $data = gps_process_manual_verify($mysqli, $input, [
        'company_id' => $companyId,
        'user_id' => $userId,
    ]);

    gps_json_response(true, 'Subscription berhasil diverifikasi', $data);
} catch (Throwable $e) {
    gps_log_exception('verify fatal error', $e);
    gps_json_response(false, 'Terjadi kesalahan saat verifikasi subscription', null, 500);
}
