<?php
// شروع session قبل از هر چیز
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../config.php';

// بررسی لاگین
if (!isLoggedIn()) {
    redirect('../login.php');
}

// بررسی دسترسی ادمین
if (!isAdmin()) {
    setMessage('دسترسی غیرمجاز', 'error');
    redirect('../login.php');
}

$rep_id = (int)($_GET['id'] ?? 0);

if ($rep_id === 0) {
    setMessage('نماینده انتخاب نشده', 'error');
    redirect('representatives.php');
}

// دریافت اطلاعات نماینده
$rep = $pdo->prepare("SELECT r.*, p.name as panel_name, p.url as panel_url, p.username as panel_username, p.password as panel_password FROM representatives r JOIN panels p ON r.panel_id = p.id WHERE r.id = ?");
$rep->execute([$rep_id]);
$rep = $rep->fetch();

if (!$rep) {
    setMessage('نماینده یافت نشد', 'error');
    redirect('representatives.php');
}

$page_title = 'مدیریت Inbound های نماینده: ' . htmlspecialchars($rep['username']);

// دریافت inbound های مجاز
$allowed_inbounds = $pdo->prepare("SELECT * FROM representative_inbounds WHERE representative_id = ?");
$allowed_inbounds->execute([$rep_id]);
$allowed_inbounds = $allowed_inbounds->fetchAll();

// دریافت لیست inbound های پنل
require_once __DIR__ . '/../api/XrayAPI.php';
try {
    // دریافت اطلاعات کامل پنل برای proxy
    $panel_full = $pdo->prepare("SELECT * FROM panels WHERE id = ?");
    $panel_full->execute([$rep['panel_id']]);
    $panel_full = $panel_full->fetch();
    
    // آماده‌سازی تنظیمات proxy
    $proxy_config = null;
    if ($panel_full && !empty($panel_full['proxy_host'])) {
        $proxy_config = [
            'type' => $panel_full['proxy_type'] ?? 'socks5',
            'host' => $panel_full['proxy_host'],
            'port' => $panel_full['proxy_port'] ?? 1080,
            'username' => $panel_full['proxy_username'] ?? null,
            'password' => $panel_full['proxy_password'] ?? null,
            'use_on_error' => !empty($panel_full['use_proxy'])
        ];
    }
    
    $xrayAPI = new XrayAPI($rep['panel_url'], $rep['panel_username'], $rep['panel_password'], $proxy_config);
    $inbounds_result = $xrayAPI->getInbounds();
    $all_inbounds = $inbounds_result['obj'] ?? [];
} catch (Exception $e) {
    $all_inbounds = [];
    setMessage('خطا در اتصال به پنل: ' . $e->getMessage(), 'error');
}

// افزودن/حذف inbound
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $inbound_id = (int)($_POST['inbound_id'] ?? 0);
        $inbound_name = $_POST['inbound_name'] ?? '';
        
        if ($inbound_id > 0) {
            try {
                // پیدا کردن نام inbound
                foreach ($all_inbounds as $inb) {
                    if ($inb['id'] == $inbound_id) {
                        $inbound_name = $inb['remark'] ?? 'Inbound #' . $inbound_id;
                        break;
                    }
                }
                
                $stmt = $pdo->prepare("INSERT INTO representative_inbounds (representative_id, inbound_id, inbound_name) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE status = 'active'");
                $stmt->execute([$rep_id, $inbound_id, $inbound_name]);
                setMessage('Inbound با موفقیت افزوده شد');
                redirect('representative_inbounds.php?id=' . $rep_id);
            } catch (Exception $e) {
                setMessage('خطا: ' . $e->getMessage(), 'error');
            }
        }
    } elseif ($action === 'remove') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            $stmt = $pdo->prepare("DELETE FROM representative_inbounds WHERE id = ?");
            $stmt->execute([$id]);
            setMessage('Inbound با موفقیت حذف شد');
            redirect('representative_inbounds.php?id=' . $rep_id);
        }
    } elseif ($action === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            $stmt = $pdo->prepare("UPDATE representative_inbounds SET status = IF(status = 'active', 'inactive', 'active') WHERE id = ?");
            $stmt->execute([$id]);
            setMessage('وضعیت تغییر کرد');
            redirect('representative_inbounds.php?id=' . $rep_id);
        }
    }
}

