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

session_start();
require_once '../config.php';
require_once '../api/XrayAPI.php';

header('Content-Type: application/json');

if (!isset($_SESSION['representative_id'])) {
    error_log("AJAX Error: No representative_id in session.");
    echo json_encode(['success' => false, 'message' => 'دسترسی غیرمجاز: نشست شما منقضی شده است.']);
    exit;
}

$action = $_POST['action'] ?? '';
error_log("Action: " . $action);

if ($action === 'get_links') {
    error_log("get_links action triggered.");
    if (!isset($_POST['user_id'], $_POST['inbound_id'], $_POST['xray_user_id'])) {
        error_log("AJAX Error: Missing POST data. Received: " . json_encode($_POST));
        echo json_encode(['success' => false, 'message' => 'اطلاعات ناقص ارسال شده است.']);
        exit;
    }

    $user_id = $_POST['user_id'];
    $inbound_id = $_POST['inbound_id'];
    $xray_user_id = $_POST['xray_user_id'];
    $representative_id = $_SESSION['representative_id'];
    error_log("Data: user_id=$user_id, inbound_id=$inbound_id, xray_user_id=$xray_user_id, rep_id=$representative_id");

    try {
        error_log("Fetching user from DB...");
        $stmt = $pdo->prepare("SELECT * FROM reseller_users WHERE id = ? AND representative_id = ?");
        $stmt->execute([$user_id, $representative_id]);
        $user = $stmt->fetch();

        if (!$user) {
            error_log("AJAX Error: User not found in DB.");
            echo json_encode(['success' => false, 'message' => 'کاربر یافت نشد.']);
            exit;
        }
        error_log("User found: " . json_encode($user));

        $panel_id = $user['panel_id'];
        error_log("Fetching panel $panel_id from DB...");
        $stmt = $pdo->prepare("SELECT * FROM panels WHERE id = ?");
        $stmt->execute([$panel_id]);
        $panel = $stmt->fetch();

        if (!$panel) {
            error_log("AJAX Error: Panel not found in DB.");
            echo json_encode(['success' => false, 'message' => 'پنل یافت نشد.']);
            exit;
        }
        error_log("Panel found: " . $panel['name']);

        error_log("Instantiating XrayAPI...");
        $api = new XrayAPI($panel['url'], $panel['username'], $panel['password'], null, $panel['config_domain']);
        error_log("XrayAPI instantiated. Getting config link...");
        
        // دریافت تنظیمات اختصاصی اینباند (Overrides)
        $overrides = [];
        $st_ov = $pdo->prepare("SELECT address_override, port_override, host_override, path_override, sni_override FROM panel_inbounds WHERE panel_id = ? AND inbound_id = ?");
        $st_ov->execute([$panel_id, $inbound_id]);
        $ov_data = $st_ov->fetch();
        if ($ov_data) {
            $overrides = [
                'address' => $ov_data['address_override'],
                'port' => $ov_data['port_override'],
                'host' => $ov_data['host_override'],
                'path' => $ov_data['path_override'],
                'sni' => $ov_data['sni_override']
            ];
        }

        $config_link = $api->getConfigLink($inbound_id, $xray_user_id, $overrides);
        error_log("getConfigLink result: " . ($config_link ?: 'EMPTY'));

        error_log("Getting subscription link...");
        $subscription_link = $api->getSubscriptionLink($inbound_id, $xray_user_id, $user['sub_id']);
        error_log("getSubscriptionLink result: " . ($subscription_link ?: 'EMPTY'));

        echo json_encode([
            'success' => true, 
            'config_link' => $config_link,
            'subscription_link' => $subscription_link
        ]);
        error_log("--- AJAX Handler Finished Successfully ---");

    } catch (Exception $e) {
        error_log("!!! AJAX FATAL ERROR (get_links): " . $e->getMessage() . " on line " . $e->getLine() . " in " . $e->getFile());
        error_log("Stack Trace: " . $e->getTraceAsString());
        echo json_encode(['success' => false, 'message' => 'خطای سرور: ' . $e->getMessage()]);
    }
    exit;
}

error_log("AJAX Error: Invalid action requested.");
echo json_encode(['success' => false, 'message' => 'عملیات نامعتبر']);
?>