<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once '../config.php';

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

$rep_id = (int)($_GET['id'] ?? 0);
if ($rep_id <= 0) {
    setMessage('شناسه نماینده نامعتبر است.', 'error');
    redirect('representatives.php');
}

// Fetch representative data
$stmt = $pdo->prepare("SELECT * FROM representatives WHERE id = ?");
$stmt->execute([$rep_id]);
$rep = $stmt->fetch();

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $full_name = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');

    if (empty($username)) {
        setMessage('نام کاربری الزامی است.', 'error');
    } elseif (empty($_POST['inbound_ids']) || !is_array($_POST['inbound_ids'])) {
        setMessage('حداقل یک اینباند باید برای نماینده انتخاب شود.', 'error');
    } else {
        // Check if username is taken by another representative
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM representatives WHERE username = ? AND id != ?");
        $stmt->execute([$username, $rep_id]);
        if ($stmt->fetchColumn() > 0) {
            setMessage('این نام کاربری قبلاً توسط نماینده دیگری استفاده شده است.', 'error');
        } else {
            try {
                $pdo->beginTransaction();

                $params = [
                    $username, $full_name, $email, $phone,
                    (float)($_POST['price_per_gb'] ?? 0),
                    (float)($_POST['price_per_day'] ?? 0),
                    max(0, min(100, (int)($_POST['discount_percent'] ?? 0))),
                    (int)($_POST['default_traffic_limit'] ?? 5),
                    (int)($_POST['default_expiry_days'] ?? 30),
                    (int)($_POST['default_ip_limit'] ?? 0),
                    isset($_POST['can_create_test_config']) ? 1 : 0,
                    (int)($_POST['test_config_traffic_limit'] ?? 1),
                    (int)($_POST['test_config_expiry_hours'] ?? 3),
                    isset($_POST['can_import_from_panel']) ? 1 : 0,
                ];

                $sql = "UPDATE representatives SET username = ?, full_name = ?, email = ?, phone = ?, price_per_gb = ?, price_per_day = ?, discount_percent = ?, default_traffic_limit = ?, default_expiry_days = ?, default_ip_limit = ?, can_create_test_config = ?, test_config_traffic_limit = ?, test_config_expiry_hours = ?, can_import_from_panel = ?";
                
                if (!empty($password)) {
                    $sql .= ", password = ?";
                    $params[] = hashPassword($password);
                }

                $sql .= " WHERE id = ?";
                $params[] = $rep_id;

                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);

                // Update inbounds
                $pdo->prepare("DELETE FROM representative_inbounds WHERE representative_id = ?")->execute([$rep_id]);
                $inbound_stmt = $pdo->prepare("INSERT INTO representative_inbounds (representative_id, panel_id, inbound_id) VALUES (?, ?, ?)");
                foreach ($_POST['inbound_ids'] as $pair) {
                    list($panel_id, $inbound_id) = explode('_', $pair);
                    if ((int)$panel_id > 0 && (int)$inbound_id > 0) {
                        $inbound_stmt->execute([$rep_id, (int)$panel_id, (int)$inbound_id]);
                    }
                }

                $pdo->commit();
                setMessage('نماینده با موفقیت ویرایش شد.', 'success');
                redirect('representatives.php');
            } catch (Exception $e) {
                $pdo->rollBack();
                setMessage('خطا در ویرایش نماینده: ' . $e->getMessage(), 'error');
            }
        }
    }
    // Preserve form data on error
    $form_data = $_POST;
} else {
    // Load existing data into form_data
    $form_data = $rep;
}

$panels = $pdo->query("SELECT id, name FROM panels WHERE status = 'active' ORDER BY name")->fetchAll();
$rep_inbounds_stmt = $pdo->prepare("SELECT panel_id, inbound_id FROM representative_inbounds WHERE representative_id = ?");
$rep_inbounds_stmt->execute([$rep_id]);
$rep_inbounds = $rep_inbounds_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$rep_inbounds_map = [];
foreach($rep_inbounds_stmt->fetchAll() as $row) {
    $rep_inbounds_map[$row['panel_id'] . '_' . $row['inbound_id']] = true;
}


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

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0 text-gray-800"><?= $page_title ?></h1>
    <a href="representatives.php" class="btn btn-secondary btn-sm"><i class="bi bi-arrow-left me-1"></i> بازگشت به لیست نمایندگان</a>
