<?php
require_once 'config.php';

// ========== توابع عمومی ==========

function write_log_to_file($message, $type = 'info') {
    $log_dir = dirname(__FILE__) . '/logs/';
    if (!file_exists($log_dir)) {
        mkdir($log_dir, 0777, true);
    }
    
    $log_file = $log_dir . 'api_debug_' . date('Y-m-d') . '.log';
    $timestamp = date('Y-m-d H:i:s');
    $log_entry = "[$timestamp] [$type] $message" . PHP_EOL;
    
    file_put_contents($log_file, $log_entry, FILE_APPEND);
}

function api_request($url, $method = 'GET', $data = null, $api_token = null) {
    write_log_to_file("API Request: $method $url", "debug");
    
    $ch = curl_init();
    $headers = ["Accept: application/json"];
    
    if ($api_token) {
        $headers[] = "Authorization: Bearer " . $api_token;
        write_log_to_file("Using API Token: " . substr($api_token, 0, 20) . "...", "debug");
    } else {
        write_log_to_file("ERROR: No API token provided", "error");
        return ['success' => false, 'msg' => 'API Token required'];
    }
    
    $options = [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_FOLLOWLOCATION => true
    ];
    
    if ($method == 'POST') {
        $options[CURLOPT_POST] = true;
        if ($data !== null) {
            $post_fields = json_encode($data);
            $options[CURLOPT_POSTFIELDS] = $post_fields;
            $headers[] = "Content-Type: application/json";
            $options[CURLOPT_HTTPHEADER] = $headers;
            write_log_to_file("POST Data: " . $post_fields, "debug");
        }
    }
    
    curl_setopt_array($ch, $options);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    write_log_to_file("HTTP Code: $http_code", "debug");
    
    if ($curl_error) {
        write_log_to_file("CURL Error: $curl_error", "error");
        return ['success' => false, 'msg' => "CURL Error: $curl_error"];
    }
    
    if ($http_code == 200) {
        $decoded = json_decode($response, true);
        if ($decoded === null) {
            write_log_to_file("Invalid JSON response: $response", "error");
            return ['success' => false, 'msg' => 'Invalid JSON response'];
        }
        write_log_to_file("Response: " . json_encode($decoded), "debug");
        return $decoded;
    }
    
    write_log_to_file("HTTP Error: $http_code, Response: $response", "error");
    return ['success' => false, 'msg' => "HTTP Error: $http_code", 'response' => $response];
}

function build_sub_link($panel, $subId) {
    $parsed = parse_url($panel['url']);
    $host = !empty($panel['sub_domain']) ? $panel['sub_domain'] : $parsed['host'];
    $protocol = isset($parsed['scheme']) ? $parsed['scheme'] : 'http';
    return $protocol . "://" . $host . ":" . $panel['sub_port'] . "/" . $panel['sub_path'] . "/" . $subId;
}

function convert_gb_to_bytes($volume_gb) {
    if ($volume_gb <= 0) return 0;
    return (int)($volume_gb * 1073741824);
}

// ========== دریافت اطلاعات کاربر با UUID (فقط پنل جدید - API Token) ==========
function get_client_info_by_uuid($panel, $uuid) {
    write_log_to_file("=== get_client_info_by_uuid ===", "debug");
    write_log_to_file("UUID: $uuid", "debug");
    
    if (empty($panel['api_token'])) {
        write_log_to_file("ERROR: API token is empty", "error");
        return ['success' => false, 'msg' => 'API Token required'];
    }
    
    $url = rtrim($panel['url'], '/') . "/panel/api/inbounds/getClientTrafficsById/" . urlencode($uuid);
    $result = api_request($url, 'GET', null, $panel['api_token']);
    
    if ($result && isset($result['success']) && $result['success'] === true) {
        if (isset($result['obj']) && is_array($result['obj'])) {
            if (isset($result['obj'][0])) {
                $result['obj'] = $result['obj'][0];
                write_log_to_file("Extracted first object from array", "debug");
            }
        }
        return $result;
    }
    
    return ['success' => false, 'msg' => 'کاربر با UUID یافت نشد'];
}

