<?php
include('includes/auth.php');

$table_name = 'vpn_profiles';
$page = 'vpn.php';

// Fetch record for update
$resU = null;
if (isset($_GET['update'])) {
    $resU = $db->select($table_name, '*', 'id = :id', '', [':id' => (int) $_GET['update']]);
}

// Handle update
if (isset($_POST['submitU'])) {
    if (!verify_token($_POST['csrf_token'] ?? '')) {
        header("Location: {$page}?status=4");
        exit;
    }
    $updateData = [
        'name' => trim($_POST['name'] ?? ''),
        'country' => trim($_POST['country'] ?? ''),
        'city' => trim($_POST['city'] ?? ''),
        'protocol' => trim($_POST['protocol'] ?? 'udp'),
        'port' => trim($_POST['port'] ?? '1194'),
        'ovpn_config' => trim($_POST['ovpn_config'] ?? ''),
        'config_url' => trim($_POST['config_url'] ?? ''),
        'username' => trim($_POST['username'] ?? ''),
        'password' => trim($_POST['password'] ?? ''),
        'enabled' => isset($_POST['enabled']) ? 1 : 0,
    ];
    $db->update($table_name, $updateData, 'id = :id', [':id' => (int) $_GET['update']]);
    header("Location: {$page}?status=1");
    exit;
}

// Handle create
if (isset($_POST['submit'])) {
    if (!verify_token($_POST['csrf_token'] ?? '')) {
        header("Location: {$page}?status=4");
        exit;
    }
    $insertData = [
        'name' => trim($_POST['name'] ?? ''),
        'country' => trim($_POST['country'] ?? ''),
        'city' => trim($_POST['city'] ?? ''),
        'protocol' => trim($_POST['protocol'] ?? 'udp'),
        'port' => trim($_POST['port'] ?? '1194'),
        'ovpn_config' => trim($_POST['ovpn_config'] ?? ''),
        'config_url' => trim($_POST['config_url'] ?? ''),
        'username' => trim($_POST['username'] ?? ''),
        'password' => trim($_POST['password'] ?? ''),
        'enabled' => isset($_POST['enabled']) ? 1 : 0,
        'created_at' => date('Y-m-d H:i:s'),
    ];
    $db->insert($table_name, $insertData);
    header("Location: {$page}?status=1");
    exit;
}

// Handle delete
if (isset($_GET['delete'])) {
    $db->delete($table_name, 'id = :id', [':id' => (int) $_GET['delete']]);
    header("Location: {$page}?status=2");
    exit;
}

// Handle toggle
if (isset($_GET['toggle'])) {
    $item = $db->select($table_name, '*', 'id = :id', '', [':id' => (int) $_GET['toggle']]);
    if (!empty($item)) {
        $newState = ((int) ($item[0]['enabled'] ?? 0)) === 1 ? 0 : 1;
        $db->update($table_name, ['enabled' => $newState], 'id = :id', [':id' => (int) $_GET['toggle']]);
    }
    header("Location: {$page}?status=1");
    exit;
}

// --- All redirects handled, now output HTML ---
include('includes/header.php');

$res = $db->select($table_name, '*', '', 'id ASC');
$csrfToken = generate_token();
?>

