<?php
/**
 * playlist_edit.php — Edit playlist/user details with robust auto-converter.
 */

declare(strict_types=1);

require_once __DIR__ . '/lib/auth.php';
require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/helpers.php';

require_login();

$pdo = db();
$id = (int) ($_GET['id'] ?? $_POST['id'] ?? 0);
$refDns = (int) ($_GET['ref_dns'] ?? $_POST['ref_dns'] ?? 0);

$flash = '';
$flashType = 'ok';

// Playlist ve bağlı cihaz bilgilerini çek
$stmt = $pdo->prepare('
    SELECT p.*, d.mac, d.device_key 
    FROM playlists p 
    JOIN devices d ON p.device_id = d.id 
    WHERE p.id = ? LIMIT 1
');
$stmt->execute([$id]);
$playlist = $stmt->fetch();

if (!$playlist) {
    header('Location: dns.php');
    exit;
}

// Form gönderildiğinde güncelleme işlemi
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    csrf_check();

    $name     = trim((string) ($_POST['name'] ?? ''));
    $type     = trim((string) ($_POST['type'] ?? 'xtream'));
    $username = trim((string) ($_POST['username'] ?? ''));
    $password = trim((string) ($_POST['password'] ?? ''));
    $url      = trim((string) ($_POST['url'] ?? ''));

    if ($name === '') {
        $flash = 'Playlist Name cannot be empty.';
        $flashType = 'error';
    } else {
        try {
            $upd = $pdo->prepare('UPDATE playlists SET name = ?, type = ?, username = ?, password = ?, url = ? WHERE id = ?');
            $upd->execute([$name, $type, $username, $password, $url, $id]);

            $flash = 'User / Playlist updated successfully!';
            
            // Bilgileri güncellemeden sonra tekrar oku
            $stmt->execute([$id]);
            $playlist = $stmt->fetch();
        } catch (Throwable $ex) {
            $flash = 'Error updating: ' . $ex->getMessage();
            $flashType = 'error';
        }
    }
}

$pageTitle = 'Edit Playlist - ' . $playlist['name'];
require __DIR__ . '/lib/header.php';
?>

