<?php
error_reporting(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('plan');

gps_log('plan 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),
]);

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

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

    $companyId = gps_get_company_id_from_auth($authUser);

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

    if (!gps_company_exists($mysqli, $companyId)) {
        gps_json_response(false, 'Company tidak ditemukan', null, 404);
    }

    $status = gps_build_plan_status($mysqli, $companyId);
    gps_json_response(true, 'Status plan berhasil diambil', $status);
} catch (Throwable $e) {
    gps_log_exception('plan fatal error', $e);
    gps_json_response(false, 'Terjadi kesalahan saat mengambil status plan', null, 500);
}