// ========== تابع اصلی افزایش ترافیک ==========
function increase_client_traffic($panel, $username, $additional_gb) {
    write_log_to_file("========== increase_client_traffic ==========", "info");
    write_log_to_file("Username: $username, Additional GB: $additional_gb", "info");
    
    if (empty($panel['api_token'])) {
        write_log_to_file("ERROR: API token is empty", "error");
        return false;
    }
    
    if (empty($panel['uuid'])) {
        write_log_to_file("خطا: UUID پنل موجود نیست", "error");
        return false;
    }
    
    $additional_bytes = $additional_gb * 1073741824;
    
    $client_info = get_client_info_by_uuid($panel, $panel['uuid']);
    
    if (!$client_info || !isset($client_info['success']) || $client_info['success'] !== true) {
        $error_msg = $client_info['msg'] ?? 'خطای نامشخص';
        write_log_to_file("خطا در دریافت اطلاعات: $error_msg", "error");
        return false;
    }
    
    $user_info = $client_info['obj'];
    $user_uuid = $user_info['uuid'] ?? $user_info['id'] ?? null;
    $user_email = $user_info['email'] ?? $username;
    $current_total_bytes = $user_info['total'] ?? $user_info['totalGB'] ?? 0;
    $new_total_bytes = $current_total_bytes + $additional_bytes;
    
    if (!$user_uuid) {
        write_log_to_file("خطا: UUID کاربر یافت نشد", "error");
        return false;
    }
    
    $settings = [
        "clients" => [[
            "id" => $user_uuid,
            "email" => $user_email,
            "totalGB" => (int)$new_total_bytes,
            "expiryTime" => $user_info['expiryTime'] ?? 0,
            "enable" => $user_info['enable'] ?? true,
            "subId" => $user_info['subId'] ?? ''
        ]],
        "decryption" => "none",
        "fallbacks" => []
    ];
    
    $data = [
        "id" => intval($panel['inbound_id']), 
        "settings" => json_encode($settings)
    ];
    
    $url = rtrim($panel['url'], '/') . "/panel/api/inbounds/updateClient/" . urlencode($user_uuid);
    
    $result = api_request($url, 'POST', $data, $panel['api_token']);
    
    if ($result && isset($result['success']) && $result['success'] === true) {
        write_log_to_file("✅ افزایش ترافیک با موفقیت انجام شد!", "success");
        return true;
    }
    
    $error_msg = $result['msg'] ?? json_encode($result);
    write_log_to_file("❌ خطا در افزایش ترافیک: $error_msg", "error");
    return false;
}