<?php if (isset($_GET['create'])): ?>
<div class="md-card md-card--elevated" style="max-width: 800px; margin: 0 auto;">
    <div class="md-card__header">
        <?= icon('add_circle', 'md-card__header-icon') ?>
        <h2 class="md-card__title">Add VPN Profile</h2>
    </div>
    <div class="md-card__content">
        <form method="post">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
            <div class="md-text-field md-text-field--outlined">
                <input type="text" name="name" id="name" class="md-text-field__input" placeholder=" " required>
                <label for="name" class="md-text-field__label">Profile Name</label>
                <div class="md-text-field__indicator"></div>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                <div class="md-text-field md-text-field--outlined">
                    <input type="text" name="country" id="country" class="md-text-field__input" placeholder=" ">
                    <label for="country" class="md-text-field__label">Country</label>
                    <div class="md-text-field__indicator"></div>
                </div>
                <div class="md-text-field md-text-field--outlined">
                    <input type="text" name="city" id="city" class="md-text-field__input" placeholder=" ">
                    <label for="city" class="md-text-field__label">City</label>
                    <div class="md-text-field__indicator"></div>
                </div>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                <div class="md-text-field md-text-field--outlined">
                    <select name="protocol" class="md-text-field__input">
                        <option value="udp">UDP</option>
                        <option value="tcp">TCP</option>
                    </select>
                    <label class="md-text-field__label">Protocol</label>
                </div>
                <div class="md-text-field md-text-field--outlined">
                    <input type="text" name="port" id="port" class="md-text-field__input" placeholder=" " value="1194">
                    <label for="port" class="md-text-field__label">Port</label>
                    <div class="md-text-field__indicator"></div>
                </div>
            </div>
            <div class="md-text-field md-text-field--outlined md-text-field--textarea">
                <textarea name="ovpn_config" id="ovpn_config" class="md-text-field__input md-text-field__textarea" placeholder=" " rows="8"></textarea>
                <label for="ovpn_config" class="md-text-field__label">OpenVPN Config (paste .ovpn content)</label>
                <div class="md-text-field__indicator"></div>
            </div>
            <p class="md-helper-text">OR provide a URL to download the config:</p>
            <div class="md-text-field md-text-field--outlined">
                <input type="text" name="config_url" id="config_url" class="md-text-field__input" placeholder=" ">
                <label for="config_url" class="md-text-field__label">Config Download URL (HTTPS)</label>
                <div class="md-text-field__indicator"></div>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                <div class="md-text-field md-text-field--outlined">
                    <input type="text" name="username" class="md-text-field__input" placeholder=" ">
                    <label class="md-text-field__label">Auth Username (optional)</label>
                    <div class="md-text-field__indicator"></div>
                </div>
                <div class="md-text-field md-text-field--outlined">
                    <input type="text" name="password" class="md-text-field__input" placeholder=" ">
                    <label class="md-text-field__label">Auth Password (optional)</label>
                    <div class="md-text-field__indicator"></div>
                </div>
            </div>
            <label style="display: flex; align-items: center; gap: 0.5rem; margin: 1rem 0; color: var(--md-on-surface);">
                <input type="checkbox" name="enabled" checked> Enabled
            </label>
            <div class="md-card__actions">
                <a href="<?= $page ?>" class="md-button md-button--text">Cancel</a>
                <button type="submit" name="submit" class="md-button md-button--filled">
                    <?= icon('check') ?>
                    <span class="md-button__label">Save</span>
                </button>
            </div>
        </form>
    </div>
</div>

<?php elseif (isset($_GET['update']) && $resU): ?>
<div class="md-card md-card--elevated" style="max-width: 800px; margin: 0 auto;">
    <div class="md-card__header">
        <?= icon('edit', 'md-card__header-icon') ?>
        <h2 class="md-card__title">Edit VPN Profile</h2>
    </div>
    <div class="md-card__content">
        <form method="post">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
            <div class="md-text-field md-text-field--outlined">
                <input type="text" name="name" class="md-text-field__input" placeholder=" " required value="<?= htmlspecialchars($resU[0]['name'] ?? '') ?>">
                <label class="md-text-field__label">Profile Name</label>
                <div class="md-text-field__indicator"></div>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                <div class="md-text-field md-text-field--outlined">
                    <input type="text" name="country" class="md-text-field__input" placeholder=" " value="<?= htmlspecialchars($resU[0]['country'] ?? '') ?>">
                    <label class="md-text-field__label">Country</label>
                    <div class="md-text-field__indicator"></div>
                </div>
                <div class="md-text-field md-text-field--outlined">
                    <input type="text" name="city" class="md-text-field__input" placeholder=" " value="<?= htmlspecialchars($resU[0]['city'] ?? '') ?>">
                    <label class="md-text-field__label">City</label>
                    <div class="md-text-field__indicator"></div>
                </div>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                <div class="md-text-field md-text-field--outlined">
                    <select name="protocol" class="md-text-field__input">
                        <option value="udp" <?= ($resU[0]['protocol'] ?? '') === 'udp' ? 'selected' : '' ?>>UDP</option>
                        <option value="tcp" <?= ($resU[0]['protocol'] ?? '') === 'tcp' ? 'selected' : '' ?>>TCP</option>
                    </select>
                    <label class="md-text-field__label">Protocol</label>
                </div>
                <div class="md-text-field md-text-field--outlined">
                    <input type="text" name="port" class="md-text-field__input" placeholder=" " value="<?= htmlspecialchars($resU[0]['port'] ?? '1194') ?>">
                    <label class="md-text-field__label">Port</label>
                    <div class="md-text-field__indicator"></div>
                </div>
            </div>
            <div class="md-text-field md-text-field--outlined md-text-field--textarea">
                <textarea name="ovpn_config" class="md-text-field__input md-text-field__textarea" placeholder=" " rows="8"><?= htmlspecialchars($resU[0]['ovpn_config'] ?? '') ?></textarea>
                <label class="md-text-field__label">OpenVPN Config</label>
                <div class="md-text-field__indicator"></div>
            </div>
            <div class="md-text-field md-text-field--outlined">
                <input type="text" name="config_url" class="md-text-field__input" placeholder=" " value="<?= htmlspecialchars($resU[0]['config_url'] ?? '') ?>">
                <label class="md-text-field__label">Config Download URL</label>
                <div class="md-text-field__indicator"></div>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                <div class="md-text-field md-text-field--outlined">
                    <input type="text" name="username" class="md-text-field__input" placeholder=" " value="<?= htmlspecialchars($resU[0]['username'] ?? '') ?>">
                    <label class="md-text-field__label">Auth Username</label>
                    <div class="md-text-field__indicator"></div>
                </div>
                <div class="md-text-field md-text-field--outlined">
                    <input type="text" name="password" class="md-text-field__input" placeholder=" " value="<?= htmlspecialchars($resU[0]['password'] ?? '') ?>">
                    <label class="md-text-field__label">Auth Password</label>
                    <div class="md-text-field__indicator"></div>
                </div>
            </div>
            <label style="display: flex; align-items: center; gap: 0.5rem; margin: 1rem 0; color: var(--md-on-surface);">
                <input type="checkbox" name="enabled" <?= ((int)($resU[0]['enabled'] ?? 0)) === 1 ? 'checked' : '' ?>> Enabled
            </label>
            <div class="md-card__actions">
                <a href="<?= $page ?>" class="md-button md-button--text">Cancel</a>
                <button type="submit" name="submitU" class="md-button md-button--filled">
                    <?= icon('check') ?>
                    <span class="md-button__label">Update</span>
                </button>
            </div>
        </form>
    </div>