<!-- NXS Panel Dynamic Theme Stilleri (Light & Dark Uyumlu) -->
<style>
    .glass-card {
        background: #ffffff !important;
        border: 1px solid #e5e7eb !important;
        border-radius: 16px !important;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.02) !important;
        overflow: hidden;
        margin-bottom: 24px;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .glass-card-header {
        padding: 16px 24px;
        border-bottom: 1px solid #e5e7eb;
        background: #f8fafc;
        display: flex;
        align-items: center;
        justify-content: space-between;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .glass-card-header h2 {
        margin: 0;
        font-size: 15px;
        font-weight: 700;
        color: #111827;
    }

    .form-control, .form-select {
        background: #ffffff !important;
        border: 1px solid #e5e7eb !important;
        color: #1f2937 !important;
        border-radius: 10px !important;
        padding: 10px 14px !important;
        transition: all 0.2s ease !important;
        font-size: 0.9rem;
    }

    .form-select option {
        background-color: #ffffff !important;
        color: #1f2937 !important;
        padding: 10px !important;
    }

    .form-control:focus, .form-select:focus {
        border-color: #7c3aed !important;
        box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.15) !important;
        background: #ffffff !important;
    }

    .form-control::placeholder {
        color: #9ca3af !important;
    }

    .form-label {
        font-size: 0.75rem !important;
        font-weight: 700 !important;
        letter-spacing: 0.8px !important;
        text-transform: uppercase !important;
        color: #4b5563 !important;
        margin-bottom: 6px !important;
    }

    .copy-btn {
        background: none;
        border: none;
        color: #6b7280;
        cursor: pointer;
        padding: 2px 4px;
        font-size: 0.85rem;
        transition: all 0.2s ease;
    }

    .copy-btn:hover {
        color: #7c3aed;
    }

    .btn-neon-save {
        background: #7c3aed !important;
        color: #ffffff !important;
        border: none !important;
        font-weight: 600 !important;
        padding: 10px 20px !important;
        border-radius: 10px !important;
        transition: opacity 0.2s ease !important;
    }

    .btn-neon-save:hover {
        opacity: 0.9;
    }

    .input-group-text-glass {
        background: #f8fafc !important;
        border: 1px solid #e5e7eb !important;
        color: #4b5563 !important;
        border-radius: 0 10px 10px 0 !important;
        cursor: pointer;
    }

    .input-group-text-glass:hover {
        color: #7c3aed !important;
    }

    /* --- Dark Mode (Koyu Tema) Uyarlamaları --- */
    [data-bs-theme="dark"] .glass-card {
        background: #171426 !important;
        border-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .glass-card-header {
        background: #141122 !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .glass-card-header h2 {
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .form-control, 
    [data-bs-theme="dark"] .form-select {
        background: #141122 !important;
        border-color: rgba(255, 255, 255, 0.08) !important;
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .form-select option {
        background-color: #171426 !important;
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .form-label {
        color: #9ca3af !important;
    }

    [data-bs-theme="dark"] .input-group-text-glass {
        background: #141122 !important;
        border-color: rgba(255, 255, 255, 0.08) !important;
        color: #9ca3af !important;
    }
</style>

<!-- Top Navigation & Header -->
<div class="d-flex flex-wrap justify-content-between align-items-center gap-3 mb-4">
    <div>
        <h1 class="h3 fw-bold mb-1 text-dark">Edit User / Playlist</h1>
        <p class="text-muted mono mb-0 d-flex align-items-center gap-2" style="font-size: 0.88rem;">
            Device MAC: <span class="fw-bold text-purple"><?= e($playlist['mac']) ?></span>
            <button class="copy-btn" onclick="copyToClipboard('<?= e($playlist['mac']) ?>', this)" title="Copy MAC">
                <i class="la la-copy"></i>
            </button>
        </p>
    </div>
    <?php if ($refDns > 0): ?>
        <a href="dns_users.php?dns_id=<?= $refDns ?>" class="btn btn-sm btn-outline-secondary rounded-3 px-3"><i class="la la-arrow-left me-1"></i> Back to DNS Users</a>
    <?php else: ?>
        <a href="dns.php" class="btn btn-sm btn-outline-secondary rounded-3 px-3"><i class="la la-arrow-left me-1"></i> Back to DNS List</a>
    <?php endif; ?>
</div>

<?php if ($flash !== ''): ?>
    <div class="alert <?= $flashType === 'ok' ? 'alert-success' : 'alert-danger' ?> alert-dismissible fade show mb-4" role="alert">
        <i class="la <?= $flashType === 'ok' ? 'la-check-circle' : 'la-exclamation-circle' ?> me-1"></i> <?= e($flash) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<!-- Main Edit Form Card -->
<div class="glass-card">
    <div class="glass-card-header">
        <h2>Playlist Configuration</h2>
    </div>
    <div class="card-body p-4">
        <form method="post" action="playlist_edit.php">
            <?= csrf_field() ?>
            <input type="hidden" name="id" value="<?= (int) $playlist['id'] ?>">
            <input type="hidden" name="ref_dns" value="<?= $refDns ?>">

            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label" for="name">Playlist Name</label>
                    <input type="text" class="form-control fw-bold" id="name" name="name" value="<?= e($playlist['name']) ?>" required placeholder="e.g. My List">
                </div>

                <div class="col-md-6">
                    <label class="form-label" for="type">Playlist Type</label>
                    <select class="form-select fw-bold" id="type" name="type">
                        <option value="xtream" <?= $playlist['type'] === 'xtream' ? 'selected' : '' ?>>Xtream Codes API</option>
                        <option value="m3u" <?= $playlist['type'] === 'm3u' ? 'selected' : '' ?>>M3U Playlist URL</option>
                    </select>
                </div>

                <div class="col-md-6" id="usernameCol">
                    <label class="form-label" for="username">Username</label>
                    <input type="text" class="form-control mono" id="username" name="username" value="<?= e($playlist['username']) ?>" placeholder="Xtream username">
                </div>

                <div class="col-md-6" id="passwordCol">
                    <label class="form-label" for="password">Password</label>
                    <div class="input-group">
                        <input type="text" class="form-control mono border-end-0" id="password" name="password" value="<?= e($playlist['password']) ?>" placeholder="Xtream password">
                        <span class="input-group-text input-group-text-glass" id="togglePasswordBtn" onclick="togglePasswordVisibility()">
                            <i class="la la-eye-slash" id="togglePasswordIcon"></i>
                        </span>
                    </div>
                </div>

                <div class="col-md-12">
                    <label class="form-label" for="url" id="urlLabel">Server / Stream URL</label>
                    <input type="text" class="form-control mono" id="url" name="url" value="<?= e($playlist['url']) ?>" required placeholder="http://domain.com:8080">
                </div>
            </div>

            <div class="d-flex justify-content-between align-items-center mt-4 pt-3 border-top">
                <button type="submit" class="btn btn-neon-save">
                    <i class="la la-save me-1"></i> Save Changes
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function togglePasswordVisibility() {
    const passwordInput = document.getElementById('password');
    const icon = document.getElementById('togglePasswordIcon');
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        icon.className = 'la la-eye-slash';
    } else {
        passwordInput.type = 'password';
        icon.className = 'la la-eye';
    }
}

function copyToClipboard(text, btnElement) {
    navigator.clipboard.writeText(text).then(function() {
        const icon = btnElement.querySelector('i');
        if (icon) {
            icon.className = 'la la-check text-success';
            setTimeout(() => {
                icon.className = 'la la-copy';
            }, 1500);
        }
    });
}

function handleTypeChange() {
    const typeSelect = document.getElementById('type');
    const usernameCol = document.getElementById('usernameCol');
    const passwordCol = document.getElementById('passwordCol');
    const urlLabel = document.getElementById('urlLabel');
    const urlInput = document.getElementById('url');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');

    if (!typeSelect) return;

    if (typeSelect.value === 'm3u') {
        let user = usernameInput.value.trim();
        let pass = passwordInput.value.trim();
        let baseUrl = urlInput.value.trim().replace(/\/+$/, '');

        if (user !== '' && pass !== '' && baseUrl !== '' && !baseUrl.includes('get.php')) {
            urlInput.value = baseUrl + '/get.php?username=' + encodeURIComponent(user) + '&password=' + encodeURIComponent(pass) + '&type=m3u_plus&output=ts';
        }

        if (usernameCol) usernameCol.style.display = 'none';
        if (passwordCol) passwordCol.style.display = 'none';
        if (urlLabel) urlLabel.textContent = 'M3U Playlist URL';
        if (urlInput) urlInput.placeholder = 'http://domain.com/get.php?username=xxx&password=yyy&type=m3u_plus&output=ts';

    } else {
        let currentUrl = urlInput.value.trim();

        if (currentUrl !== '') {
            let testUrl = currentUrl;
            if (!testUrl.startsWith('http://') && !testUrl.startsWith('https://')) {
                testUrl = 'http://' + testUrl;
            }

            try {
                let parsed = new URL(testUrl);
                let params = new URLSearchParams(parsed.search);

                let extractedUser = params.get('username') || params.get('user') || '';
                let extractedPass = params.get('password') || params.get('pass') || '';

                if (extractedUser) usernameInput.value = extractedUser;
                if (extractedPass) passwordInput.value = extractedPass;

                let cleanBase = parsed.protocol + '//' + parsed.host;
                if (currentUrl.includes('username=') || currentUrl.includes('get.php')) {
                    urlInput.value = cleanBase;
                }
            } catch (e) {
                // Hata durumunda yoksay
            }
        }

        if (usernameCol) usernameCol.style.display = 'block';
        if (passwordCol) passwordCol.style.display = 'block';
        if (urlLabel) urlLabel.textContent = 'Server / DNS Base URL';
        if (urlInput) urlInput.placeholder = 'http://domain.com:8080';
    }
}

document.addEventListener('DOMContentLoaded', function () {
    const typeSelect = document.getElementById('type');
    if (typeSelect) {
        typeSelect.addEventListener('change', handleTypeChange);
        
        if (typeSelect.value === 'm3u') {
            if (document.getElementById('usernameCol')) document.getElementById('usernameCol').style.display = 'none';
            if (document.getElementById('passwordCol')) document.getElementById('passwordCol').style.display = 'none';
            if (document.getElementById('urlLabel')) document.getElementById('urlLabel').textContent = 'M3U Playlist URL';
        }
    }
});
</script>

<?php require __DIR__ . '/lib/footer.php'; ?>