<?php
require_once 'config.php';
require_once 'includes/Database.php';
require_once 'includes/Auth.php';

Auth::requireLogin();

$db = new Database();
$pageTitle = Auth::isAdmin() ? 'Hesap Yönetimi' : 'Hesap Ayarlarım';

$message = '';
$messageType = '';

// Kullanıcı Ekleme (Sadece Admin)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add' && Auth::isAdmin()) {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $full_name = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $extension = trim($_POST['extension'] ?? '');
    $salary = trim($_POST['salary'] ?? '0');
    $role = $_POST['role'] ?? 'personel';

    if (empty($username) || empty($password) || empty($full_name)) {
        $message = 'Kullanıcı adı, şifre ve ad soyad zorunludur!';
        $messageType = 'error';
    } else {
        $hashedPassword = password_hash($password, HASH_ALGO);
        $sql = "INSERT INTO users (username, password, full_name, email, phone, extension, salary, role) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

        if ($db->query($sql, [$username, $hashedPassword, $full_name, $email, $phone, $extension, $salary, $role])) {
            $message = 'Kullanıcı başarıyla eklendi!';
            $messageType = 'success';
        } else {
            $message = 'Kullanıcı eklenirken hata oluştu!';
            $messageType = 'error';
        }
    }
}

// Kullanıcı Güncelleme
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit') {
    $id = $_POST['id'] ?? 0;
    $username = trim($_POST['username'] ?? '');
    $full_name = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $extension = trim($_POST['extension'] ?? '');
    $salary = trim($_POST['salary'] ?? '0');
    $role = $_POST['role'] ?? 'personel';
    $password = $_POST['password'] ?? '';

    // Personel sadece kendi hesabını düzenleyebilir
    if (!Auth::isAdmin()) {
        $currentUser = $db->fetchOne("SELECT id FROM users WHERE full_name = ?", [Auth::getFullName()]);
        if (!$currentUser || $currentUser['id'] != $id) {
            $message = 'Bu işlem için yetkiniz yok!';
            $messageType = 'error';
            goto skipEdit;
        }
    }

    if (empty($username) || empty($full_name)) {
        $message = 'Kullanıcı adı ve ad soyad zorunludur!';
        $messageType = 'error';
    } else {
        if (!empty($password)) {
            $hashedPassword = password_hash($password, HASH_ALGO);
            if (Auth::isAdmin()) {
                $sql = "UPDATE users SET username = ?, password = ?, full_name = ?, email = ?, phone = ?, extension = ?, salary = ?, role = ? WHERE id = ?";
                $params = [$username, $hashedPassword, $full_name, $email, $phone, $extension, $salary, $role, $id];
            } else {
                // Personel rol değiştiremez
                $sql = "UPDATE users SET username = ?, password = ?, full_name = ?, email = ?, phone = ?, extension = ?, salary = ? WHERE id = ?";
                $params = [$username, $hashedPassword, $full_name, $email, $phone, $extension, $salary, $id];
            }
        } else {
            if (Auth::isAdmin()) {
                $sql = "UPDATE users SET username = ?, full_name = ?, email = ?, phone = ?, extension = ?, salary = ?, role = ? WHERE id = ?";
                $params = [$username, $full_name, $email, $phone, $extension, $salary, $role, $id];
            } else {
                // Personel rol değiştiremez
                $sql = "UPDATE users SET username = ?, full_name = ?, email = ?, phone = ?, extension = ?, salary = ? WHERE id = ?";
                $params = [$username, $full_name, $email, $phone, $extension, $salary, $id];
            }
        }

        if ($db->query($sql, $params)) {
            $message = 'Kullanıcı başarıyla güncellendi!';
            $messageType = 'success';
        } else {
            $message = 'Kullanıcı güncellenirken hata oluştu!';
            $messageType = 'error';
        }
    }
    skipEdit:
}

