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

Auth::requireLogin();

$pageTitle = 'Personel Listesi';
include 'includes/header.php';

$db = new Database();

// Maaş güncelleme işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_salary'])) {
    $userId = $_POST['user_id'];
    $salary = $_POST['salary'];

    $db->query("UPDATE users SET salary = ? WHERE id = ?", [$salary, $userId]);

    header('Location: personel_list.php?success=1');
    exit;
}

// Filtreler
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? 'all';

// Sorgu oluştur
$sql = "SELECT u.*,
        COUNT(DISTINCT ic.id) as incoming_calls_count,
        COUNT(DISTINCT oc.id) as outgoing_calls_count,
        COUNT(DISTINCT tc.id) as training_count
        FROM users u
        LEFT JOIN incoming_calls ic ON u.id = ic.user_id
        LEFT JOIN outgoing_calls oc ON u.id = oc.user_id
        LEFT JOIN training_completion tc ON u.full_name = tc.support_representative
        WHERE 1=1";

$params = [];

if (!empty($search)) {
    $sql .= " AND (u.full_name LIKE ? OR u.username LIKE ? OR u.email LIKE ? OR u.extension LIKE ?)";
    $searchTerm = "%$search%";
    $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm, $searchTerm]);
}

if ($status === 'active') {
    $sql .= " AND u.is_active = 1";
} elseif ($status === 'inactive') {
    $sql .= " AND u.is_active = 0";
}

$sql .= " GROUP BY u.id ORDER BY u.full_name ASC";

$personnel = $db->fetchAll($sql, $params);
?>

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

    .filters-form {
        display: grid;
        grid-template-columns: 2fr 1fr auto;
        gap: 15px;
        align-items: end;
    }

    .form-group {
        display: flex;
        flex-direction: column;
    }

    .form-group label {
        font-size: 13px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 8px;
    }

    .form-control {
        padding: 12px 15px;
        border: 2px solid #e0e0e0;
        border-radius: 8px;
        font-size: 14px;
        transition: all 0.3s;
    }

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

    .btn {
        padding: 12px 24px;
        border: none;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

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

    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    }

    .personnel-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
        gap: 20px;
    }

    .personnel-card {
        background: white;
        border-radius: 15px;
        padding: 25px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
        transition: all 0.3s;
        position: relative;
        overflow: hidden;
    }

    .personnel-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    }

    .personnel-header {
        display: flex;
        align-items: center;
        gap: 15px;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 2px solid #f0f0f0;
    }

    .personnel-avatar {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        font-weight: 700;
        color: white;
        flex-shrink: 0;
    }

    .personnel-info {
        flex: 1;
    }

    .personnel-name {
        font-size: 18px;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 5px;
    }

    .personnel-role {
        display: inline-block;
        padding: 4px 12px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 12px;
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
    }

    .personnel-role.personel {
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    }

    .personnel-details {
        margin-bottom: 20px;
    }

    .detail-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 8px 0;
        font-size: 14px;
        color: #555;
    }

    .detail-icon {
        font-size: 16px;
        width: 20px;
        text-align: center;
    }

    .personnel-stats {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 10px;
        padding-top: 15px;
        border-top: 2px solid #f0f0f0;
    }

    .stat-item {
        text-align: center;
    }

    .stat-value {
        font-size: 20px;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 3px;
    }

    .stat-label {
        font-size: 11px;
        color: #7f8c8d;
        text-transform: uppercase;
        font-weight: 600;
    }

    .status-badge {
        position: absolute;
        top: 15px;
        right: 15px;
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
    }

    .status-badge.active {
        background: #d4edda;
        color: #155724;
    }

    .status-badge.inactive {
        background: #f8d7da;
        color: #721c24;
    }

    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #95a5a6;
    }

    .empty-state-icon {
        font-size: 64px;
        margin-bottom: 20px;
        opacity: 0.5;
    }

    .empty-state-text {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 10px;
    }

    @media (max-width: 768px) {
        .filters-form {
            grid-template-columns: 1fr;
        }

        .personnel-grid {
            grid-template-columns: 1fr;
        }
    }
</style>

<!-- Filtreler -->
<div class="filters-card">
    <form method="GET" class="filters-form">
        <div class="form-group">
            <label>Ara (İsim, Kullanıcı Adı, E-posta, Dahili)</label>
            <input type="text" name="search" class="form-control" placeholder="Aramak için yazın..." value="<?php echo htmlspecialchars($search); ?>">
        </div>
        <div class="form-group">
            <label>Durum</label>
            <select name="status" class="form-control">
                <option value="all" <?php echo $status === 'all' ? 'selected' : ''; ?>>Tümü</option>
                <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Aktif</option>
                <option value="inactive" <?php echo $status === 'inactive' ? 'selected' : ''; ?>>Pasif</option>
            </select>
        </div>
        <button type="submit" class="btn btn-primary">🔍 Filtrele</button>
    </form>
</div>

<!-- Personel Kartları -->
<?php if (empty($personnel)): ?>
    <div class="empty-state">
        <div class="empty-state-icon">👥</div>
        <div class="empty-state-text">Personel Bulunamadı</div>
        <p>Arama kriterlerinize uygun personel bulunamadı.</p>
    </div>
