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

Auth::requireAdmin();

$db = new Database();
$pageTitle = 'Kriter Yönetimi';

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

// Kriter Ekleme
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $name = trim($_POST['name'] ?? '');
    $code = trim($_POST['code'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $point_value = floatval($_POST['point_value'] ?? 0);
    $description = trim($_POST['description'] ?? '');
    $display_order = intval($_POST['display_order'] ?? 0);

    if (empty($name) || empty($code)) {
        $message = 'Kriter adı ve kodu zorunludur!';
        $messageType = 'error';
    } else {
        $sql = "INSERT INTO criteria (name, code, category, point_value, description, display_order) VALUES (?, ?, ?, ?, ?, ?)";

        if ($db->query($sql, [$name, $code, $category, $point_value, $description, $display_order])) {
            $message = 'Kriter başarıyla eklendi!';
            $messageType = 'success';
        } else {
            $message = 'Kriter eklenirken hata oluştu!';
            $messageType = 'error';
        }
    }
}

// Kriter Güncelleme
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit') {
    $id = $_POST['id'] ?? 0;
    $name = trim($_POST['name'] ?? '');
    $code = trim($_POST['code'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $point_value = floatval($_POST['point_value'] ?? 0);
    $description = trim($_POST['description'] ?? '');
    $display_order = intval($_POST['display_order'] ?? 0);

    if (empty($name) || empty($code)) {
        $message = 'Kriter adı ve kodu zorunludur!';
        $messageType = 'error';
    } else {
        $sql = "UPDATE criteria SET name = ?, code = ?, category = ?, point_value = ?, description = ?, display_order = ? WHERE id = ?";

        if ($db->query($sql, [$name, $code, $category, $point_value, $description, $display_order, $id])) {
            $message = 'Kriter başarıyla güncellendi!';
            $messageType = 'success';
        } else {
            $message = 'Kriter güncellenirken hata oluştu!';
            $messageType = 'error';
        }
    }
}

// Kriter Silme/Deaktive Etme
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $id = $_GET['id'];
    $sql = "UPDATE criteria SET is_active = 0 WHERE id = ?";

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

// Kriter Aktivasyon
if (isset($_GET['action']) && $_GET['action'] === 'activate' && isset($_GET['id'])) {
    $id = $_GET['id'];
    $sql = "UPDATE criteria SET is_active = 1 WHERE id = ?";

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

// Tüm Kriterleri Getir
$criteria = $db->fetchAll("SELECT * FROM criteria ORDER BY category ASC, display_order ASC, name ASC");

// Kategorileri grupla
$categorizedCriteria = [];
foreach ($criteria as $criterion) {
    $cat = $criterion['category'] ?? 'Genel';
    if (!isset($categorizedCriteria[$cat])) {
        $categorizedCriteria[$cat] = [];
    }
    $categorizedCriteria[$cat][] = $criterion;
}

$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,
    .form-group textarea {
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e0e0e0;
        border-radius: 8px;
        font-size: 14px;
        transition: all 0.3s;
        outline: none;
    }

    .form-group textarea {
        resize: vertical;
        min-height: 100px;
    }

    .form-group input:focus,
    .form-group select:focus,
    .form-group textarea: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.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;
    }

    .point-value {
        font-weight: 700;
        color: #667eea;
    }

    .info-box {
        background: #e8f4fd;
        border-left: 4px solid #3498db;
        padding: 15px 20px;
        border-radius: 8px;
        margin-bottom: 20px;
    }

    .info-box h4 {
        margin-bottom: 10px;
        color: #2c3e50;
    }

    .info-box p {
        font-size: 14px;
        color: #555;
        line-height: 1.6;
    }
</style>

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

<div class="info-box">
    <h4>Kriter Puanlama Sistemi Hakkında</h4>
    <p>
        Her kriter için belirlediğiniz puan değerleri, personel değerlendirmelerinde kullanılır.
        Örneğin "Gelen Arama Sayısı" için 0.15 puan belirlediğinizde, her gelen arama için personele 0.15 puan eklenir.
        Bu puanlar toplanarak personelin toplam performans puanı hesaplanır.
    </p>
</div>

<!-- Yeni Kriter Ekleme Formu -->
<div class="card">
    <div class="card-header">
        <h2 class="card-title">Yeni Kriter Ekle</h2>
    </div>
    <form method="POST" action="">
        <input type="hidden" name="action" value="add">
        <div class="form-grid">
            <div class="form-group">
                <label for="name">Kriter Adı *</label>
                <input type="text" id="name" name="name" placeholder="Örn: Gelen Arama Sayısı" required>
            </div>
            <div class="form-group">
                <label for="code">Kriter Kodu *</label>
                <input type="text" id="code" name="code" placeholder="Örn: gelen_arama_sayisi" required>
            </div>
            <div class="form-group">
                <label for="category">Kategori</label>
                <input type="text" id="category" name="category" placeholder="Örn: Aramalar, Eğitim, Performans">
            </div>
            <div class="form-group">
                <label for="point_value">Puan Değeri *</label>
                <input type="number" id="point_value" name="point_value" step="0.01" min="0" placeholder="Örn: 0.15" required>
            </div>
            <div class="form-group">
                <label for="display_order">Gösterim Sırası</label>
                <input type="number" id="display_order" name="display_order" min="0" value="0">
            </div>
        </div>
        <div class="form-group">
            <label for="description">Açıklama</label>
            <textarea id="description" name="description" placeholder="Kriterin detaylı açıklaması..."></textarea>
        </div>
        <button type="submit" class="btn btn-success">Kriter Ekle</button>
    </form>
</div>

<!-- Kriter Listesi -->
<div class="card">
    <div class="card-header">
        <h2 class="card-title">Kriter Listesi</h2>
    </div>
    <?php foreach ($categorizedCriteria as $category => $categoryItems): ?>
        <div style="margin-top: 30px;">
            <h3 style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 20px; border-radius: 8px; font-size: 16px; margin-bottom: 15px;">
                📁 <?php echo htmlspecialchars($category); ?>
            </h3>
            <table>
                <thead>
                    <tr>
                        <th>Sıra</th>
                        <th>Kriter Adı</th>
                        <th>Kod</th>
                        <th>Puan Değeri</th>
                        <th>Açıklama</th>
                        <th>Durum</th>
                        <th>İşlemler</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($categoryItems as $criterion): ?>
                    <tr>
                        <td><?php echo $criterion['display_order']; ?></td>
                        <td><?php echo htmlspecialchars($criterion['name']); ?></td>
                        <td><code><?php echo htmlspecialchars($criterion['code']); ?></code></td>
                        <td><span class="point-value"><?php echo number_format($criterion['point_value'], 2); ?></span></td>
                        <td><?php echo htmlspecialchars(substr($criterion['description'] ?? '-', 0, 50)); ?></td>
                        <td>
                            <span class="badge <?php echo $criterion['is_active'] ? 'active' : 'inactive'; ?>">
                                <?php echo $criterion['is_active'] ? 'Aktif' : 'Pasif'; ?>
                            </span>
                        </td>
                        <td>
                            <div class="actions">
                                <button onclick="showHistory('<?php echo $criterion['code']; ?>', '<?php echo htmlspecialchars($criterion['name']); ?>')" class="btn btn-info btn-sm">Tarihçe</button>
                                <button onclick="editCriterion(<?php echo htmlspecialchars(json_encode($criterion)); ?>)" class="btn btn-warning btn-sm">Düzenle</button>
                                <?php if ($criterion['is_active']): ?>
                                    <a href="?action=delete&id=<?php echo $criterion['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Bu kriteri deaktive etmek istediğinizden emin misiniz?')">Deaktive Et</a>
                                <?php else: ?>
                                    <a href="?action=activate&id=<?php echo $criterion['id']; ?>" class="btn btn-info btn-sm">Aktifleştir</a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endforeach; ?>
</div>

<!-- Düzenleme Modalı -->
<div id="editModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">Kriter 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_name">Kriter Adı *</label>
                <input type="text" id="edit_name" name="name" required>
            </div>
            <div class="form-group">
                <label for="edit_code">Kriter Kodu *</label>
                <input type="text" id="edit_code" name="code" required>
            </div>
            <div class="form-group">
                <label for="edit_category">Kategori</label>
                <input type="text" id="edit_category" name="category" placeholder="Örn: Aramalar, Eğitim, Performans">
            </div>
            <div class="form-group">
                <label for="edit_point_value">Puan Değeri (Varsayılan) *</label>
                <input type="number" id="edit_point_value" name="point_value" step="0.01" min="0" required>
            </div>
            <div class="form-group">
                <label for="edit_display_order">Gösterim Sırası</label>
                <input type="number" id="edit_display_order" name="display_order" min="0">
            </div>
            <div class="form-group">
                <label for="edit_description">Açıklama</label>
                <textarea id="edit_description" name="description"></textarea>
            </div>
            <div class="info-box" style="margin-top: 15px;">
                <p><strong>Not:</strong> Buradan değiştirdiğiniz puan değeri sadece varsayılan değerdir.
                Belirli tarih aralıkları için farklı değerler kullanmak istiyorsanız "Tarihçe" butonuna tıklayın.</p>
            </div>
            <button type="submit" class="btn btn-success">Güncelle</button>
            <button type="button" class="btn btn-danger" onclick="closeEditModal()">İptal</button>
        </form>
    </div>
</div>

<!-- Tarihçe Modalı -->
<div id="historyModal" class="modal">
    <div class="modal-content" style="max-width: 900px;">
        <div class="modal-header">
            <h3 class="modal-title">Kriter Tarihçesi: <span id="history_criterion_name"></span></h3>
            <button type="button" class="close-modal" onclick="closeHistoryModal()">&times;</button>
        </div>

        <div class="info-box">
            <p><strong>Tarih Bazlı Değer Yönetimi:</strong> Belirli tarih aralıklarında farklı puan değerleri kullanabilirsiniz.
            Örneğin: Ocak-Şubat 2025 için 0.35, Mart 2025 ve sonrası için 0.40 gibi.</p>
        </div>

        <!-- Yeni Tarihçe Ekleme Formu -->
        <div style="background: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
            <h4 style="margin-bottom: 15px;">Yeni Tarih Aralığı Ekle</h4>
            <form id="addHistoryForm" onsubmit="addHistory(event)">
                <input type="hidden" id="history_criteria_code">
                <div class="form-grid" style="grid-template-columns: 1fr 1fr 1fr auto;">
                    <div class="form-group">
                        <label for="history_start_date">Başlangıç Tarihi *</label>
                        <input type="date" id="history_start_date" required>
                    </div>
                    <div class="form-group">
                        <label for="history_end_date">Bitiş Tarihi</label>
                        <input type="date" id="history_end_date">
                        <small style="color: #666;">Boş bırakırsanız süresiz olur</small>
                    </div>
                    <div class="form-group">
                        <label for="history_point_value">Puan Değeri *</label>
                        <input type="number" id="history_point_value" step="0.01" min="0" required>
                    </div>
                    <div class="form-group" style="display: flex; align-items: flex-end;">
                        <button type="submit" class="btn btn-success">Ekle</button>
                    </div>
                </div>
                <div class="form-group">
                    <label for="history_notes">Notlar</label>
                    <textarea id="history_notes" placeholder="Bu değişikliğin sebebi..." style="min-height: 60px;"></textarea>
                </div>
            </form>
        </div>

        <!-- Tarihçe Listesi -->
        <div id="historyList">
            <p style="text-align: center; color: #999;">Yükleniyor...</p>
        </div>
    </div>
</div>

<script>
function editCriterion(criterion) {
    document.getElementById('edit_id').value = criterion.id;
    document.getElementById('edit_name').value = criterion.name;
    document.getElementById('edit_code').value = criterion.code;
    document.getElementById('edit_category').value = criterion.category || '';
    document.getElementById('edit_point_value').value = criterion.point_value;
    document.getElementById('edit_display_order').value = criterion.display_order;
    document.getElementById('edit_description').value = criterion.description || '';
    document.getElementById('editModal').classList.add('active');
}

function closeEditModal() {
    document.getElementById('editModal').classList.remove('active');
}

// Tarihçe modalı fonksiyonları
function showHistory(criteriaCode, criteriaName) {
    document.getElementById('history_criterion_name').textContent = criteriaName;
    document.getElementById('history_criteria_code').value = criteriaCode;
    document.getElementById('historyModal').classList.add('active');
    loadHistory(criteriaCode);
}

function closeHistoryModal() {
    document.getElementById('historyModal').classList.remove('active');
    document.getElementById('addHistoryForm').reset();
}

async function loadHistory(criteriaCode) {
    const listDiv = document.getElementById('historyList');
    listDiv.innerHTML = '<p style="text-align: center; color: #999;">Yükleniyor...</p>';

    try {
        const response = await fetch(`criteria_history_api.php?action=list&criteria_code=${encodeURIComponent(criteriaCode)}`);
        const result = await response.json();

        if (!result.success) {
            listDiv.innerHTML = `<p style="color: #e74c3c; text-align: center;">${result.message}</p>`;
            return;
        }

        const history = result.data;

        if (history.length === 0) {
            listDiv.innerHTML = '<p style="text-align: center; color: #999;">Henüz tarihçe kaydı bulunmuyor. Yukarıdaki formu kullanarak ekleyebilirsiniz.</p>';
            return;
        }

        let html = '<table><thead><tr><th>Başlangıç</th><th>Bitiş</th><th>Puan Değeri</th><th>Notlar</th><th>Oluşturan</th><th>İşlemler</th></tr></thead><tbody>';

        history.forEach(item => {
            const endDateText = item.end_date ? item.end_date : '<span style="color: #27ae60; font-weight: 600;">Süresiz</span>';
            const notes = item.notes || '-';
            const creator = item.created_by_name || 'Bilinmiyor';

            html += `<tr>
                <td>${item.start_date}</td>
                <td>${endDateText}</td>
                <td><span class="point-value">${parseFloat(item.point_value).toFixed(2)}</span></td>
                <td style="max-width: 200px;">${notes}</td>
                <td>${creator}</td>
                <td>
                    <div class="actions">
                        <button onclick="deleteHistory(${item.id})" class="btn btn-danger btn-sm">Sil</button>
                    </div>
                </td>
            </tr>`;
        });

        html += '</tbody></table>';
        listDiv.innerHTML = html;
    } catch (error) {
        listDiv.innerHTML = '<p style="color: #e74c3c; text-align: center;">Tarihçe yüklenirken hata oluştu!</p>';
        console.error('Error:', error);
    }
}

async function addHistory(event) {
    event.preventDefault();

    const formData = new FormData();
    formData.append('action', 'add');
    formData.append('criteria_code', document.getElementById('history_criteria_code').value);
    formData.append('start_date', document.getElementById('history_start_date').value);
    formData.append('end_date', document.getElementById('history_end_date').value);
    formData.append('point_value', document.getElementById('history_point_value').value);
    formData.append('notes', document.getElementById('history_notes').value);

    try {
        const response = await fetch('criteria_history_api.php', {
            method: 'POST',
            body: formData
        });

        const result = await response.json();

        if (result.success) {
            alert(result.message);
            document.getElementById('addHistoryForm').reset();
            loadHistory(document.getElementById('history_criteria_code').value);
        } else {
            alert('Hata: ' + result.message);
        }
    } catch (error) {
        alert('İşlem sırasında hata oluştu!');
        console.error('Error:', error);
    }
}

async function deleteHistory(id) {
    if (!confirm('Bu tarihçe kaydını silmek istediğinizden emin misiniz?')) {
        return;
    }

    const formData = new FormData();
    formData.append('action', 'delete');
    formData.append('id', id);

    try {
        const response = await fetch('criteria_history_api.php', {
            method: 'POST',
            body: formData
        });

        const result = await response.json();

        if (result.success) {
            alert(result.message);
            loadHistory(document.getElementById('history_criteria_code').value);
        } else {
            alert('Hata: ' + result.message);
        }
    } catch (error) {
        alert('İşlem sırasında hata oluştu!');
        console.error('Error:', error);
    }
}
</script>

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