// Kullanıcı Silme/Deaktive Etme (Sadece Admin)
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id']) && Auth::isAdmin()) {
    $id = $_GET['id'];
    $sql = "UPDATE users SET is_active = 0 WHERE id = ?";

    if ($db->query($sql, [$id])) {
        $message = 'Kullanıcı başarıyla deaktive edildi!';
        $messageType = 'success';
    } else {
        $message = 'Kullanıcı deaktive edilirken hata oluştu!';
        $messageType = 'error';
    }
}

// Kullanıcı Aktivasyon (Sadece Admin)
if (isset($_GET['action']) && $_GET['action'] === 'activate' && isset($_GET['id']) && Auth::isAdmin()) {
    $id = $_GET['id'];
    $sql = "UPDATE users SET is_active = 1 WHERE id = ?";

    if ($db->query($sql, [$id])) {
        $message = 'Kullanıcı başarıyla aktifleştirildi!';
        $messageType = 'success';
    } else {
        $message = 'Kullanıcı aktifleştirilirken hata oluştu!';
        $messageType = 'error';
    }
}

// Kullanıcıları Getir (Admin: hepsi, Personel: sadece kendisi)
if (Auth::isAdmin()) {
    $users = $db->fetchAll("SELECT * FROM users ORDER BY created_at DESC");
} else {
    $users = $db->fetchAll("SELECT * FROM users WHERE full_name = ? ORDER BY created_at DESC", [Auth::getFullName()]);
}

$isEmbedded = isset($_GET['embed']) && $_GET['embed'] == '1';
if (!$isEmbedded) {
    include 'includes/header.php';
}
?>

<style>
    /* Temel Stiller */
    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background: #f5f7fa;
        margin: 0;
        padding: 20px;
        color: #2c3e50;
    }

    * {
        box-sizing: border-box;
    }

    /* Buton Temel Stilleri */
    .btn {
        display: inline-block;
        padding: 10px 20px;
        border: none;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
        text-decoration: none;
        text-align: center;
    }

    .btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }

    .btn-primary:hover {
        background: linear-gradient(135deg, #5568d3 0%, #63418b 100%);
    }

    .btn-danger {
        background: #e74c3c;
        color: white;
    }

    .btn-danger:hover {
        background: #c0392b;
    }

    .message {
        padding: 15px 20px;
        border-radius: 10px;
        margin-bottom: 20px;
        font-weight: 500;
    }

    .message.success {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }

    .message.error {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }

    .card {
        background: white;
        border-radius: 15px;
        padding: 25px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
        margin-bottom: 30px;
    }

    .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 25px;
        padding-bottom: 15px;
        border-bottom: 2px solid #f0f0f0;
    }

    .card-title {
        font-size: 20px;
        font-weight: 700;
        color: #2c3e50;
    }

    .form-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 20px;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-group label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        color: #333;
        font-size: 14px;
    }

    .form-group input,
    .form-group select {
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e0e0e0;
        border-radius: 8px;
        font-size: 14px;
        transition: all 0.3s;
        outline: none;
    }

    .form-group input:focus,
    .form-group select:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    .btn-success {
        background: #27ae60;
        color: white;
    }

    .btn-success:hover {
        background: #229954;
    }

    table {
        width: 100%;
        border-collapse: collapse;
    }

    thead {
        background: #f8f9fa;
    }

    th {
        padding: 15px;
        text-align: left;
        font-weight: 600;
        color: #2c3e50;
        font-size: 14px;
        border-bottom: 2px solid #e0e0e0;
    }

    td {
        padding: 15px;
        border-bottom: 1px solid #f0f0f0;
        font-size: 14px;
    }

    tr:hover {
        background: #f8f9fa;
    }

    .badge {
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }

    .badge.admin {
        background: #667eea;
        color: white;
    }

    .badge.personel {
        background: #3498db;
        color: white;
    }

    .badge.active {
        background: #27ae60;
        color: white;
    }

    .badge.inactive {
        background: #e74c3c;
        color: white;
    }

    .actions {
        display: flex;
        gap: 10px;
    }

    .btn-sm {
        padding: 6px 12px;
        font-size: 13px;
    }

    .btn-warning {
        background: #f39c12;
        color: white;
    }

    .btn-warning:hover {
        background: #e67e22;
    }

    .btn-info {
        background: #3498db;
        color: white;
    }

    .btn-info:hover {
        background: #2980b9;
    }

    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 9999;
        align-items: center;
        justify-content: center;
    }

    .modal.active {
        display: flex;
    }

    .modal-content {
        background: white;
        border-radius: 15px;
        padding: 30px;
        max-width: 600px;
        width: 90%;
        max-height: 90vh;
        overflow-y: auto;
    }

    .modal-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
    }

    .modal-title {
        font-size: 22px;
        font-weight: 700;
        color: #2c3e50;
    }

    .close-modal {
        background: none;
        border: none;
        font-size: 28px;
        cursor: pointer;
        color: #999;
    }

    .close-modal:hover {
        color: #333;
    }
