<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../session.php';
require_once __DIR__ . '/../is_admin.php';

$page_title = 'مدیریت سرورها';

// Handle Add/Edit/Delete operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $server_id = $_POST['server_id'] ?? null;

    if ($action === 'delete' && $server_id) {
        $stmt = $pdo->prepare("DELETE FROM servers WHERE id = ?");
        $stmt->execute([$server_id]);
        setMessage('سرور با موفقیت حذف شد.', 'success');
        header('Location: servers.php');
        exit;
    }

    $name = $_POST['name'];
    $ip_address = $_POST['ip_address'];
    $ssh_user = $_POST['ssh_user'];
    $ssh_port = $_POST['ssh_port'] ?: 22;
    $tags = $_POST['tags'] ?? null;
    $traffic_limit_gb = (isset($_POST['traffic_limit_gb']) && $_POST['traffic_limit_gb'] !== '') ? $_POST['traffic_limit_gb'] : null;
    $expiration_date = (isset($_POST['expiration_date']) && $_POST['expiration_date'] !== '') ? $_POST['expiration_date'] : null;

    if ($action === 'add') {
        try {
            $ssh_password = encrypt_data($_POST['ssh_password']);
            $stmt = $pdo->prepare("INSERT INTO servers (name, ip_address, ssh_user, ssh_password, ssh_port, tags, traffic_limit_gb, expiration_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $ip_address, $ssh_user, $ssh_password, $ssh_port, $tags, $traffic_limit_gb, $expiration_date]);
            setMessage('سرور جدید با موفقیت اضافه شد.', 'success');
        } catch (PDOException $e) {
            if ($e->getCode() == 23000) { // Integrity constraint violation (duplicate entry)
                setMessage('خطا: سروری با این آدرس IP از قبل وجود دارد.', 'danger');
            } else {
                setMessage('خطا در پایگاه داده: ' . $e->getMessage(), 'danger');
            }
        }
    } elseif ($action === 'edit' && $server_id) {
        if (!empty($_POST['ssh_password'])) {
            $ssh_password = encrypt_data($_POST['ssh_password']);
            $stmt = $pdo->prepare("UPDATE servers SET name = ?, ip_address = ?, ssh_user = ?, ssh_password = ?, ssh_port = ?, tags = ?, traffic_limit_gb = ?, expiration_date = ? WHERE id = ?");
            $stmt->execute([$name, $ip_address, $ssh_user, $ssh_password, $ssh_port, $tags, $traffic_limit_gb, $expiration_date, $server_id]);
        } else {
            $stmt = $pdo->prepare("UPDATE servers SET name = ?, ip_address = ?, ssh_user = ?, ssh_port = ?, tags = ?, traffic_limit_gb = ?, expiration_date = ? WHERE id = ?");
            $stmt->execute([$name, $ip_address, $ssh_user, $ssh_port, $tags, $traffic_limit_gb, $expiration_date, $server_id]);
        }
        setMessage('اطلاعات سرور با موفقیت به‌روزرسانی شد.', 'success');
    }
    header('Location: servers.php');
    exit;
}

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

<div class="card admin-main-card">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
        <h3 class="card-title mb-0"><?= htmlspecialchars($page_title) ?></h3>
        <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#serverModal" onclick="prepareAddModal()">
            <i class="bi bi-plus-lg"></i> افزودن سرور جدید
        </button>
    </div>
    <div class="card-body">

                <table id="servers-table" class="table table-bordered dt-responsive nowrap w-100">
                    <thead>
                        <tr>
                            <th>نام</th>
                            <th>آدرس IP</th>
                            <th>کاربر SSH</th>
                            <th>پورت</th>
                            <th>برچسب‌ها</th>
                            <th>حد ترافیک (GB)</th>
                            <th>تاریخ انقضا</th>
                            <th>عملیات</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>

    </div>
</div>

<!-- Server Modal -->
<div class="modal fade" id="serverModal" tabindex="-1" aria-labelledby="serverModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="serverModalLabel">افزودن سرور جدید</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="serverForm" method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" id="action" value="add">
                    <input type="hidden" name="server_id" id="server_id">

                    <div class="mb-3">
                        <label for="name" class="form-label">نام سرور</label>
                        <input type="text" class="form-control" id="name" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="ip_address" class="form-label">آدرس IP</label>
                        <input type="text" class="form-control" id="ip_address" name="ip_address" required>
                        <div class="mb-3">
                            <label for="tags" class="form-label">برچسب‌ها</label>
                            <input type="text" class="form-control" id="tags" name="tags" placeholder="مثال: ایران, آلمان, اختصاصی">
                            <small class="form-text text-muted">برچسب‌ها را با کاما (,) از هم جدا کنید.</small>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-8">
                            <div class="mb-3">
                                <label for="ssh_user" class="form-label">کاربر SSH</label>
                                <input type="text" class="form-control" id="ssh_user" name="ssh_user" value="root" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="ssh_port" class="form-label">پورت SSH</label>
                                <input type="number" class="form-control" id="ssh_port" name="ssh_port" value="22" required>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="ssh_password" class="form-label">رمز عبور SSH</label>
                        <input type="password" class="form-control" id="ssh_password" name="ssh_password">
                        <small class="form-text text-muted" id="passwordHelp">در حالت ویرایش، برای تغییر ندادن رمز عبور، این فیلد را خالی بگذارید.</small>
                    </div>
                    <hr>
                     <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="traffic_limit_gb" class="form-label">حد مصرف ترافیک (GB)</label>
                                <input type="number" class="form-control" id="traffic_limit_gb" name="traffic_limit_gb" placeholder="اختیاری">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="expiration_date" class="form-label">تاریخ انقضا</label>
                                <input type="date" class="form-control" id="expiration_date" name="expiration_date">
                            </div>
                        </div>
                    </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>