</div>

<?php 
$message_data = getMessage();
if ($message_data): 
?>
    <div class="alert alert-<?= $message_data['type'] ?> alert-dismissible fade show" role="alert">
        <?= htmlspecialchars($message_data['message']) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="card admin-main-card mb-4">
    <div class="card-header">
        <h3 class="card-title mb-0"><?= htmlspecialchars($page_title) ?></h3>
    </div>
    <div class="card-body">
        <form method="POST" action="representative_edit.php?id=<?= $rep_id ?>">
            <ul class="nav nav-tabs" id="editRepTabs" role="tablist">
                <li class="nav-item" role="presentation"><button class="nav-link active" id="main-info-tab" data-bs-toggle="tab" data-bs-target="#main-info" type="button" role="tab">اطلاعات اصلی</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" id="inbounds-tab" data-bs-toggle="tab" data-bs-target="#inbounds" type="button" role="tab">دسترسی اینباندها</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" id="rules-tab" data-bs-toggle="tab" data-bs-target="#rules" type="button" role="tab">قوانین کانفیگ</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" id="wallet-tab" data-bs-toggle="tab" data-bs-target="#wallet" type="button" role="tab">قوانین کیف پول</button></li>
            </ul>

            <div class="tab-content p-3 border border-top-0 rounded-bottom">
                <!-- Main Info Tab -->
                <div class="tab-pane fade show active" id="main-info" role="tabpanel">
                    <div class="row">
                        <div class="col-md-6 mb-3"><label class="form-label">نام کاربری <span class="text-danger">*</span></label><input type="text" name="username" class="form-control" required value="<?= htmlspecialchars($form_data['username'] ?? '') ?>"></div>
                        <div class="col-md-6 mb-3"><label class="form-label">رمز عبور (برای تغییر وارد کنید)</label><input type="password" name="password" class="form-control" placeholder="••••••••"></div>
                        <div class="col-md-6 mb-3"><label class="form-label">نام کامل</label><input type="text" name="full_name" class="form-control" value="<?= htmlspecialchars($form_data['full_name'] ?? '') ?>"></div>
                        <div class="col-md-6 mb-3"><label class="form-label">ایمیل</label><input type="email" name="email" class="form-control" value="<?= htmlspecialchars($form_data['email'] ?? '') ?>"></div>
                        <div class="col-md-6 mb-3"><label class="form-label">تلفن</label><input type="text" name="phone" class="form-control" value="<?= htmlspecialchars($form_data['phone'] ?? '') ?>"></div>
                    </div>
                </div>

                <!-- Inbounds Tab -->
                <div class="tab-pane fade" id="inbounds" role="tabpanel">
                    <p>نماینده به کدام اینباندها دسترسی داشته باشد؟ <span class="text-danger">*</span></p>
                    <div id="inbounds-container" class="inbounds-container border p-3 rounded" style="max-height: 400px; overflow-y: auto;">
                        <?php foreach ($panels as $panel): ?>
                            <div class="panel-inbounds-group" id="panel-group-<?= $panel['id'] ?>">
                                <h5><?= htmlspecialchars($panel['name']) ?></h5>
                                <div class="ps-3">
                                    <div class="spinner-border spinner-border-sm text-primary" role="status">
                                        <span class="visually-hidden">در حال بارگذاری...</span>
                                    </div>
                                    <span class="text-muted">در حال بارگذاری اینباندها...</span>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Config Rules Tab -->
                <div class="tab-pane fade" id="rules" role="tabpanel">
                    <div class="row">
                        <div class="col-md-4 mb-3"><label class="form-label">ترافیک پیش‌فرض (GB)</label><input type="number" name="default_traffic_limit" class="form-control" min="0" value="<?= $form_data['default_traffic_limit'] ?? 5 ?>"></div>
                        <div class="col-md-4 mb-3"><label class="form-label">انقضا پیش‌فرض (روز)</label><input type="number" name="default_expiry_days" class="form-control" min="0" value="<?= $form_data['default_expiry_days'] ?? 30 ?>"></div>
                        <div class="col-md-4 mb-3"><label class="form-label">محدودیت IP پیش‌فرض</label><input type="number" name="default_ip_limit" class="form-control" min="0" value="<?= $form_data['default_ip_limit'] ?? 0 ?>"></div>
                    </div>
                    <hr>
                    <div class="form-check form-switch mb-3"><input class="form-check-input" type="checkbox" role="switch" id="can_create_test_config" name="can_create_test_config" <?= !empty($form_data['can_create_test_config']) ? 'checked' : '' ?>><label class="form-check-label" for="can_create_test_config">قابلیت ساخت کانفیگ تست</label></div>
                    <div class="row">
                        <div class="col-md-6 mb-3"><label class="form-label">ترافیک کانفیگ تست (GB)</label><input type="number" name="test_config_traffic_limit" class="form-control" min="1" value="<?= $form_data['test_config_traffic_limit'] ?? 1 ?>"></div>
                        <div class="col-md-6 mb-3"><label class="form-label">انقضا کانفیگ تست (ساعت)</label><input type="number" name="test_config_expiry_hours" class="form-control" min="1" value="<?= $form_data['test_config_expiry_hours'] ?? 3 ?>"></div>
                    </div>
                    <hr>
                    <div class="form-check form-switch mb-3"><input class="form-check-input" type="checkbox" role="switch" id="can_import_from_panel" name="can_import_from_panel" <?= !empty($form_data['can_import_from_panel']) ? 'checked' : '' ?>><label class="form-check-label" for="can_import_from_panel">قابلیت وارد کردن کاربر از پنل</label></div>
                </div>

                <!-- Wallet Rules Tab -->
                <div class="tab-pane fade" id="wallet" role="tabpanel">
                    <div class="row">
                        <div class="col-md-4 mb-3"><label class="form-label">قیمت هر گیگ (تومان)</label><input type="number" name="price_per_gb" class="form-control" min="0" step="1" value="<?= $form_data['price_per_gb'] ?? 0 ?>"></div>
                        <div class="col-md-4 mb-3"><label class="form-label">قیمت هر روز (تومان)</label><input type="number" name="price_per_day" class="form-control" min="0" step="1" value="<?= $form_data['price_per_day'] ?? 0 ?>"></div>
                        <div class="col-md-4 mb-3"><label class="form-label">درصد تخفیف</label><input type="number" name="discount_percent" class="form-control" min="0" max="100" value="<?= $form_data['discount_percent'] ?? 0 ?>"></div>
                    </div>
                </div>
            </div>

            <div class="mt-4">
                <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle-fill me-2"></i>ذخیره تغییرات</button>
                <a href="representatives.php" class="btn btn-secondary">انصراف</a>
            </div>
        </form>
    </div>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    const panels = document.querySelectorAll('.panel-inbounds-group');
    const existingInbounds = <?= json_encode($rep_inbounds_map) ?>;

    panels.forEach(panelElement => {
        const panelId = panelElement.id.split('-').pop();
        const container = panelElement.querySelector('.ps-3');

        fetch(`ajax_get_inbounds.php?panel_id=${panelId}`)
            .then(response => response.json())
            .then(data => {
                container.innerHTML = ''; // Clear the spinner
                if (data.success && data.inbounds.length > 0) {
                    data.inbounds.forEach(inbound => {
                        const div = document.createElement('div');
                        div.className = 'form-check';
                        
                        const input = document.createElement('input');
                        input.className = 'form-check-input';
                        input.type = 'checkbox';
                        input.name = 'inbound_ids[]';
                        const value = `${panelId}_${inbound.id}`;
                        input.value = value;
                        input.id = `inbound_${panelId}_${inbound.id}`;
                        if (existingInbounds[value]) {
                            input.checked = true;
                        }

                        const label = document.createElement('label');
                        label.className = 'form-check-label';
                        label.htmlFor = input.id;
                        label.textContent = inbound.tag;

                        div.appendChild(input);
                        div.appendChild(label);
                        container.appendChild(div);
                    });
                } else {
                    const message = data.message || 'اینباندی یافت نشد یا ارتباط با پنل برقرار نیست.';
                    container.innerHTML = `<p class="text-muted small">${message}</p>`;
                }
            })
            .catch(error => {
                container.innerHTML = `<p class="text-danger small">خطا در بارگذاری اطلاعات. لطفاً صفحه را رفرش کنید.</p>`;
                console.error('Error fetching inbounds:', error);
            });
    });
});
</script>
