<?php
session_start();
require_once 'config/database.php';

// Get user info
$user_id = $_SESSION['user_id'];
$sql = "SELECT username, email, role FROM users WHERE id = $user_id";
$result = $con->query($sql);
$user = $result ? $result->fetch_assoc() : null;

// If user not found, create empty user array to prevent sidebar errors
if (!$user) {
    $user = [
        'username' => 'Unknown',
        'email' => '',
        'role' => 'user'
    ];
}

// Layout variables
$page_title = 'DMAppsESP - Kullanıcı Düzenle';
$breadcrumb_title = 'Kullanıcı Düzenle';
$current_page = 'users';
$extra_css = '<style>
    .form-section {
        background: white;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .permission-item {
        border: 1px solid #ddd;
        border-radius: 5px;
        padding: 10px;
        margin-bottom: 10px;
        background: #f8f9fa;
    }
    .activity-item {
        border-left: 3px solid #007bff;
        padding-left: 15px;
        margin-bottom: 10px;
    }
    .status-badge {
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: bold;
    }
    .status-active { background-color: #d4edda; color: #155724; }
    .status-inactive { background-color: #f8d7da; color: #721c24; }
    .status-suspended { background-color: #fff3cd; color: #856404; }
</style>';

$extra_js = '<script>
function validateForm() {
    const username = document.getElementById(\'username\').value;
    const email = document.getElementById(\'email\').value;
    
    if (!username.trim()) {
        alert(\'Kullanıcı adı boş olamaz!\');
        return false;
    }
    
    if (!email.trim()) {
        alert(\'E-posta adresi boş olamaz!\');
        return false;
    }
    
    // E-posta formatını kontrol et
    const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
    if (!emailRegex.test(email)) {
        alert(\'Geçerli bir e-posta adresi giriniz!\');
        return false;
    }
    
    return true;
}

function togglePassword() {
    const passwordField = document.getElementById(\'password\');
    const confirmPasswordField = document.getElementById(\'confirmPassword\');
    const toggleBtn = document.getElementById(\'togglePassword\');
    
    if (passwordField.type === \'password\') {
        passwordField.type = \'text\';
        confirmPasswordField.type = \'text\';
        toggleBtn.textContent = \'Gizle\';
    } else {
        passwordField.type = \'password\';
        confirmPasswordField.type = \'password\';
        toggleBtn.textContent = \'Göster\';
    }
}

function checkPasswords() {
    const password = document.getElementById(\'password\').value;
    const confirmPassword = document.getElementById(\'confirmPassword\').value;
    const message = document.getElementById(\'passwordMessage\');
    
    if (password && confirmPassword) {
        if (password === confirmPassword) {
            message.innerHTML = \'<span class="text-success">Şifreler eşleşiyor</span>\';
            message.className = \'form-text\';
        } else {
            message.innerHTML = \'<span class="text-danger">Şifreler eşleşmiyor</span>\';
            message.className = \'form-text\';
        }
    } else {
        message.innerHTML = \'\';
    }
}

function saveUser() {
    if (!validateForm()) {
        return;
    }
    
    const formData = new FormData(document.getElementById(\'userForm\'));
    
    fetch(\'api/users.php?action=update\', {
        method: \'POST\',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(\'Kullanıcı başarıyla güncellendi!\');
            window.location.href = \'all_users.php\';
        } else {
            alert(\'Hata: \' + data.message);
        }
    })
    .catch(error => {
        alert(\'Hata: \' + error.message);
    });
}

function resetPassword() {
    if (confirm(\'Bu kullanıcının şifresini sıfırlamak istediğinizden emin misiniz?\')) {
        const userId = document.getElementById(\'userId\').value;
        
        fetch(\'api/users.php?action=reset_password\', {
            method: \'POST\',
            headers: {
                \'Content-Type\': \'application/json\'
            },
            body: JSON.stringify({user_id: userId})
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(\'Şifre sıfırlandı: \' + data.new_password);
            } else {
                alert(\'Hata: \' + data.message);
            }
        });
    }
}

function toggleStatus() {
    const userId = document.getElementById(\'userId\').value;
    const currentStatus = document.getElementById(\'status\').value;
    const newStatus = currentStatus === \'active\' ? \'inactive\' : \'active\';
    
    fetch(\'api/users.php?action=toggle_status\', {
        method: \'POST\',
        headers: {
            \'Content-Type\': \'application/json\'
        },
        body: JSON.stringify({user_id: userId, status: newStatus})
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById(\'status\').value = newStatus;
            updateStatusBadge(newStatus);
            alert(\'Kullanıcı durumu güncellendi!\');
        } else {
            alert(\'Hata: \' + data.message);
        }
    });
}

function updateStatusBadge(status) {
    const badge = document.getElementById(\'statusBadge\');
    badge.className = \'status-badge status-\' + status;
    badge.textContent = status.charAt(0).toUpperCase() + status.slice(1);
}

function loadUserActivity() {
    const userId = document.getElementById(\'userId\').value;
    
    fetch(\'api/users.php?action=activity&user_id=\' + userId)
        .then(response => response.json())
        .then(data => {
            const container = document.getElementById(\'activityContainer\');
            let html = \'\';
            
            if (data.activities && data.activities.length > 0) {
                data.activities.forEach(activity => {
                    html += \'<div class="activity-item">\';
                    html += \'<strong>\' + activity.action + \'</strong>\';
                    html += \'<br><small class="text-muted">\' + activity.created_at + \'</small>\';
                    html += \'</div>\';
                });
            } else {
                html = \'<p class="text-muted">Aktivite bulunamadı.</p>\';
            }
            
            container.innerHTML = html;
        });
}

function loadUserDevices() {
    const userId = document.getElementById(\'userId\').value;
    
    fetch(\'api/users.php?action=devices&user_id=\' + userId)
        .then(response => response.json())
        .then(data => {
            const container = document.getElementById(\'devicesContainer\');
            let html = \'\';
            
            if (data.devices && data.devices.length > 0) {
                data.devices.forEach(device => {
                    html += \'<div class="permission-item">\';
                    html += \'<strong>\' + device.name + \'</strong> (\' + device.device_id + \')\';
                    html += \'<br><small class="text-muted">İzin: \' + device.permission_type + \'</small>\';
                    html += \'</div>\';
                });
            } else {
                html = \'<p class="text-muted">Cihaz bulunamadı.</p>\';
            }
            
            container.innerHTML = html;
        });
}
</script>';

// Kullanıcı bilgilerini getir
$user_id = $_GET['id'] ?? 0;
$user = null;

if ($user_id > 0) {
    $stmt = $con->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
    }
}

if (!$user) {
    header('Location: all_users.php');
    exit;
}

require_once 'layouts/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <h1 class="h3 mb-4">Kullanıcı Düzenle: <?php echo htmlspecialchars($user['username']); ?></h1>
            
            <form id="userForm" method="post" onsubmit="return false;">
                <input type="hidden" id="userId" name="user_id" value="<?php echo $user_id; ?>">
                
                <!-- Temel Bilgiler -->
                <div class="form-section">
                    <h5>Temel Bilgiler</h5>
                    <div class="row">
                        <div class="col-md-4">
                            <label class="form-label">Kullanıcı Adı:</label>
                            <input type="text" class="form-control" id="username" name="username" value="<?php echo htmlspecialchars($user['username']); ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">E-posta:</label>
                            <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Rol:</label>
                            <select class="form-select" name="role">
                                <option value="viewer" <?php echo $user['role'] == 'viewer' ? 'selected' : ''; ?>>Viewer</option>
                                <option value="user" <?php echo $user['role'] == 'user' ? 'selected' : ''; ?>>User</option>
                                <option value="admin" <?php echo $user['role'] == 'admin' ? 'selected' : ''; ?>>Admin</option>
                            </select>
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-4">
                            <label class="form-label">Ad:</label>
                            <input type="text" class="form-control" name="first_name" value="<?php echo htmlspecialchars($user['first_name']); ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Soyad:</label>
                            <input type="text" class="form-control" name="last_name" value="<?php echo htmlspecialchars($user['last_name']); ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Telefon:</label>
                            <input type="tel" class="form-control" name="phone" value="<?php echo htmlspecialchars($user['phone']); ?>">
                        </div>
                    </div>
                </div>
                
                <!-- Durum ve Güvenlik -->
                <div class="form-section">
                    <h5>Durum ve Güvenlik</h5>
                    <div class="row">
                        <div class="col-md-4">
                            <label class="form-label">Durum:</label>
                            <select class="form-select" id="status" name="status">
                                <option value="active" <?php echo $user['status'] == 'active' ? 'selected' : ''; ?>>Aktif</option>
                                <option value="inactive" <?php echo $user['status'] == 'inactive' ? 'selected' : ''; ?>>Pasif</option>
                                <option value="suspended" <?php echo $user['status'] == 'suspended' ? 'selected' : ''; ?>>Askıya Alındı</option>
                            </select>
                            <span id="statusBadge" class="status-badge status-<?php echo $user['status']; ?>">
                                <?php echo ucfirst($user['status']); ?>
                            </span>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Son Giriş:</label>
                            <input type="text" class="form-control" value="<?php echo $user['last_login'] ? date('d.m.Y H:i', strtotime($user['last_login'])) : 'Hiç giriş yapmadı'; ?>" readonly>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Kayıt Tarihi:</label>
                            <input type="text" class="form-control" value="<?php echo date('d.m.Y H:i', strtotime($user['created_at'])); ?>" readonly>
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label class="form-label">Yeni Şifre:</label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="password" name="password" placeholder="Boş bırakırsanız şifre değişmez">
                                <button class="btn btn-outline-secondary" type="button" id="togglePassword" onclick="togglePassword()">Göster</button>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Şifre Tekrar:</label>
                            <input type="password" class="form-control" id="confirmPassword" name="confirm_password" placeholder="Şifreyi tekrar girin" onkeyup="checkPasswords()">
                            <div id="passwordMessage" class="form-text"></div>
                        </div>
                    </div>
                </div>
                
                <!-- Kullanıcı Aktivitesi -->
                <div class="form-section">
                    <h5>Kullanıcı Aktivitesi</h5>
                    <div id="activityContainer">
                        <p class="text-muted">Aktivite yükleniyor...</p>
                    </div>
                </div>
                
                <!-- Cihaz İzinleri -->
                <div class="form-section">
                    <h5>Cihaz İzinleri</h5>
                    <div id="devicesContainer">
                        <p class="text-muted">Cihazlar yükleniyor...</p>
                    </div>
                </div>
                
                <!-- Butonlar -->
                <div class="row">
                    <div class="col-12">
                        <button type="button" class="btn btn-primary" onclick="saveUser()">Kaydet</button>
                        <button type="button" class="btn btn-warning" onclick="resetPassword()">Şifre Sıfırla</button>
                        <button type="button" class="btn btn-info" onclick="toggleStatus()">Durum Değiştir</button>
                        <a href="all_users.php" class="btn btn-secondary">İptal</a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Sayfa yüklendiğinde aktivite ve cihazları yükle
document.addEventListener('DOMContentLoaded', function() {
    loadUserActivity();
    loadUserDevices();
});
</script>

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