// دریافت مجدد لیست
$allowed_inbounds = $pdo->prepare("SELECT * FROM representative_inbounds WHERE representative_id = ? ORDER BY inbound_id");
$allowed_inbounds->execute([$rep_id]);
$allowed_inbounds = $allowed_inbounds->fetchAll();

$allowed_ids = array_column($allowed_inbounds, 'inbound_id');

require_once '../includes/header.php';
?>

<div class="card mb-3">
    <div class="card-header">
        <h5 class="mb-0">اطلاعات نماینده</h5>
    </div>
    <div class="card-body">
        <p><strong>نام کاربری:</strong> <?= htmlspecialchars($rep['username']) ?></p>
        <p><strong>پنل:</strong> <?= htmlspecialchars($rep['panel_name']) ?></p>
    </div>
</div>

<div class="card mb-3">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Inbound های مجاز</h5>
        <button type="button" class="btn btn-light btn-sm" data-bs-toggle="modal" data-bs-target="#addInboundModal">
            <i class="bi bi-plus-circle"></i> افزودن Inbound
        </button>
    </div>
    <div class="card-body">
        <?php if (empty($allowed_inbounds)): ?>
            <div class="alert alert-info">هیچ inbound مجازی تعریف نشده است. نماینده می‌تواند از همه inbound ها استفاده کند.</div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>نام</th>
                            <th>وضعیت</th>
                            <th>عملیات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($allowed_inbounds as $ai): ?>
                            <?php
                            $inbound_info = null;
                            foreach ($all_inbounds as $inb) {
                                if ($inb['id'] == $ai['inbound_id']) {
                                    $inbound_info = $inb;
                                    break;
                                }
                            }
                            ?>
                            <tr>
                                <td><?= $ai['inbound_id'] ?></td>
                                <td>
                                    <?= htmlspecialchars($ai['inbound_name'] ?? '-') ?>
                                    <?php if ($inbound_info): ?>
                                        <br><small class="text-muted">
                                            <?= htmlspecialchars($inbound_info['protocol']) ?> - Port: <?= $inbound_info['port'] ?>
                                        </small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge bg-<?= $ai['status'] === 'active' ? 'success' : 'danger' ?>">
                                        <?= $ai['status'] === 'active' ? 'فعال' : 'غیرفعال' ?>
                                    </span>
                                </td>
                                <td>
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="action" value="toggle">
                                        <input type="hidden" name="id" value="<?= $ai['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-warning">
                                            <i class="bi bi-toggle-<?= $ai['status'] === 'active' ? 'on' : 'off' ?>"></i>
                                        </button>
                                    </form>
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('آیا مطمئن هستید؟')">
                                        <input type="hidden" name="action" value="remove">
                                        <input type="hidden" name="id" value="<?= $ai['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-danger">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Modal افزودن Inbound -->
<div class="modal fade" id="addInboundModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">افزودن Inbound مجاز</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label class="form-label">Inbound <span class="text-danger">*</span></label>
                        <select name="inbound_id" class="form-select" required>
                            <option value="">انتخاب کنید</option>
                            <?php foreach ($all_inbounds as $inbound): ?>
                                <?php if (!in_array($inbound['id'], $allowed_ids)): ?>
                                    <option value="<?= $inbound['id'] ?>">
                                        <?= htmlspecialchars($inbound['remark'] ?? 'Inbound #' . $inbound['id']) ?> 
                                        (<?= htmlspecialchars($inbound['protocol']) ?>) - Port: <?= $inbound['port'] ?>
                                    </option>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                    <button type="submit" class="btn btn-primary">افزودن</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="mt-3">
    <a href="representatives.php" class="btn btn-secondary">بازگشت</a>
</div>

<?php require_once '../includes/footer.php'; ?>