<!-- Online Users Modal -->
<div class="modal fade" id="onlineUsersModal" tabindex="-1" aria-labelledby="onlineUsersModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="onlineUsersModalLabel">کاربران آنلاین</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="onlineUsersBody">
                <div class="text-center">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">در حال بارگذاری...</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">بستن</button>
            </div>
        </div>
    </div>
</div>

<?php
$page_specific_script = <<<JS
<script>
    let serversData = [];
    document.addEventListener('DOMContentLoaded', function() {
        fetch('api.php?action=get_servers')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json();
            })
            .then(data => {
                console.log("Data received, attempting to build table manually:", data);
                serversData = data;
                const tableBody = document.querySelector('#servers-table tbody');
                tableBody.innerHTML = ''; // Clear existing rows

                if (data.length === 0) {
                    tableBody.innerHTML = '<tr><td colspan="8" class="text-center">هیچ سروری یافت نشد.</td></tr>';
                    return;
                }

                data.forEach(function(server) {
                    const expirationDate = server.expiration_date_jalali;
                    const trafficLimit = server.traffic_limit_gb ? server.traffic_limit_gb + ' GB' : 'نامحدود';
                    const tags = server.tags ? server.tags.split(',').map(tag => `<span class="badge bg-secondary me-1">\${tag.trim()}</span>`).join(' ') : '';
                    const row = `
                        <tr>
                            <td>\${server.name}</td>
                            <td>\${server.ip_address}</td>
                            <td>\${server.ssh_user}</td>
                            <td>\${server.ssh_port}</td>
                            <td>\${tags}</td>
                            <td>\${trafficLimit}</td>
                            <td>\${expirationDate}</td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <button class="btn btn-icon btn-info" onclick="showOnlineUsers(\${server.id}, '\${server.name}')" title="کاربران آنلاین"><i class="bi bi-people-fill"></i></button>
                                    <button class="btn btn-icon btn-primary" onclick="prepareEditModal(\${server.id})"><i class="bi bi-pencil-fill"></i></button>
                                    <button class="btn btn-icon btn-danger" onclick="deleteServer(\${server.id})"><i class="bi bi-trash-fill"></i></button>
                                </div>
                            </td>
                        </tr>
                    `;
                    tableBody.insertAdjacentHTML('beforeend', row);
                });
            })
            .catch(error => {
                console.error("Fetch Error:", error);
                alert('خطا در بارگذاری اطلاعات سرورها. لطفاً کنسول مرورگر را برای جزئیات بیشتر بررسی کنید.');
            });
    });

    const serverModal = new bootstrap.Modal(document.getElementById('serverModal'));

    function prepareAddModal() {
        document.getElementById('serverForm').reset();
        document.getElementById('action').value = 'add';
        document.getElementById('server_id').value = '';
        document.getElementById('serverModalLabel').textContent = 'افزودن سرور جدید';
        document.getElementById('ssh_password').required = true;
        document.getElementById('passwordHelp').style.display = 'none';
        serverModal.show();
    }

    function prepareEditModal(id) {
        const server = serversData.find(s => s.id == id);
        if (server) {
            document.getElementById('action').value = 'edit';
            document.getElementById('server_id').value = server.id;
            document.getElementById('name').value = server.name;
            document.getElementById('ip_address').value = server.ip_address;
            document.getElementById('ssh_user').value = server.ssh_user;
            document.getElementById('ssh_port').value = server.ssh_port;
            document.getElementById('tags').value = server.tags;
            document.getElementById('traffic_limit_gb').value = server.traffic_limit_gb;
            document.getElementById('expiration_date').value = server.expiration_date;
            document.getElementById('ssh_password').value = '';
            document.getElementById('ssh_password').required = false;
            document.getElementById('serverModalLabel').textContent = 'ویرایش سرور: ' + server.name;
            document.getElementById('passwordHelp').style.display = 'block';
            serverModal.show();
        }
    }

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

    const onlineUsersModal = new bootstrap.Modal(document.getElementById('onlineUsersModal'));
    function showOnlineUsers(serverId, serverName) {
        const modalTitle = document.getElementById('onlineUsersModalLabel');
        const modalBody = document.getElementById('onlineUsersBody');

        modalTitle.textContent = 'کاربران آنلاین سرور: ' + serverName;
        modalBody.innerHTML = '<div class="text-center p-4"><div class="spinner-border" role="status"><span class="visually-hidden">در حال بارگذاری...</span></div></div>';
        onlineUsersModal.show();

        fetch(`ajax_online_users.php?server_id=${serverId}`)
            .then(response => response.text())
            .then(html => {
                modalBody.innerHTML = html;
            })
            .catch(error => {
                console.error('Error fetching online users:', error);
                modalBody.innerHTML = '<div class="alert alert-danger">خطا در دریافت اطلاعات کاربران آنلاین.</div>';
            });
    }
</script>
JS;

// We need an API endpoint to fetch server data for DataTable
if (!file_exists(__DIR__ . '/api.php')) {
    $api_content = <<<'PHP'
<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../session.php';
require_once __DIR__ . '/../is_admin.php';

$action = $_GET['action'] ?? '';

if ($action === 'get_servers') {
    $servers = $pdo->query("SELECT id, name, ip_address, ssh_user, ssh_port, traffic_limit_gb, expiration_date FROM servers ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($servers);
    exit;
}

echo json_encode(['error' => 'Invalid action']);
?>
PHP;
    file_put_contents(__DIR__ . '/api.php', $api_content);
}

$footer_scripts = $page_specific_script;
require_once __DIR__ . '/../includes/footer.php';
?>