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

require_once '../../vippanneladmin56329803/config.php';
require_once '../../vippanneladmin56329803/api.php';
require_once 'marzban_api.php';

function displayText($text) {
    if ($text === null) return '';
    return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

if (!isset($_SESSION['agent_id'])) {
    header("Location: ../agent.php");
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM agents WHERE id = ?");
$stmt->execute([$_SESSION['agent_id']]);
$agent = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$agent) {
    session_destroy();
    header("Location: ../agent.php");
    exit;
}

$message = null;
$error = null;

function getAgentServers($pdo, $agent_id) {
    $stmt = $pdo->prepare("
        SELECT asv.*, 
               p.name as panel_name, p.url as panel_url, p.panel_type, 
               p.marzban_username, p.marzban_password, p.selected_inbounds,
               p.extra_traffic_enabled, p.extra_traffic_price_per_gb, p.extra_traffic_min, p.extra_traffic_max,
               p.refund_enabled, p.refund_min_remaining_gb, p.refund_min_remaining_days, p.renewal_enabled,
               p.custom_volume_enabled, p.custom_volume_price_per_gb, p.custom_volume_price_per_day,
               p.custom_volume_min_gb, p.custom_volume_max_gb, p.custom_volume_min_days, p.custom_volume_max_days,
               pl.name as plan_name, pl.volume_gb as plan_volume, pl.days as plan_days
        FROM agent_servers asv
        LEFT JOIN panels p ON asv.panel_id = p.id
        LEFT JOIN plans pl ON asv.plan_id = pl.id
        WHERE asv.agent_id = ?
        ORDER BY asv.id DESC
    ");
    $stmt->execute([$agent_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getTotalVolumeAndPrice($pdo, $server_id) {
    $stmt = $pdo->prepare("SELECT * FROM renewal_logs WHERE server_id = ? ORDER BY created_at DESC LIMIT 1");
    $stmt->execute([$server_id]);
    $last_renewal = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($last_renewal && !empty($last_renewal)) {
        $base_volume = $last_renewal['new_volume_gb'];
        $base_price = $last_renewal['price'];
        $renewal_date = $last_renewal['created_at'];
        
        $stmt = $pdo->prepare("SELECT IFNULL(SUM(volume_gb), 0) as total_extra_volume, IFNULL(SUM(price), 0) as total_extra_price FROM extra_traffic_logs WHERE server_id = ? AND created_at > ?");
        $stmt->execute([$server_id, $renewal_date]);
    } else {
        $stmt = $pdo->prepare("SELECT volume_gb as base_volume, price as base_price FROM agent_servers WHERE id = ?");
        $stmt->execute([$server_id]);
        $server_data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$server_data) {
            return ['base_volume' => 0, 'base_price' => 0, 'extra_volume' => 0, 'extra_price' => 0, 'total_volume' => 0, 'total_price' => 0, 'has_renewal' => false, 'renewal_date' => null];
        }
        
        $base_volume = $server_data['base_volume'];
        $base_price = $server_data['base_price'];
        
        $stmt = $pdo->prepare("SELECT IFNULL(SUM(volume_gb), 0) as total_extra_volume, IFNULL(SUM(price), 0) as total_extra_price FROM extra_traffic_logs WHERE server_id = ?");
        $stmt->execute([$server_id]);
    }
    
    $extra = $stmt->fetch(PDO::FETCH_ASSOC);
    $extra_volume = $extra['total_extra_volume'] ?? 0;
    $extra_price = $extra['total_extra_price'] ?? 0;
    
    return [
        'base_volume' => $base_volume ?? 0,
        'base_price' => $base_price ?? 0,
        'extra_volume' => $extra_volume,
        'extra_price' => $extra_price,
        'total_volume' => ($base_volume ?? 0) + $extra_volume,
        'total_price' => ($base_price ?? 0) + $extra_price,
        'has_renewal' => !empty($last_renewal),
        'renewal_date' => $last_renewal['created_at'] ?? null
    ];
}

// خرید ترافیک اضافه
if (isset($_POST['action']) && $_POST['action'] == 'buy_extra_traffic') {
    $server_id = intval($_POST['server_id']);
    $extra_gb = floatval($_POST['extra_gb']);
    
    $stmt = $pdo->prepare("SELECT asv.*, p.* FROM agent_servers asv JOIN panels p ON asv.panel_id = p.id WHERE asv.id = ? AND asv.agent_id = ?");
    $stmt->execute([$server_id, $agent['id']]);
    $server = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$server) {
        $error = "سرویس یافت نشد";
    } elseif (!$server['extra_traffic_enabled']) {
        $error = "خرید ترافیک اضافه برای این پنل فعال نیست";
    } elseif ($extra_gb < $server['extra_traffic_min'] || $extra_gb > $server['extra_traffic_max']) {
        $error = "حجم باید بین {$server['extra_traffic_min']} و {$server['extra_traffic_max']} گیگ باشد";
    } else {
        $base_price = $extra_gb * $server['extra_traffic_price_per_gb'];
        $discount_percent = $agent['discount'];
        $total_price = $discount_percent > 0 ? round($base_price - ($base_price * $discount_percent / 100)) : $base_price;
        
        if ($agent['balance'] < $total_price) {
            $error = "موجودی کافی نیست. نیاز: " . number_format($total_price) . " تومان";
        }
    }
    
    if (!$error) {
        $update_result = false;
        if ($server['panel_type'] == 'marzban') {
            $panel = ['url' => $server['url'], 'marzban_username' => $server['marzban_username'], 'marzban_password' => $server['marzban_password']];
            $update_result = marzban_add_volume($panel, $server['username'], $extra_gb);
        } else {
            $panel_info = ['url' => $server['url'], 'api_token' => $server['api_token'], 'inbound_id' => $server['inbound_id'], 'uuid' => $server['uuid']];
            $update_result = increase_client_traffic($panel_info, $server['username'], $extra_gb);
        }
        
        if ($update_result) {
            $stmt = $pdo->prepare("INSERT INTO extra_traffic_logs (server_id, agent_id, panel_id, username, volume_gb, price, discount_percent, original_price, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([$server_id, $agent['id'], $server['panel_id'], $server['username'], $extra_gb, $total_price, $discount_percent, $base_price]);
            $pdo->prepare("UPDATE agents SET balance = balance - ? WHERE id = ?")->execute([$total_price, $agent['id']]);
            $stmt = $pdo->prepare("SELECT * FROM agents WHERE id = ?");
            $stmt->execute([$agent['id']]);
            $agent = $stmt->fetch(PDO::FETCH_ASSOC);
            $message = "{$extra_gb} گیگ ترافیک اضافه خریداری شد. مبلغ: " . number_format($total_price) . " تومان";
        } else {
            $error = "خطا در افزایش حجم روی پنل";
        }
    }
}

// تابع تمدید با حجم دلخواه
function renewCustomVolumeService($pdo, $agent, $server, $volume_gb, $days) {
    $price_per_gb = $server['custom_volume_price_per_gb'];
    $price_per_day = $server['custom_volume_price_per_day'];
    $total_price = ($volume_gb * $price_per_gb) + ($days * $price_per_day);
    if ($agent['discount'] > 0) $total_price = round($total_price - ($total_price * $agent['discount'] / 100));
    if ($agent['balance'] < $total_price) return ['success' => false, 'error' => 'موجودی کافی نیست'];
    
    if ($server['panel_type'] == 'marzban') {
        $panel = ['url' => $server['url'], 'marzban_username' => $server['marzban_username'], 'marzban_password' => $server['marzban_password']];
        $result = marzban_renew_service($panel, $server['username'], $volume_gb, $days);
    } else {
        $panel_info = ['url' => $server['url'], 'api_token' => $server['api_token'], 'uuid' => $server['uuid'], 'inbound_id' => $server['inbound_id']];
        $result = renew_client($panel_info, $server['username'], $volume_gb, $days);
    }
    
    if ($result === true || (is_array($result) && isset($result['success']) && $result['success'])) {
        $new_expiry_date = $days > 0 ? date('Y-m-d H:i:s', strtotime("+{$days} days")) : null;
        $stmt = $pdo->prepare("INSERT INTO renewal_logs (server_id, agent_id, panel_id, username, old_plan_id, new_plan_id, old_volume_gb, new_volume_gb, old_expiry_date, new_expiry_date, price, is_custom_renewal, custom_volume_gb, custom_days, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, NOW())");
        $stmt->execute([$server['id'], $agent['id'], $server['panel_id'], $server['username'], $server['plan_id'], 0, $server['volume_gb'], $volume_gb, $server['expiry_date'], $new_expiry_date, $total_price, $volume_gb, $days]);
        $pdo->prepare("DELETE FROM extra_traffic_logs WHERE server_id = ?")->execute([$server['id']]);
        $stmt = $pdo->prepare("UPDATE agent_servers SET plan_id = 0, volume_gb = ?, expiry_date = ?, days = ?, price = ? WHERE id = ?");
        $stmt->execute([$volume_gb, $new_expiry_date, $days, $total_price, $server['id']]);
        $pdo->prepare("UPDATE agents SET balance = balance - ? WHERE id = ?")->execute([$total_price, $agent['id']]);
        return ['success' => true, 'price' => $total_price];
    }
    return ['success' => false, 'error' => 'خطا در تمدید سرویس'];
}

// تمدید سرویس
if (isset($_POST['action']) && $_POST['action'] == 'renew_service') {
    $server_id = intval($_POST['server_id']);
    $plan_id = intval($_POST['plan_id']);
    $renew_type = $_POST['renew_type'] ?? 'plan';
    
    $stmt = $pdo->prepare("SELECT asv.*, p.* FROM agent_servers asv JOIN panels p ON asv.panel_id = p.id WHERE asv.id = ? AND asv.agent_id = ?");
    $stmt->execute([$server_id, $agent['id']]);
    $server = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$server) $error = "سرویس یافت نشد";
    elseif (!$server['renewal_enabled']) $error = "تمدید سرویس برای این پنل فعال نیست";
    
    $plan = null;
    $volume_gb = 0;
    $days = 0;
    $final_price = 0;
    
    if ($renew_type == 'plan' && !$error) {
        $stmt = $pdo->prepare("SELECT * FROM plans WHERE id = ? AND status = 1");
        $stmt->execute([$plan_id]);
        $plan = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$plan) $error = "پلن مورد نظر یافت نشد";
        else {
            $volume_gb = $plan['volume_gb'];
            $days = $plan['days'];
            $final_price = $plan['price'];
            if ($agent['discount'] > 0) $final_price = round($plan['price'] - ($plan['price'] * $agent['discount'] / 100));
        }
    } elseif ($renew_type == 'custom' && !$error) {
        $volume_gb = floatval($_POST['volume_gb']);
        $days = intval($_POST['days']);
        if (!$server['custom_volume_enabled']) $error = "خرید حجم دلخواه برای این پنل فعال نیست";
        elseif ($volume_gb < $server['custom_volume_min_gb'] || $volume_gb > $server['custom_volume_max_gb']) $error = "حجم وارد شده باید بین {$server['custom_volume_min_gb']} و {$server['custom_volume_max_gb']} گیگابایت باشد";
        elseif ($days < $server['custom_volume_min_days'] || $days > $server['custom_volume_max_days']) $error = "تایم وارد شده باید بین {$server['custom_volume_min_days']} و {$server['custom_volume_max_days']} روز باشد";
        else {
            $price_per_gb = $server['custom_volume_price_per_gb'];
            $price_per_day = $server['custom_volume_price_per_day'];
            $final_price = ($volume_gb * $price_per_gb) + ($days * $price_per_day);
            if ($agent['discount'] > 0) $final_price = round($final_price - ($final_price * $agent['discount'] / 100));
        }
    }
    
    if ($agent['balance'] < $final_price && !$error) $error = "موجودی کافی نیست. نیاز: " . number_format($final_price) . " تومان";
    
    if (isset($_POST['confirm_renew']) && $_POST['confirm_renew'] == '1' && !$error) {
        if ($renew_type == 'plan') {
            if ($server['panel_type'] == 'marzban') {
                $panel = ['url' => $server['url'], 'marzban_username' => $server['marzban_username'], 'marzban_password' => $server['marzban_password']];
                $renew_result = marzban_renew_service($panel, $server['username'], $volume_gb, $days);
            } else {
                $panel_info = ['url' => $server['url'], 'api_token' => $server['api_token'], 'uuid' => $server['uuid'], 'inbound_id' => $server['inbound_id']];
                $renew_result = renew_client($panel_info, $server['username'], $volume_gb, $days);
            }
            
            if ($renew_result === true || (is_array($renew_result) && isset($renew_result['success']) && $renew_result['success'])) {
                $new_expiry_date = $days > 0 ? date('Y-m-d H:i:s', strtotime("+{$days} days")) : null;
                $stmt = $pdo->prepare("INSERT INTO renewal_logs (server_id, agent_id, panel_id, username, old_plan_id, new_plan_id, old_volume_gb, new_volume_gb, old_expiry_date, new_expiry_date, price, is_custom_renewal, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NOW())");
                $stmt->execute([$server_id, $agent['id'], $server['panel_id'], $server['username'], $server['plan_id'], $plan['id'], $server['volume_gb'], $volume_gb, $server['expiry_date'], $new_expiry_date, $final_price]);
                $pdo->prepare("DELETE FROM extra_traffic_logs WHERE server_id = ?")->execute([$server_id]);
                $stmt = $pdo->prepare("UPDATE agent_servers SET plan_id = ?, volume_gb = ?, expiry_date = ?, days = ?, price = ? WHERE id = ?");
                $stmt->execute([$plan['id'], $volume_gb, $new_expiry_date, $days, $final_price, $server_id]);
                $pdo->prepare("UPDATE agents SET balance = balance - ? WHERE id = ?")->execute([$final_price, $agent['id']]);
                $_SESSION['message'] = "سرویس با موفقیت تمدید شد. حجم جدید: {$volume_gb} GB";
                header("Location: manage_services.php");
                exit;
            } else $error = "خطا در تمدید سرویس";
        } elseif ($renew_type == 'custom') {
            $result = renewCustomVolumeService($pdo, $agent, $server, $volume_gb, $days);
            if ($result['success']) {
                $_SESSION['message'] = "سرویس با موفقیت تمدید شد. حجم جدید: {$volume_gb} GB, مدت: {$days} روز";
                header("Location: manage_services.php");
                exit;
            } else $error = $result['error'];
        }
    }
    
    if (!isset($_POST['confirm_renew']) && !$error && (isset($plan) || $renew_type == 'custom')) {
        ?>
        <!DOCTYPE html>
        <html dir="rtl" lang="fa">
        <head><meta charset="UTF-8"><title>تأیید تمدید</title>
        <style>
            *{margin:0;padding:0;box-sizing:border-box;}
            body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;background:linear-gradient(135deg,#e0e7ff 0%,#f3e8ff 100%);min-height:100vh;padding:50px 20px;}
            .container{max-width:500px;margin:0 auto;}
            .confirm-box{background:white;border-radius:24px;padding:30px;box-shadow:0 20px 40px rgba(0,0,0,0.1);}
            .confirm-title{font-size:20px;margin-bottom:20px;color:#1f2937;display:flex;align-items:center;gap:8px;}
            .warning-box{background:#fef3c7;border:1px solid #fde68a;border-radius:12px;padding:15px;margin:15px 0;color:#92400e;}
            .confirm-list{margin:10px 0 0 20px;}
            .info-row{display:flex;justify-content:space-between;padding:10px 0;border-bottom:1px solid #e5e7eb;}
            .info-row.total{border-top:2px solid #e5e7eb;border-bottom:none;margin-top:10px;padding-top:15px;font-weight:700;color:#7c3aed;}
            .confirm-form{display:flex;gap:15px;margin-top:25px;}
            .btn-confirm{flex:1;background:#7c3aed;color:white;border:none;padding:12px;border-radius:40px;font-weight:700;cursor:pointer;}
            .btn-cancel{flex:1;background:#f3f4f6;color:#374151;border:none;padding:12px;border-radius:40px;font-weight:600;cursor:pointer;text-align:center;text-decoration:none;display:inline-block;}
            .svg-icon{display:inline-block;vertical-align:middle;}
        </style>
        </head>
        <body>
        <div class="container"><div class="confirm-box">
            <div class="confirm-title"><svg class="svg-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg> تأیید تمدید سرویس</div>
            <div class="warning-box"><strong>توجه مهم:</strong><br><ul class="confirm-list"><li>حجم مصرفی فعلی شما صفر می‌شود</li><li>حجم کل به حجم جدید تنظیم می‌شود</li><li>تاریخ انقضا از امروز محاسبه می‌شود</li><li><strong>تمام ترافیک‌های اضافه قبلی حذف می‌شوند</strong></li></ul></div>
            <div class="info-row"><strong>سرویس:</strong> <span><?= htmlspecialchars($server['username']) ?></span></div>
            <div class="info-row"><strong>حجم جدید:</strong> <span><?= $volume_gb == 0 ? 'نامحدود' : $volume_gb . ' GB' ?></span></div>
            <div class="info-row"><strong>مدت جدید:</strong> <span><?= $days == 0 ? 'نامحدود' : $days . ' روز' ?></span></div>
            <div class="info-row total"><strong>مبلغ:</strong> <span><?= number_format($final_price) ?> تومان</span></div>
            <form method="POST" class="confirm-form">
                <input type="hidden" name="action" value="renew_service">
                <input type="hidden" name="server_id" value="<?= $server_id ?>">
                <input type="hidden" name="plan_id" value="<?= $plan_id ?>">
                <input type="hidden" name="renew_type" value="<?= $renew_type ?>">
                <?php if($renew_type == 'custom'): ?>
                    <input type="hidden" name="volume_gb" value="<?= $volume_gb ?>">
                    <input type="hidden" name="days" value="<?= $days ?>">
                <?php endif; ?>
                <input type="hidden" name="confirm_renew" value="1">
                <button type="submit" class="btn-confirm">تأیید تمدید</button>
                <a href="manage_services.php" class="btn-cancel">انصراف</a>
            </form>
        </div></div></body></html>
        <?php
        exit;
    }
}

// حذف سرویس
if (isset($_POST['action']) && $_POST['action'] == 'delete_service') {
    $server_id = intval($_POST['server_id']);
    $stmt = $pdo->prepare("SELECT asv.*, p.* FROM agent_servers asv JOIN panels p ON asv.panel_id = p.id WHERE asv.id = ? AND asv.agent_id = ?");
    $stmt->execute([$server_id, $agent['id']]);
    $server = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$server) $error = "سرویس یافت نشد";
    
    $used_traffic_gb = 0;
    $remaining_days = PHP_INT_MAX;
    $client_info_success = false;
    
    if (!$error) {
        if ($server['panel_type'] == 'marzban') {
            $panel = ['url' => $server['url'], 'marzban_username' => $server['marzban_username'], 'marzban_password' => $server['marzban_password']];
            $info = marzban_get_client_info($panel, $server['username']);
            if ($info['success']) {
                $client_info_success = true;
                $used_traffic_gb = round($info['obj']['up'] / 1073741824, 2);
                if ($info['obj']['expiryTime'] > 0) $remaining_days = max(0, floor(($info['obj']['expiryTime'] / 1000 - time()) / 86400));
            }
        } else {
            $panel_info = ['url' => $server['url'], 'api_token' => $server['api_token']];
            $info = get_client_info_by_uuid($panel_info, $server['uuid']);
            if ($info && isset($info['success']) && $info['success'] === true) {
                $client_info_success = true;
                $user = $info['obj'];
                $used_bytes = ($user['up'] ?? 0) + ($user['down'] ?? 0);
                $used_traffic_gb = round($used_bytes / 1073741824, 2);
                if (($user['expiryTime'] ?? 0) > 0) $remaining_days = max(0, floor(($user['expiryTime'] / 1000 - time()) / 86400));
            }
        }
    }
    
    $total_info = getTotalVolumeAndPrice($pdo, $server_id);
    $refund_amount = 0;
    $can_refund = $server['refund_enabled'];
    if ($can_refund && $total_info['total_volume'] > 0) {
        $remaining_volume = max(0, $total_info['total_volume'] - $used_traffic_gb);
        $min_gb = $server['refund_min_remaining_gb'];
        $min_days = $server['refund_min_remaining_days'];
        if ($remaining_volume >= $min_gb && ($min_days == 0 || $remaining_days >= $min_days)) {
            $ratio = $remaining_volume / $total_info['total_volume'];
            $refund_amount = round($total_info['total_price'] * $ratio);
        }
    }
    
    if (isset($_POST['confirm_delete']) && $_POST['confirm_delete'] == '1') {
        $deleted = false;
        if ($server['panel_type'] == 'marzban') {
            $panel = ['url' => $server['url'], 'marzban_username' => $server['marzban_username'], 'marzban_password' => $server['marzban_password']];
            $deleted = marzban_delete_service($panel, $server['username']);
        } else {
            $panel_info = ['url' => $server['url'], 'api_token' => $server['api_token'], 'inbound_id' => $server['inbound_id']];
            $deleted = delete_client($panel_info, $server['username']);
            if (!$deleted && !empty($server['uuid'])) $deleted = delete_client_by_uuid($panel_info, $server['uuid']);
        }
        
        if ($deleted) {
            if ($refund_amount > 0) {
                $pdo->prepare("UPDATE agents SET balance = balance + ? WHERE id = ?")->execute([$refund_amount, $agent['id']]);
                $pdo->prepare("INSERT INTO refund_logs (server_id, agent_id, panel_id, username, refund_amount, total_volume_gb, used_traffic_gb, remaining_gb, remaining_days, refund_reason, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'delete_service', NOW())")->execute([$server_id, $agent['id'], $server['panel_id'], $server['username'], $refund_amount, $total_info['total_volume'], $used_traffic_gb, max(0, $total_info['total_volume'] - $used_traffic_gb), $remaining_days == PHP_INT_MAX ? -1 : $remaining_days]);
                $_SESSION['message'] = "سرویس حذف شد. مبلغ " . number_format($refund_amount) . " تومان به حساب شما برگشت داده شد.";
            } else $_SESSION['message'] = "سرویس حذف شد.";
            $pdo->prepare("DELETE FROM agent_servers WHERE id = ?")->execute([$server_id]);
            header("Location: manage_services.php");
            exit;
        } else $error = "خطا در حذف سرویس از پنل";
    }
    
    if (!isset($_POST['confirm_delete']) && !$error) {
        ?>
        <!DOCTYPE html>
        <html dir="rtl" lang="fa">
        <head><meta charset="UTF-8"><title>تأیید حذف سرویس</title>
        <style>
            *{margin:0;padding:0;box-sizing:border-box;}
            body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;background:linear-gradient(135deg,#e0e7ff 0%,#f3e8ff 100%);min-height:100vh;padding:50px 20px;}
            .container{max-width:550px;margin:0 auto;}
            .confirm-box{background:white;border-radius:24px;padding:30px;box-shadow:0 20px 40px rgba(0,0,0,0.1);}
            .confirm-title{font-size:20px;margin-bottom:20px;color:#dc2626;display:flex;align-items:center;gap:8px;}
            .info-row{display:flex;justify-content:space-between;padding:10px 0;border-bottom:1px solid #e5e7eb;}
            .info-text{background:#f9fafb;border-radius:12px;padding:15px;margin:15px 0;}
            .detail-row{display:flex;justify-content:space-between;padding:5px 0;font-size:13px;}
            .detail-row.total{border-top:1px solid #e5e7eb;margin-top:5px;padding-top:8px;font-weight:700;}
            .usage-bar{margin:10px 0;}
            .usage-bar-bg{background:#e5e7eb;border-radius:10px;height:8px;overflow:hidden;}
            .usage-bar-fill{background:#7c3aed;height:100%;border-radius:10px;}
            .refund-box{background:#dcfce7;border:1px solid #bbf7d0;border-radius:12px;padding:15px;margin:15px 0;text-align:center;}
            .refund-amount{font-size:24px;font-weight:700;color:#166534;margin:10px 0;}
            .warning-box{background:#fef3c7;border:1px solid #fde68a;border-radius:12px;padding:15px;margin:15px 0;text-align:center;color:#92400e;}
            .confirm-form{margin-top:20px;}
            .button-group{display:flex;gap:15px;}
            .btn-confirm-delete{flex:1;background:#dc2626;color:white;border:none;padding:12px;border-radius:40px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;}
            .btn-cancel{flex:1;background:#f3f4f6;color:#374151;border:none;padding:12px;border-radius:40px;font-weight:600;cursor:pointer;text-align:center;text-decoration:none;display:inline-block;}
            .svg-icon{display:inline-block;vertical-align:middle;}
        </style>
        </head>
        <body>
        <div class="container"><div class="confirm-box">
            <div class="confirm-title"><svg class="svg-icon" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg> تأیید حذف سرویس</div>
            <div class="info-row"><strong>نام سرویس:</strong> <span><?= htmlspecialchars($server['username']) ?></span></div>
            <div class="info-row"><strong>پنل:</strong> <span><?= htmlspecialchars($server['panel_name'] ?? 'نامشخص') ?></span></div>
            <div class="info-text"><div class="detail-row"><strong>جزئیات هزینه‌ها:</strong></div><div class="detail-row"><span>حجم پایه:</span><span><?= number_format($total_info['base_volume']) ?> GB (<?= number_format($total_info['base_price']) ?> تومان)</span></div><?php if($total_info['extra_volume'] > 0): ?><div class="detail-row"><span>ترافیک اضافه:</span><span><?= number_format($total_info['extra_volume']) ?> GB (<?= number_format($total_info['extra_price']) ?> تومان)</span></div><?php endif; ?><div class="detail-row total"><strong>مجموع:</strong><strong><?= number_format($total_info['total_volume']) ?> GB | <?= number_format($total_info['total_price']) ?> تومان</strong></div></div>
            <?php if($client_info_success): ?>
            <div class="info-row"><strong>حجم مصرف شده:</strong> <span><?= number_format($used_traffic_gb, 2) ?> GB</span></div>
            <div class="usage-bar"><div class="usage-bar-bg"><div class="usage-bar-fill" style="width: <?= ($total_info['total_volume'] > 0) ? round(($used_traffic_gb / $total_info['total_volume']) * 100, 1) : 0 ?>%;"></div></div></div>
            <div class="info-row"><strong>حجم باقیمانده:</strong> <span><?= number_format(max(0, $total_info['total_volume'] - $used_traffic_gb), 2) ?> GB</span></div>
            <div class="info-row"><strong>روز باقیمانده:</strong> <span><?= $remaining_days == PHP_INT_MAX ? 'نامحدود' : number_format($remaining_days) . ' روز' ?></span></div>
            <?php endif; ?>
            <?php if($refund_amount > 0): ?>
            <div class="refund-box"><div class="refund-amount"><?= number_format($refund_amount) ?> تومان</div><div>مبلغ قابل بازگشت به حساب شما</div></div>
            <?php else: ?>
            <div class="warning-box">با توجه به شرایط، هیچ مبلغی قابل بازگشت نیست</div>
            <?php endif; ?>
            <form method="POST" class="confirm-form"><input type="hidden" name="action" value="delete_service"><input type="hidden" name="server_id" value="<?= $server_id ?>"><input type="hidden" name="confirm_delete" value="1"><div class="button-group"><button type="submit" class="btn-confirm-delete"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg> تأیید حذف سرویس</button><a href="manage_services.php" class="btn-cancel">انصراف</a></div></form>
        </div></div></body></html>
        <?php
        exit;
    }
}

if (isset($_GET['get_server_info'])) {
    header('Content-Type: application/json');
    $server_id = intval($_GET['get_server_info']);
    $stmt = $pdo->prepare("SELECT asv.*, p.url, p.panel_type, p.marzban_username, p.marzban_password, p.extra_traffic_enabled, p.extra_traffic_price_per_gb, p.extra_traffic_min, p.extra_traffic_max, p.refund_enabled, p.refund_min_remaining_gb, p.refund_min_remaining_days, p.renewal_enabled, p.api_token, p.inbound_id, p.custom_volume_enabled, p.custom_volume_price_per_gb, p.custom_volume_price_per_day, p.custom_volume_min_gb, p.custom_volume_max_gb, p.custom_volume_min_days, p.custom_volume_max_days FROM agent_servers asv JOIN panels p ON asv.panel_id = p.id WHERE asv.id = ? AND asv.agent_id = ?");
    $stmt->execute([$server_id, $agent['id']]);
    $server = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$server) { echo json_encode(['success' => false, 'msg' => 'سرویس یافت نشد']); exit; }
    
    $total_info = getTotalVolumeAndPrice($pdo, $server_id);
    $renew_plans = [];
    if ($server['renewal_enabled']) { $stmt = $pdo->prepare("SELECT * FROM plans WHERE panel_id = ? AND status = 1 ORDER BY price ASC"); $stmt->execute([$server['panel_id']]); $renew_plans = $stmt->fetchAll(PDO::FETCH_ASSOC); }
    
    if ($server['panel_type'] == 'marzban') {
        $panel = ['url' => $server['url'], 'marzban_username' => $server['marzban_username'], 'marzban_password' => $server['marzban_password']];
        $info = marzban_get_client_info($panel, $server['username']);
        if ($info['success']) {
            $user = $info['obj'];
            $total_gb = ($user['totalGB'] ?? 0) > 0 ? round($user['totalGB'] / 1073741824, 2) : $total_info['total_volume'];
            $used_gb = round(($user['up'] ?? 0) / 1073741824, 2);
            $remaining_gb = max(0, $total_gb - $used_gb);
            $usage_percent = $total_gb > 0 ? round(($used_gb / $total_gb) * 100, 1) : 0;
            $expiry_date = ($user['expiryTime'] ?? 0) > 0 ? date('Y-m-d H:i:s', ($user['expiryTime'] / 1000)) : 'نامحدود';
            $status_text = ($user['enable'] ?? true) ? 'فعال' : 'غیرفعال';
            $status_class = ($user['enable'] ?? true) ? 'badge-active' : 'badge-expired';
            echo json_encode(['success' => true, 'server_id' => $server['id'], 'username' => $server['username'], 'uuid' => $user['uuid'] ?? '', 'sub_link' => $server['sub_link'], 'total_gb' => $total_gb, 'used_gb' => $used_gb, 'remaining_gb' => $remaining_gb, 'usage_percent' => $usage_percent, 'expiry_date' => $expiry_date, 'status_text' => $status_text, 'status_class' => $status_class, 'enable' => $user['enable'] ?? true, 'extra_traffic_enabled' => (bool)$server['extra_traffic_enabled'], 'extra_traffic_price_per_gb' => $server['extra_traffic_price_per_gb'], 'extra_traffic_min' => $server['extra_traffic_min'], 'extra_traffic_max' => $server['extra_traffic_max'], 'renewal_enabled' => (bool)$server['renewal_enabled'], 'renew_plans' => $renew_plans, 'base_volume' => $total_info['base_volume'], 'extra_volume' => $total_info['extra_volume'], 'custom_volume_enabled' => (bool)$server['custom_volume_enabled'], 'custom_volume_price_per_gb' => $server['custom_volume_price_per_gb'], 'custom_volume_price_per_day' => $server['custom_volume_price_per_day'], 'custom_volume_min_gb' => $server['custom_volume_min_gb'], 'custom_volume_max_gb' => $server['custom_volume_max_gb'], 'custom_volume_min_days' => $server['custom_volume_min_days'], 'custom_volume_max_days' => $server['custom_volume_max_days']]);
        } else echo json_encode(['success' => false, 'msg' => $info['msg']]);
    } else {
        $panel = ['url' => $server['url'], 'api_token' => $server['api_token']];
        try {
            $info = get_client_info_by_uuid($panel, $server['uuid']);
            if ($info && isset($info['success']) && $info['success'] === true) {
                $user = $info['obj'];
                $total_bytes = $user['totalGB'] ?? $user['total'] ?? 0;
                $total_gb = $total_bytes > 0 ? round($total_bytes / 1073741824, 2) : $total_info['total_volume'];
                $used_bytes = ($user['up'] ?? 0) + ($user['down'] ?? 0);
                $used_gb = round($used_bytes / 1073741824, 2);
                $remaining_gb = max(0, $total_gb - $used_gb);
                $usage_percent = $total_gb > 0 ? round(($used_gb / $total_gb) * 100, 1) : 0;
                $expiry_time = ($user['expiryTime'] ?? 0) / 1000;
                $expiry_date = $expiry_time > 0 ? date('Y-m-d H:i:s', $expiry_time) : 'نامحدود';
                $status_text = ($user['enable'] ?? true) ? 'فعال' : 'غیرفعال';
                $status_class = ($user['enable'] ?? true) ? 'badge-active' : 'badge-expired';
                echo json_encode(['success' => true, 'server_id' => $server['id'], 'username' => $server['username'], 'uuid' => $server['uuid'], 'sub_link' => $server['sub_link'], 'total_gb' => $total_gb, 'used_gb' => $used_gb, 'remaining_gb' => $remaining_gb, 'usage_percent' => $usage_percent, 'expiry_date' => $expiry_date, 'status_text' => $status_text, 'status_class' => $status_class, 'enable' => $user['enable'] ?? true, 'extra_traffic_enabled' => (bool)$server['extra_traffic_enabled'], 'extra_traffic_price_per_gb' => $server['extra_traffic_price_per_gb'], 'extra_traffic_min' => $server['extra_traffic_min'], 'extra_traffic_max' => $server['extra_traffic_max'], 'renewal_enabled' => (bool)$server['renewal_enabled'], 'renew_plans' => $renew_plans, 'base_volume' => $total_info['base_volume'], 'extra_volume' => $total_info['extra_volume'], 'custom_volume_enabled' => (bool)$server['custom_volume_enabled'], 'custom_volume_price_per_gb' => $server['custom_volume_price_per_gb'], 'custom_volume_price_per_day' => $server['custom_volume_price_per_day'], 'custom_volume_min_gb' => $server['custom_volume_min_gb'], 'custom_volume_max_gb' => $server['custom_volume_max_gb'], 'custom_volume_min_days' => $server['custom_volume_min_days'], 'custom_volume_max_days' => $server['custom_volume_max_days']]);
            } else echo json_encode(['success' => false, 'msg' => 'خطا در دریافت اطلاعات از پنل']);
        } catch (Exception $e) { echo json_encode(['success' => false, 'msg' => 'خطا: ' . $e->getMessage()]); }
    }
    exit;
}

$servers = getAgentServers($pdo, $agent['id']);
?>
<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مدیریت سرویس‌ها | رهگذر</title>
    <style>
        *{margin:0;padding:0;box-sizing:border-box;}
        body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;background:linear-gradient(135deg,#e0e7ff 0%,#f3e8ff 100%);min-height:100vh;padding:24px;}
        .container{max-width:1400px;margin:0 auto;}
        .admin-header{background:rgba(255,255,255,0.9);backdrop-filter:blur(12px);border-radius:16px;padding:15px 25px;margin-bottom:25px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;}
        .brand-name{font-size:18px;font-weight:700;color:#1f2937;display:flex;align-items:center;gap:8px;}
        .admin-info{display:flex;gap:15px;align-items:center;flex-wrap:wrap;}
        .admin-info a,.admin-info span{color:#6b7280;text-decoration:none;font-size:14px;display:flex;align-items:center;gap:5px;}
        .my-services-btn{background:#8b5cf6;color:white!important;padding:6px 15px;border-radius:20px;}
        .alert{padding:15px 20px;border-radius:12px;margin-bottom:20px;display:flex;align-items:center;gap:10px;}
        .alert-success{background:#dcfce7;color:#166534;border:1px solid #bbf7d0;}
        .alert-error{background:#fee2e2;color:#991b1b;border:1px solid #fecaca;}
        .content-card{background:rgba(255,255,255,0.95);backdrop-filter:blur(12px);border-radius:24px;padding:25px;box-shadow:0 4px 20px rgba(0,0,0,0.08);}
        .section-header{margin-bottom:20px;}
        .section-header h3{color:#1f2937;display:flex;align-items:center;gap:8px;}
        .table-wrapper{overflow-x:auto;}
        .data-table{width:100%;border-collapse:collapse;}
        .data-table th{padding:12px;text-align:center;background:rgba(0,0,0,0.03);border-bottom:1px solid #e5e7eb;color:#6b7280;font-weight:600;}
        .data-table td{padding:12px;text-align:center;border-bottom:1px solid #e5e7eb;color:#374151;}
        .badge-active{background:#dcfce7;color:#166534;padding:4px 10px;border-radius:20px;font-size:12px;display:inline-block;}
        .badge-expired{background:#fee2e2;color:#991b1b;padding:4px 10px;border-radius:20px;font-size:12px;display:inline-block;}
        .volume-detail{font-size:10px;color:#8b5cf6;margin-top:3px;}
        .edit-btn,.delete-btn,.extra-traffic-btn{padding:5px 12px;margin:0 3px;border:none;border-radius:8px;cursor:pointer;font-size:12px;transition:all 0.2s;display:inline-flex;align-items:center;gap:4px;}
        .edit-btn{background:#e0e7ff;color:#4338ca;}
        .delete-btn{background:#fee2e2;color:#dc2626;}
        .extra-traffic-btn{background:#fef3c7;color:#d97706;}
        .modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);backdrop-filter:blur(8px);z-index:1000;justify-content:center;align-items:center;}
        .modal-content{background:white;border-radius:24px;max-width:750px;width:90%;max-height:85vh;overflow-y:auto;}
        .modal-small{max-width:450px;}
        .modal-header{display:flex;justify-content:space-between;align-items:center;padding:20px;border-bottom:1px solid #e5e7eb;}
        .close-modal{background:none;border:none;font-size:24px;cursor:pointer;color:#6b7280;}
        .modal-body-loading{padding:30px;text-align:center;}
        .loading-spinner{padding:40px;text-align:center;color:#8b5cf6;}
        .service-detail-card{padding:20px;}
        .service-detail-section{margin-bottom:25px;border-bottom:1px solid #e5e7eb;padding-bottom:15px;}
        .service-detail-title{font-weight:700;margin-bottom:15px;color:#374151;display:flex;align-items:center;gap:8px;}
        .service-info-row{display:flex;justify-content:space-between;padding:8px 0;font-size:14px;}
        .renew-plans-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px;margin-top:10px;}
        .renew-plan-card{background:#f9fafb;border:1px solid #e5e7eb;border-radius:12px;padding:12px;cursor:pointer;transition:all 0.2s;text-align:center;}
        .renew-plan-card:hover{background:#f5f3ff;border-color:#8b5cf6;}
        .renew-plan-card strong{color:#1f2937;}
        .plan-price{color:#7c3aed;font-weight:700;margin-top:5px;display:block;}
        .custom-renew-section{background:#fef3c7;border-radius:12px;padding:16px;margin-top:16px;border:1px solid #fde68a;}
        .custom-renew-title{font-weight:700;color:#92400e;margin-bottom:12px;display:flex;align-items:center;gap:8px;}
        .custom-renew-inputs{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px;}
        .custom-renew-inputs input{width:100%;padding:10px;border:1px solid #fde68a;border-radius:8px;background:white;}
        .custom-renew-info{font-size:12px;color:#78350f;margin-top:8px;background:#fffbeb;padding:8px;border-radius:8px;}
        .btn-custom-renew{background:#f59e0b;width:100%;margin-top:12px;padding:10px;border:none;border-radius:40px;color:white;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;}
        .usage-bar{margin:10px 0;}
        .usage-bar-bg{background:#e5e7eb;border-radius:10px;height:8px;overflow:hidden;}
        .usage-bar-fill{background:#7c3aed;height:100%;border-radius:10px;}
        .modal-action-buttons{display:flex;gap:10px;padding:15px 20px;border-top:1px solid #e5e7eb;}
        .btn-modal-update{flex:1;background:#8b5cf6;color:white;border:none;padding:10px;border-radius:40px;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:6px;}
        .btn-modal-danger{flex:1;background:#dc2626;color:white;border:none;padding:10px;border-radius:40px;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:6px;}
        .invoice-preview{background:#f0fdf4;border-radius:12px;padding:15px;margin:15px 0;text-align:center;border:1px solid #bbf7d0;}
        .form-group{margin-bottom:20px;}
        .form-group label{display:block;margin-bottom:8px;font-weight:600;color:#374151;display:flex;align-items:center;gap:8px;}
        .form-group input{width:100%;padding:12px;border:2px solid #e5e7eb;border-radius:12px;font-size:14px;}
        .form-actions{display:flex;gap:12px;margin-top:20px;}
        .btn-submit{flex:1;background:#7c3aed;color:white;border:none;padding:12px;border-radius:40px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;}
        .btn-cancel{background:#f3f4f6;border:none;padding:12px 20px;border-radius:40px;font-weight:600;cursor:pointer;display:flex;align-items:center;gap:8px;}
        .info-text{font-size:11px;color:#6b7280;margin-top:5px;}
        .svg-icon{display:inline-block;vertical-align:middle;}
        @media (max-width:768px){.admin-info{gap:8px;}.data-table th,.data-table td{padding:8px;font-size:12px;}}
    </style>
</head>
<body>
<div class="container">
    <div class="admin-header">
        <div class="brand"><span class="brand-name"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg> مدیریت سرویس‌ها</span></div>
        <div class="admin-info"><span><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg> خوش آمدید، <strong><?= displayText($agent['name']) ?></strong></span><span><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg> موجودی: <?= number_format($agent['balance']) ?> تومان</span><a href="services.php" class="my-services-btn"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg> ساخت سرویس</a><a href="../agent.php"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"/></svg> بازگشت</a></div>
    </div>

    <?php if(isset($_SESSION['message'])): ?>
    <div class="alert alert-success"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> <?= displayText($_SESSION['message']) ?></div>
    <?php unset($_SESSION['message']); endif; ?>
    <?php if($error): ?>
    <div class="alert alert-error"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg> <?= displayText($error) ?></div>
    <?php endif; ?>

    <div class="content-card">
        <div class="section-header"><h3><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg> لیست سرویس‌های من</h3></div>
        
        <div class="table-wrapper">
            <table class="data-table">
                <thead><tr><th>شناسه</th><th>پنل</th><th>پلن</th><th>نام کاربری</th><th>حجم</th><th>قیمت</th><th>انقضا</th><th>وضعیت</th><th>عملیات</th></tr></thead>
                <tbody>
                    <?php foreach($servers as $server):
                        $is_expired = $server['expiry_date'] && strtotime($server['expiry_date']) < time();
                        $status = $is_expired ? 'منقضی' : ($server['status'] == 1 ? 'فعال' : 'غیرفعال');
                        $status_class = $is_expired ? 'badge-expired' : 'badge-active';
                        $total_info = getTotalVolumeAndPrice($pdo, $server['id']);
                        $vol_display = ($total_info['total_volume'] == 0) ? 'نامحدود' : number_format($total_info['total_volume']) . ' GB';
                        $price_display = number_format($total_info['total_price']) . ' تومان';
                        $plan_display = ($server['plan_id'] == 0) ? 'حجم دلخواه' : ($server['plan_name'] ?? '-');
                        $extra_text = ($total_info['extra_volume'] > 0) ? '<div class="volume-detail">+ ' . number_format($total_info['extra_volume']) . ' GB اضافه</div>' : '';
                    ?>
                    <tr><td><?= $server['id'] ?></td><td><?= displayText($server['panel_name'] ?? '-') ?></td><td><?= displayText($plan_display) ?></td><td><?= displayText($server['username']) ?></td><td><?= $vol_display . $extra_text ?></td><td><?= $price_display ?></td><td><?= $server['expiry_date'] ? date('Y-m-d', strtotime($server['expiry_date'])) : 'نامحدود' ?></td><td><span class="<?= $status_class ?>"><?= $status ?></span></td>
                    <td><button class="edit-btn" onclick="manageService(<?= $server['id'] ?>)"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg> مدیریت</button>
                    <button class="delete-btn" onclick="deleteServiceDirect(<?= $server['id'] ?>)"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg> حذف</button>
                    <?php if($server['extra_traffic_enabled'] && !$is_expired && $server['status'] == 1): ?>
                    <button class="extra-traffic-btn" onclick="openExtraTrafficModal(<?= $server['id'] ?>, '<?= addslashes($server['username']) ?>', <?= $server['extra_traffic_min'] ?>, <?= $server['extra_traffic_max'] ?>, <?= $server['extra_traffic_price_per_gb'] ?>)"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg> ترافیک</button>
                    <?php endif; ?></td></tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div id="serviceModal" class="modal"><div class="modal-content"><div class="modal-header"><h3><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg> مدیریت سرویس</h3><button class="close-modal" onclick="closeModal('serviceModal')">✕</button></div><div id="serviceModalContent" class="modal-body-loading">در حال بارگذاری...</div><div class="modal-action-buttons"><button onclick="updateServiceInfoFromModal()" class="btn-modal-update"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg> بروزرسانی</button><button onclick="deleteServiceFromModal()" class="btn-modal-danger"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg> حذف سرویس</button></div></div></div>

<div id="extraTrafficModal" class="modal"><div class="modal-content modal-small"><div class="modal-header"><h3><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg> خرید ترافیک اضافه</h3><button class="close-modal" onclick="closeModal('extraTrafficModal')">✕</button></div><form method="POST"><input type="hidden" name="action" value="buy_extra_traffic"><input type="hidden" name="server_id" id="extra_server_id"><div class="form-group"><label>نام کاربری</label><input type="text" id="extra_username" disabled></div><div class="form-group"><label>میزان ترافیک (GB)</label><input type="number" name="extra_gb" id="extra_gb" step="1" required><div id="extra_range_text" class="info-text"></div></div><div class="form-group"><label>قیمت هر گیگابایت</label><input type="text" id="extra_price_per_gb" disabled></div><div id="invoice_preview" class="invoice-preview" style="display:none;"><strong>مبلغ قابل پرداخت: <span id="invoice_total_price">0</span></strong></div><div class="form-actions"><button type="submit" id="submit_extra_traffic_btn" disabled class="btn-submit">تایید و خرید</button><button type="button" onclick="closeModal('extraTrafficModal')" class="btn-cancel">انصراف</button></div></form></div></div>

<script>
const discount = <?= $agent['discount'] ?>;
let currentExtraMin = 0, currentExtraMax = 0, currentExtraPrice = 0;
let currentServerId = null;

function closeModal(modalId) { document.getElementById(modalId).style.display = 'none'; }

function manageService(serverId) {
    currentServerId = serverId;
    const modal = document.getElementById('serviceModal');
    const content = document.getElementById('serviceModalContent');
    modal.style.display = 'flex';
    content.innerHTML = '<div class="loading-spinner">در حال بارگذاری...</div>';
    
    fetch(`?get_server_info=${serverId}`).then(r=>r.json()).then(data=>{
        if(!data.success){ content.innerHTML=`<div class="alert alert-error">${data.msg}</div>`; return; }

        let plansHtml = '';
        if(data.renewal_enabled && data.renew_plans && data.renew_plans.length>0){
            plansHtml = `<div class="service-detail-section"><div class="service-detail-title"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/><path d="M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/></svg> تمدید با پلن آماده</div><div class="renew-plans-grid">`;
            for(let plan of data.renew_plans){
                let vol = plan.volume_gb==0?'نامحدود':plan.volume_gb+' GB';
                let days = plan.days==0?'نامحدود':plan.days+' روز';
                let finalPrice = discount>0?Math.round(plan.price-(plan.price*discount/100)):plan.price;
                plansHtml += `<div class="renew-plan-card" onclick="renewService(${serverId}, ${plan.id}, ${plan.volume_gb}, ${plan.days}, ${finalPrice}, '${plan.name}', 'plan')"><strong>${plan.name}</strong><br><small>${vol} | ${days}</small><br><span class="plan-price">${finalPrice.toLocaleString()} تومان</span></div>`;
            }
            plansHtml += '</div></div>';
        }
        
        let customRenewHtml = '';
        if(data.custom_volume_enabled && data.renewal_enabled){
            customRenewHtml = `<div class="service-detail-section custom-renew-section"><div class="custom-renew-title"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#92400e" stroke-width="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><path d="M14 2v6h6"/></svg> تمدید با حجم دلخواه</div><div class="custom-renew-inputs"><input type="number" id="renew_volume" placeholder="حجم (GB)" min="${data.custom_volume_min_gb}" max="${data.custom_volume_max_gb}"><input type="number" id="renew_days" placeholder="مدت (روز)" min="${data.custom_volume_min_days}" max="${data.custom_volume_max_days}"></div><div class="custom-renew-info">محدوده حجم: ${data.custom_volume_min_gb} تا ${data.custom_volume_max_gb} GB | محدوده تایم: ${data.custom_volume_min_days} تا ${data.custom_volume_max_days} روز<br>قیمت هر GB: ${data.custom_volume_price_per_gb.toLocaleString()} تومان | قیمت هر روز: ${data.custom_volume_price_per_day.toLocaleString()} تومان</div><button class="btn-custom-renew" onclick="calculateCustomRenew(${serverId}, ${data.custom_volume_price_per_gb}, ${data.custom_volume_price_per_day})"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg> محاسبه و تمدید</button></div>`;
        }

        let extraInfo = (data.extra_volume && data.extra_volume > 0) ? `<div class="service-info-row"><span>ترافیک اضافه خریداری شده:</span><span>${data.extra_volume} GB</span></div>` : '';

        content.innerHTML = `<div class="service-detail-card"><div class="service-detail-section"><div class="service-detail-title"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg> اطلاعات کاربر</div><div class="service-info-row"><span>نام کاربری:</span><span><strong>${data.username}</strong></span></div><div class="service-info-row"><span>UUID:</span><span><code>${data.uuid}</code></span></div><div class="service-info-row"><span>لینک ساب:</span><span><a href="${data.sub_link}" target="_blank">${data.sub_link}</a></span></div></div><div class="service-detail-section"><div class="service-detail-title"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg> اطلاعات مصرف</div><div class="service-info-row"><span>حجم پایه:</span><span>${data.base_volume} GB</span></div>${extraInfo}<div class="service-info-row"><span>حجم کل:</span><span>${data.total_gb} GB</span></div><div class="service-info-row"><span>مصرف شده:</span><span>${data.used_gb} GB (${data.usage_percent}%)</span></div><div class="usage-bar"><div class="usage-bar-bg"><div class="usage-bar-fill" style="width:${data.usage_percent}%"></div></div></div><div class="service-info-row"><span>باقیمانده:</span><span>${data.remaining_gb} GB</span></div><div class="service-info-row"><span><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg> انقضا:</span><span>${data.expiry_date}</span></div><div class="service-info-row"><span>وضعیت:</span><span class="${data.status_class}">${data.status_text}</span></div></div>${plansHtml}${customRenewHtml}</div>`;
    }).catch(err=>{ content.innerHTML=`<div class="alert alert-error">خطا: ${err.message}</div>`; });
}

function calculateCustomRenew(serverId, pricePerGb, pricePerDay){
    const volume = parseFloat(document.getElementById('renew_volume').value);
    const days = parseInt(document.getElementById('renew_days').value);
    if(!volume || !days || volume <=0 || days <=0){ alert('لطفاً حجم و تایم را وارد کنید'); return; }
    let totalPrice = (volume * pricePerGb) + (days * pricePerDay);
    if(discount > 0) totalPrice = Math.round(totalPrice - (totalPrice * discount / 100));
    if(confirm(`آیا از تمدید سرویس با مشخصات زیر اطمینان دارید؟\nحجم: ${volume} GB\nمدت: ${days} روز\nمبلغ: ${totalPrice.toLocaleString()} تومان`)){
        renewService(serverId, 0, volume, days, totalPrice, 'حجم دلخواه', 'custom', volume, days);
    }
}

function renewService(serverId, planId, volumeGb, days, price, planName, renewType, customVolume=0, customDays=0){
    const content = document.getElementById('serviceModalContent');
    let volText = volumeGb==0?'نامحدود':volumeGb+' GB';
    let daysText = days==0?'نامحدود':days+' روز';
    let customFields = (renewType == 'custom') ? `<input type="hidden" name="volume_gb" value="${customVolume}"><input type="hidden" name="days" value="${customDays}">` : '';
    content.innerHTML = `<div class="service-detail-card"><h3>تأیید تمدید</h3><div class="warning-box" style="background:#fef3c7;border:1px solid #fde68a;border-radius:12px;padding:15px;margin:15px 0;color:#92400e;"><strong>توجه مهم:</strong><br><ul style="margin:10px 0 0 20px;"><li>حجم مصرفی فعلی شما صفر می‌شود</li><li>حجم کل به ${volText} تغییر می‌کند</li><li>تاریخ انقضا از امروز محاسبه می‌شود</li><li><strong>تمام ترافیک‌های اضافه قبلی حذف می‌شوند</strong></li></ul></div><div class="service-info-row"><span>نوع تمدید:</span><span>${planName}</span></div><div class="service-info-row"><span>حجم جدید:</span><span>${volText}</span></div><div class="service-info-row"><span>مدت جدید:</span><span>${daysText}</span></div><div class="service-info-row total" style="border-top:2px solid #e5e7eb;margin-top:10px;padding-top:15px;font-weight:700;color:#7c3aed;"><span>مبلغ:</span><span class="price">${price.toLocaleString()} تومان</span></div><form method="POST" class="renew-form"><input type="hidden" name="action" value="renew_service"><input type="hidden" name="server_id" value="${serverId}"><input type="hidden" name="plan_id" value="${planId}"><input type="hidden" name="renew_type" value="${renewType}">${customFields}<input type="hidden" name="confirm_renew" value="1"><div style="display:flex;gap:12px;margin-top:20px;"><button type="submit" class="btn-submit" style="flex:1;">تأیید تمدید</button><button type="button" class="btn-cancel" onclick="manageService(${serverId})">انصراف</button></div></form></div>`;
}

function updateServiceInfoFromModal(){ if(currentServerId) manageService(currentServerId); }
function deleteServiceFromModal(){ if(currentServerId && confirm('آیا از حذف این سرویس اطمینان دارید؟')) deleteServiceDirect(currentServerId); }
function deleteServiceDirect(serverId){ if(confirm('آیا از حذف این سرویس اطمینان دارید؟')){ const form=document.createElement('form'); form.method='POST'; form.innerHTML=`<input type="hidden" name="action" value="delete_service"><input type="hidden" name="server_id" value="${serverId}">`; document.body.appendChild(form); form.submit(); } }

function openExtraTrafficModal(serverId, username, minGb, maxGb, pricePerGb){
    currentExtraMin=minGb; currentExtraMax=maxGb; currentExtraPrice=pricePerGb;
    document.getElementById('extra_server_id').value=serverId;
    document.getElementById('extra_username').value=username;
    document.getElementById('extra_price_per_gb').value=pricePerGb.toLocaleString()+' تومان';
    document.getElementById('extra_range_text').innerHTML=`حداقل: ${minGb} GB | حداکثر: ${maxGb} GB`;
    document.getElementById('extra_gb').value='';
    document.getElementById('invoice_preview').style.display='none';
    document.getElementById('submit_extra_traffic_btn').disabled=true;
    document.getElementById('extraTrafficModal').style.display='flex';
}

function calculatePrice(){
    let gb=parseFloat(document.getElementById('extra_gb').value);
    if(isNaN(gb) || gb<currentExtraMin || gb>currentExtraMax){ document.getElementById('invoice_preview').style.display='none'; document.getElementById('submit_extra_traffic_btn').disabled=true; return; }
    let basePrice=gb*currentExtraPrice;
    let finalPrice=discount>0?Math.round(basePrice-(basePrice*discount/100)):basePrice;
    document.getElementById('invoice_total_price').innerHTML=finalPrice.toLocaleString()+' تومان';
    document.getElementById('invoice_preview').style.display='block';
    document.getElementById('submit_extra_traffic_btn').disabled=false;
}
document.getElementById('extra_gb')?.addEventListener('input',calculatePrice);
window.addEventListener('click',function(e){ if(e.target===document.getElementById('serviceModal')) closeModal('serviceModal'); if(e.target===document.getElementById('extraTrafficModal')) closeModal('extraTrafficModal'); });
</script>
</body>
</html>