</div>

<?php else: ?>
<div class="md-card md-card--elevated">
    <div class="md-card__header">
        <?= icon('vpn_key', 'md-card__header-icon') ?>
        <h2 class="md-card__title">VPN Profiles</h2>
        <a href="<?= $page ?>?create" class="md-button md-button--filled-tonal md-button--icon-right">
            <?= icon('add') ?>
            <span class="md-button__label">Add Profile</span>
        </a>
    </div>
    <div class="md-card__content md-card__content--table">
        <?php if (empty($res)): ?>
            <div class="md-empty-state">
                <?= icon('vpn_key', 'md-empty-state__icon') ?>
                <p class="md-empty-state__text">No VPN profiles configured. Add an OpenVPN profile to enable in-app VPN.</p>
            </div>
        <?php else: ?>
        <div class="md-table-container">
            <table class="md-table">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Location</th>
                        <th>Protocol</th>
                        <th>Config</th>
                        <th>Status</th>
                        <th class="md-table__actions-col">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($res as $row): ?>
                    <tr>
                        <td><strong><?= htmlspecialchars($row['name'] ?? '') ?></strong></td>
                        <td><?= htmlspecialchars(($row['country'] ?? '') . ($row['city'] ? ', ' . $row['city'] : '')) ?></td>
                        <td><span class="md-chip md-chip--small"><?= htmlspecialchars(strtoupper($row['protocol'] ?? 'UDP')) ?>:<?= htmlspecialchars($row['port'] ?? '1194') ?></span></td>
                        <td>
                            <?php if (!empty($row['ovpn_config'])): ?>
                                <span class="md-chip md-chip--success">Inline</span>
                            <?php elseif (!empty($row['config_url'])): ?>
                                <span class="md-chip md-chip--info">URL</span>
                            <?php else: ?>
                                <span class="md-chip md-chip--error">None</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <a href="<?= $page ?>?toggle=<?= (int) $row['id'] ?>" class="md-chip md-chip--<?= ((int)($row['enabled'] ?? 0)) === 1 ? 'success' : 'error' ?>">
                                <?= ((int)($row['enabled'] ?? 0)) === 1 ? 'Active' : 'Disabled' ?>
                            </a>
                        </td>
                        <td class="md-table__actions">
                            <a href="<?= $page ?>?update=<?= (int) $row['id'] ?>" class="md-icon-button" title="Edit">
                                <?= icon('edit') ?>
                            </a>
                            <button class="md-icon-button md-icon-button--error" title="Delete"
                                    onclick="showDeleteDialog('<?= $page ?>?delete=<?= (int) $row['id'] ?>')">
                                <?= icon('delete') ?>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<?php include('includes/footer.php'); ?>