// ========== تمدید سرویس (ریست ترافیک + تنظیم مجدد حجم و زمان) ==========
function renew_client($panel, $username, $volume_gb, $expire_days) {
    write_log_to_file("========== renew_client ==========", "info");
    write_log_to_file("Username: $username, Volume GB: $volume_gb, Days: $expire_days", "info");
    
    if (empty($panel['api_token'])) {
        write_log_to_file("ERROR: API token is empty", "error");
        return ['success' => false, 'msg' => 'API Token required'];
    }
    
    if (empty($panel['uuid'])) {
        write_log_to_file("خطا: UUID پنل موجود نیست", "error");
        return ['success' => false, 'msg' => 'UUID سرویس یافت نشد'];
    }
    
    // دریافت اطلاعات فعلی کاربر
    $client_info = get_client_info_by_uuid($panel, $panel['uuid']);
    
    if (!$client_info || !isset($client_info['success']) || $client_info['success'] !== true) {
        write_log_to_file("خطا در دریافت اطلاعات کاربر", "error");
        return ['success' => false, 'msg' => 'خطا در دریافت اطلاعات کاربر از پنل'];
    }
    
    $user_info = $client_info['obj'];
    $user_uuid = $user_info['uuid'] ?? $user_info['id'] ?? null;
    $user_email = $user_info['email'] ?? $username;
    $user_subid = $user_info['subId'] ?? '';
    
    if (!$user_uuid) {
        write_log_to_file("خطا: UUID کاربر یافت نشد", "error");
        return ['success' => false, 'msg' => 'UUID کاربر یافت نشد'];
    }
    
    // مرحله 1: ریست کردن ترافیک مصرفی (up و down) به صفر
    $reset_url = rtrim($panel['url'], '/') . "/panel/api/inbounds/" . $panel['inbound_id'] . "/resetClientTraffic/" . urlencode($user_email);
    
    $reset_result = api_request($reset_url, 'POST', null, $panel['api_token']);
    
    if (!$reset_result || !isset($reset_result['success']) || $reset_result['success'] !== true) {
        write_log_to_file("⚠️ خطا در ریست ترافیک مصرفی: " . json_encode($reset_result), "warning");
    } else {
        write_log_to_file("✅ ترافیک مصرفی با موفقیت ریست شد", "success");
    }
    
    // مرحله 2: محاسبه حجم جدید به بایت
    $new_total_bytes = convert_gb_to_bytes($volume_gb);
    
    // مرحله 3: محاسبه زمان انقضای جدید (از زمان حال)
    $expiry_ms = ($expire_days > 0) ? (time() + ($expire_days * 86400)) * 1000 : 0;
    
    // مرحله 4: تنظیمات جدید کلاینت (حجم کل و زمان انقضا)
    $settings = [
        "clients" => [[
            "id" => $user_uuid,
            "email" => $user_email,
            "totalGB" => (int)$new_total_bytes,
            "expiryTime" => $expiry_ms,
            "enable" => true,
            "subId" => $user_subid
        ]],
        "decryption" => "none",
        "fallbacks" => []
    ];
    
    $data = [
        "id" => intval($panel['inbound_id']),
        "settings" => json_encode($settings)
    ];
    
    $url = rtrim($panel['url'], '/') . "/panel/api/inbounds/updateClient/" . urlencode($user_uuid);
    
    $result = api_request($url, 'POST', $data, $panel['api_token']);
    
    if ($result && isset($result['success']) && $result['success'] === true) {
        write_log_to_file("✅ تمدید سرویس با موفقیت انجام شد!", "success");
        return ['success' => true, 'msg' => 'تمدید با موفقیت انجام شد'];
    }
    
    $error_msg = $result['msg'] ?? json_encode($result);
    write_log_to_file("❌ خطا در تمدید سرویس: $error_msg", "error");
    return ['success' => false, 'msg' => $error_msg];
}

// ========== ساخت سرویس جدید ==========
function add_client($panel, $username, $total_gb, $expire_days) {
    if (empty($panel['api_token'])) {
        return ['success' => false, 'msg' => 'API Token required'];
    }
    
    $uuid = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4));
    $subId = bin2hex(random_bytes(8));
    
    $total_bytes = convert_gb_to_bytes($total_gb);
    $expiry_ms = ($expire_days > 0) ? (time() + ($expire_days * 86400)) * 1000 : 0;
    
    $settings = json_encode([
        "clients" => [[
            "id" => $uuid,
            "email" => $username,
            "totalGB" => $total_bytes,
            "expiryTime" => $expiry_ms,
            "enable" => true,
            "subId" => $subId
        ]],
        "decryption" => "none",
        "fallbacks" => []
    ]);
    
    $data = ["id" => intval($panel['inbound_id']), "settings" => $settings];
    $url = rtrim($panel['url'], '/') . "/panel/api/inbounds/addClient";
    
    $result = api_request($url, 'POST', $data, $panel['api_token']);
    
    if ($result && isset($result['success']) && $result['success'] === true) {
        return ['success' => true, 'uuid' => $uuid, 'subId' => $subId, 'sub_link' => build_sub_link($panel, $subId)];
    }
    
    return ['success' => false, 'msg' => $result['msg'] ?? 'خطا در ساخت کاربر'];
}