</style>

<?php if ($message): ?>
    <div class="message <?php echo $messageType; ?>"><?php echo htmlspecialchars($message); ?></div>
<?php endif; ?>

<?php if (Auth::isAdmin()): ?>
<!-- Yeni Kullanıcı Ekleme Formu -->
<div class="card">
    <div class="card-header">
        <h2 class="card-title">Yeni Hesap Ekle</h2>
    </div>
    <form method="POST" action="">
        <input type="hidden" name="action" value="add">
        <div class="form-grid">
            <div class="form-group">
                <label for="username">Kullanıcı Adı *</label>
                <input type="text" id="username" name="username" required>
            </div>
            <div class="form-group">
                <label for="password">Şifre *</label>
                <input type="password" id="password" name="password" required>
            </div>
            <div class="form-group">
                <label for="full_name">Ad Soyad *</label>
                <input type="text" id="full_name" name="full_name" required>
            </div>
            <div class="form-group">
                <label for="email">E-posta</label>
                <input type="email" id="email" name="email">
            </div>
            <div class="form-group">
                <label for="phone">Telefon</label>
                <input type="text" id="phone" name="phone">
            </div>
            <div class="form-group">
                <label for="extension">Dahili Numarası</label>
                <input type="text" id="extension" name="extension" placeholder="101 veya 101,102,103">
                <small style="color: #666; font-size: 12px;">Birden fazla dahili için virgül ile ayırın</small>
            </div>
            <div class="form-group">
                <label for="salary">Aylık Maaş (₺)</label>
                <input type="number" id="salary" name="salary" step="0.01" placeholder="Örn: 17000">
            </div>
            <div class="form-group">
                <label for="role">Rol *</label>
                <select id="role" name="role" required>
                    <option value="personel">Personel</option>
                    <option value="admin">Yönetici</option>
                </select>
            </div>
        </div>
        <button type="submit" class="btn btn-success">Kullanıcı Ekle</button>
    </form>
</div>
<?php endif; ?>