<?php else: ?>
    <div class="personnel-grid">
        <?php foreach ($personnel as $person): ?>
            <div class="personnel-card">
                <span class="status-badge <?php echo $person['is_active'] ? 'active' : 'inactive'; ?>">
                    <?php echo $person['is_active'] ? 'Aktif' : 'Pasif'; ?>
                </span>

                <div class="personnel-header">
                    <div class="personnel-avatar">
                        <?php echo strtoupper(mb_substr($person['full_name'], 0, 1)); ?>
                    </div>
                    <div class="personnel-info">
                        <div class="personnel-name"><?php echo htmlspecialchars($person['full_name']); ?></div>
                        <span class="personnel-role <?php echo $person['role']; ?>">
                            <?php echo $person['role'] === 'admin' ? 'Yönetici' : 'Personel'; ?>
                        </span>
                    </div>
                </div>

                <div class="personnel-details">
                    <div class="detail-item">
                        <span class="detail-icon">👤</span>
                        <strong><?php echo htmlspecialchars($person['username']); ?></strong>
                    </div>
                    <?php if (!empty($person['email'])): ?>
                        <div class="detail-item">
                            <span class="detail-icon">📧</span>
                            <?php echo htmlspecialchars($person['email']); ?>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($person['phone'])): ?>
                        <div class="detail-item">
                            <span class="detail-icon">📱</span>
                            <?php echo htmlspecialchars($person['phone']); ?>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($person['extension'])): ?>
                        <div class="detail-item">
                            <span class="detail-icon">☎️</span>
                            Dahili: <?php echo htmlspecialchars($person['extension']); ?>
                        </div>
                    <?php endif; ?>
                    <div class="detail-item" style="background: rgba(102, 126, 234, 0.05); padding: 10px; border-radius: 8px; margin-top: 10px;">
                        <span class="detail-icon">💰</span>
                        <div style="flex: 1; display: flex; justify-content: space-between; align-items: center;">
                            <span><strong>Maaş:</strong> <?php echo number_format($person['salary'] ?? 0, 0); ?> ₺</span>
                            <button class="edit-salary-btn" data-user-id="<?php echo $person['id']; ?>"
                                    data-user-name="<?php echo htmlspecialchars($person['full_name']); ?>"
                                    data-current-salary="<?php echo $person['salary'] ?? 0; ?>"
                                    style="background: #667eea; color: white; border: none; padding: 5px 12px; border-radius: 5px; cursor: pointer; font-size: 12px; font-weight: 600;">
                                ✏️ Düzenle
                            </button>
                        </div>
                    </div>
                </div>

                <div class="personnel-stats">
                    <div class="stat-item">
                        <div class="stat-value"><?php echo $person['incoming_calls_count']; ?></div>
                        <div class="stat-label">Gelen</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?php echo $person['outgoing_calls_count']; ?></div>
                        <div class="stat-label">Giden</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?php echo $person['training_count']; ?></div>
                        <div class="stat-label">Eğitim</div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<!-- Maaş Düzenleme Modalı -->
<div id="salaryModal" style="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;">
    <div style="background: white; border-radius: 15px; padding: 30px; max-width: 400px; width: 90%; box-shadow: 0 10px 40px rgba(0,0,0,0.3);">
        <h3 style="margin: 0 0 20px 0; color: #2c3e50; font-size: 20px;">💰 Maaş Düzenle</h3>
        <form method="POST" action="">
            <input type="hidden" name="update_salary" value="1">
            <input type="hidden" name="user_id" id="modal-user-id">

            <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #2c3e50;">Personel</label>
                <input type="text" id="modal-user-name" readonly
                       style="width: 100%; padding: 12px; border: 2px solid #e0e0e0; border-radius: 8px; background: #f5f5f5; font-size: 14px;">
            </div>

            <div style="margin-bottom: 25px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #2c3e50;">Aylık Maaş (₺)</label>
                <input type="number" name="salary" id="modal-salary" step="0.01" required
                       style="width: 100%; padding: 12px; border: 2px solid #e0e0e0; border-radius: 8px; font-size: 14px;"
                       placeholder="Örn: 17000">
            </div>

            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                <button type="button" onclick="closeSalaryModal()"
                        style="padding: 12px 24px; border: 2px solid #e0e0e0; background: white; color: #666; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 14px;">
                    İptal
                </button>
                <button type="submit"
                        style="padding: 12px 24px; border: none; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 14px;">
                    💾 Kaydet
                </button>
            </div>
        </form>
    </div>
</div>

<?php if (isset($_GET['success'])): ?>
<div id="successMessage" style="position: fixed; top: 20px; right: 20px; background: #4CAF50; color: white; padding: 15px 25px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.2); z-index: 10000; font-weight: 600;">
    ✓ Maaş başarıyla güncellendi!
</div>
<script>
    setTimeout(function() {
        document.getElementById('successMessage').style.display = 'none';
    }, 3000);
</script>
<?php endif; ?>

<script>
function closeSalaryModal() {
    document.getElementById('salaryModal').style.display = 'none';
}

// Maaş düzenleme butonlarına tıklama olayı
document.querySelectorAll('.edit-salary-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const userId = this.dataset.userId;
        const userName = this.dataset.userName;
        const currentSalary = this.dataset.currentSalary;

        document.getElementById('modal-user-id').value = userId;
        document.getElementById('modal-user-name').value = userName;
        document.getElementById('modal-salary').value = currentSalary;

        document.getElementById('salaryModal').style.display = 'flex';
    });
});

// Modal dışına tıklandığında kapat
document.getElementById('salaryModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeSalaryModal();
    }
});
</script>

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