// ========== حذف سرویس با ایمیل ==========
function delete_client($panel, $username) {
    write_log_to_file("========== delete_client ==========", "info");
    write_log_to_file("Username: $username", "info");
    
    if (empty($panel['api_token'])) {
        write_log_to_file("ERROR: API token is empty", "error");
        return false;
    }
    
    $url = rtrim($panel['url'], '/') . "/panel/api/inbounds/" . $panel['inbound_id'] . "/delClientByEmail/" . urlencode($username);
    $result = api_request($url, 'POST', null, $panel['api_token']);
    
    $success = ($result && isset($result['success']) && $result['success'] === true);
    write_log_to_file($success ? "✅ حذف کلاینت با موفقیت انجام شد!" : "❌ خطا در حذف کلاینت", $success ? "success" : "error");
    
    return $success;
}

// ========== حذف سرویس با UUID ==========
function delete_client_by_uuid($panel, $uuid) {
    write_log_to_file("========== delete_client_by_uuid ==========", "info");
    write_log_to_file("UUID: $uuid", "info");
    
    if (empty($panel['api_token'])) {
        write_log_to_file("ERROR: API token is empty", "error");
        return false;
    }
    
    $url = rtrim($panel['url'], '/') . "/panel/api/inbounds/" . $panel['inbound_id'] . "/delClient/" . urlencode($uuid);
    $result = api_request($url, 'POST', null, $panel['api_token']);
    
    return ($result && isset($result['success']) && $result['success'] === true);
}

// ========== همگام‌سازی با پنل ==========
function sync_service_with_panel($pdo, $server_id) {
    $stmt = $pdo->prepare("
        SELECT asv.*, p.url, p.inbound_id, p.sub_port, p.sub_path, p.sub_domain, p.api_token
        FROM agent_servers asv
        JOIN panels p ON asv.panel_id = p.id
        WHERE asv.id = ?
    ");
    $stmt->execute([$server_id]);
    $server = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$server) return false;
    
    if (empty($server['api_token'])) {
        write_log_to_file("ERROR: API token is empty for panel", "error");
        return false;
    }
    
    if (empty($server['uuid'])) {
        write_log_to_file("ERROR: UUID is empty for service", "error");
        return false;
    }
    
    $panel = [
        'url' => $server['url'],
        'api_token' => $server['api_token']
    ];
    
    $info = get_client_info_by_uuid($panel, $server['uuid']);
    
    if ($info && isset($info['success']) && $info['success'] === true) {
        $user_info = $info['obj'];
        
        $uuid = $user_info['id'] ?? $user_info['uuid'] ?? $server['uuid'];
        $total_bytes = $user_info['total'] ?? $user_info['totalGB'] ?? 0;
        $volume_gb = $total_bytes > 0 ? round($total_bytes / 1073741824, 3) : 0;
        
        $expiry_time_ms = $user_info['expiryTime'] ?? 0;
        $expiry_date = null;
        if ($expiry_time_ms > 0 && $expiry_time_ms != -2592000000) {
            $expiry_date = date('Y-m-d H:i:s', $expiry_time_ms / 1000);
        }
        
        $status = $user_info['enable'] ? 1 : 0;
        
        $stmt = $pdo->prepare("
            UPDATE agent_servers 
            SET uuid = ?, volume_gb = ?, expiry_date = ?, status = ?
            WHERE id = ?
        ");
        $stmt->execute([$uuid, $volume_gb, $expiry_date, $status, $server_id]);
        
        return true;
    }
    
    return false;
}

// ========== دریافت پلن‌های یک پنل ==========
function get_panel_plans_api($pdo, $panel_id) {
    $stmt = $pdo->prepare("SELECT * FROM plans WHERE panel_id = ? AND status = 1 ORDER BY price ASC");
    $stmt->execute([$panel_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>