<!-- Kullanıcı Listesi -->
<div class="card">
    <div class="card-header">
        <h2 class="card-title">Hesap Listesi</h2>
    </div>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Kullanıcı Adı</th>
                <th>Ad Soyad</th>
                <th>E-posta</th>
                <th>Telefon</th>
                <th>Dahili</th>
                <th>Maaş</th>
                <th>Rol</th>
                <th>Durum</th>
                <th>İşlemler</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($users as $user): ?>
            <tr>
                <td><?php echo $user['id']; ?></td>
                <td><?php echo htmlspecialchars($user['username']); ?></td>
                <td><?php echo htmlspecialchars($user['full_name']); ?></td>
                <td><?php echo htmlspecialchars($user['email'] ?? '-'); ?></td>
                <td><?php echo htmlspecialchars($user['phone'] ?? '-'); ?></td>
                <td><strong><?php echo htmlspecialchars($user['extension'] ?? '-'); ?></strong></td>
                <td><strong style="color: #27ae60;"><?php echo number_format($user['salary'] ?? 0, 0); ?> ₺</strong></td>
                <td>
                    <span class="badge <?php echo $user['role']; ?>">
                        <?php echo $user['role'] === 'admin' ? 'Yönetici' : 'Personel'; ?>
                    </span>
                </td>
                <td>
                    <span class="badge <?php echo $user['is_active'] ? 'active' : 'inactive'; ?>">
                        <?php echo $user['is_active'] ? 'Aktif' : 'Pasif'; ?>
                    </span>
                </td>
                <td>
                    <div class="actions">
                        <button onclick="editUser(<?php echo htmlspecialchars(json_encode($user)); ?>)" class="btn btn-warning btn-sm">Düzenle</button>
                        <?php if (Auth::isAdmin()): ?>
                            <?php if ($user['is_active']): ?>
                                <a href="?action=delete&id=<?php echo $user['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Bu kullanıcıyı deaktive etmek istediğinizden emin misiniz?')">Deaktive Et</a>
                            <?php else: ?>
                                <a href="?action=activate&id=<?php echo $user['id']; ?>" class="btn btn-info btn-sm">Aktifleştir</a>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Düzenleme Modalı -->
<div id="editModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">Kullanıcı Düzenle</h3>
            <button type="button" class="close-modal" onclick="closeEditModal()">&times;</button>
        </div>
        <form method="POST" action="">
            <input type="hidden" name="action" value="edit">
            <input type="hidden" name="id" id="edit_id">
            <div class="form-group">
                <label for="edit_username">Kullanıcı Adı *</label>
                <input type="text" id="edit_username" name="username" required>
            </div>
            <div class="form-group">
                <label for="edit_password">Yeni Şifre (Boş bırakılırsa değişmez)</label>
                <input type="password" id="edit_password" name="password">
            </div>
            <div class="form-group">
                <label for="edit_full_name">Ad Soyad *</label>
                <input type="text" id="edit_full_name" name="full_name" required>
            </div>
            <div class="form-group">
                <label for="edit_email">E-posta</label>
                <input type="email" id="edit_email" name="email">
            </div>
            <div class="form-group">
                <label for="edit_phone">Telefon</label>
                <input type="text" id="edit_phone" name="phone">
            </div>
            <div class="form-group">
                <label for="edit_extension">Dahili Numarası</label>
                <input type="text" id="edit_extension" name="extension" placeholder="101 veya 101,102,103">
                <small style="color: #666; font-size: 12px;">Birden fazla dahili için virgül ile ayırın</small>
            </div>
            <div class="form-group">
                <label for="edit_salary">Aylık Maaş (₺)</label>
                <input type="number" id="edit_salary" name="salary" step="0.01" placeholder="Örn: 17000">
            </div>
            <?php if (Auth::isAdmin()): ?>
            <div class="form-group">
                <label for="edit_role">Rol *</label>
                <select id="edit_role" name="role" required>
                    <option value="personel">Personel</option>
                    <option value="admin">Yönetici</option>
                </select>
            </div>
            <?php endif; ?>
            <button type="submit" class="btn btn-success">Güncelle</button>
            <button type="button" class="btn btn-danger" onclick="closeEditModal()">İptal</button>
        </form>
    </div>
</div>

<script>
function editUser(user) {
    document.getElementById('edit_id').value = user.id;
    document.getElementById('edit_username').value = user.username;
    document.getElementById('edit_full_name').value = user.full_name;
    document.getElementById('edit_email').value = user.email || '';
    document.getElementById('edit_phone').value = user.phone || '';
    document.getElementById('edit_extension').value = user.extension || '';
    document.getElementById('edit_salary').value = user.salary || '';

    // Rol alanı sadece admin için mevcut
    const roleField = document.getElementById('edit_role');
    if (roleField) {
        roleField.value = user.role;
    }

    document.getElementById('editModal').classList.add('active');
}

function closeEditModal() {
    document.getElementById('editModal').classList.remove('active');
}
</script>

<?php
if (!$isEmbedded) {
    include 'includes/footer.php';
}
?>
