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

Auth::requireAdmin();

$pageTitle = 'Destek Mesajı Raporları';
include 'includes/header.php';

$db = new Database();
$message = '';
$messageType = '';

// Tüm aktif personeller
$personnelList = $db->fetchAll("SELECT id, full_name FROM users WHERE is_active = 1 ORDER BY full_name ASC");

// Toplu kayıt / tekil ekleme
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {

    // Toplu giriş (bir tarihe tüm personeller)
    if ($_POST['action'] === 'bulk_save') {
        $date = $_POST['bulk_date'] ?? '';
        $counts = $_POST['counts'] ?? [];
        $notes = $_POST['notes'] ?? [];

        if (empty($date)) {
            $message = 'Tarih seçilmesi zorunludur!';
            $messageType = 'error';
        } else {
            $saved = 0;
            $updated = 0;
            foreach ($counts as $userId => $count) {
                $userId = (int)$userId;
                $count  = (int)$count;
                $note   = trim($notes[$userId] ?? '');
                if ($count < 0) continue;

                $existing = $db->fetchOne(
                    "SELECT id FROM support_messages WHERE user_id = ? AND message_date = ?",
                    [$userId, $date]
                );

                if ($existing) {
                    $db->query(
                        "UPDATE support_messages SET message_count = ?, notes = ?, created_by = ? WHERE id = ?",
                        [$count, $note, Auth::getUserId(), $existing['id']]
                    );
                    $updated++;
                } else {
                    $db->query(
                        "INSERT INTO support_messages (user_id, message_date, message_count, notes, created_by) VALUES (?, ?, ?, ?, ?)",
                        [$userId, $date, $count, $note, Auth::getUserId()]
                    );
                    $saved++;
                }
            }
            $message = "Kayıt tamamlandı. Yeni: $saved, Güncellenen: $updated.";
            $messageType = 'success';
        }
    }

    // Tekil silme
    if ($_POST['action'] === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0 && $db->query("DELETE FROM support_messages WHERE id = ?", [$id])) {
            $message = 'Kayıt silindi.';
            $messageType = 'success';
        } else {
            $message = 'Silme işlemi başarısız.';
            $messageType = 'error';
        }
    }

    // Tekil düzenleme (modal'dan)
    if ($_POST['action'] === 'edit') {
        $id    = (int)($_POST['id'] ?? 0);
        $count = (int)($_POST['message_count'] ?? 0);
        $note  = trim($_POST['notes'] ?? '');
        $date  = $_POST['message_date'] ?? '';

        if ($id > 0 && !empty($date)) {
            $db->query(
                "UPDATE support_messages SET message_count = ?, notes = ?, message_date = ? WHERE id = ?",
                [$count, $note, $date, $id]
            );
            $message = 'Kayıt güncellendi.';
            $messageType = 'success';
        }
    }
}

// Filtre
$filterStart = $_GET['start_date'] ?? date('Y-m-01');
$filterEnd   = $_GET['end_date']   ?? date('Y-m-d');
$filterUser  = $_GET['user_id']    ?? '';

// Toplu giriş için varsayılan tarih (GET'ten veya bugün)
$bulkDate = $_GET['bulk_date'] ?? date('Y-m-d');

// Seçilen tarihteki mevcut kayıtları çek (toplu form için)
$existingForDate = [];
if ($bulkDate) {
    $rows = $db->fetchAll(
        "SELECT user_id, message_count, notes FROM support_messages WHERE message_date = ?",
        [$bulkDate]
    );
    foreach ($rows as $r) {
        $existingForDate[$r['user_id']] = $r;
    }
}

// Liste sorgusu
$listSql = "
    SELECT sm.id, sm.message_date, sm.message_count, sm.notes,
           u.full_name, u.id as user_id,
           cb.full_name as created_by_name
    FROM support_messages sm
    JOIN users u ON sm.user_id = u.id
    LEFT JOIN users cb ON sm.created_by = cb.id
    WHERE sm.message_date BETWEEN ? AND ?
";
$listParams = [$filterStart, $filterEnd];

if ($filterUser !== '') {
    $listSql .= " AND sm.user_id = ?";
    $listParams[] = (int)$filterUser;
}

$listSql .= " ORDER BY sm.message_date DESC, u.full_name ASC";
$records = $db->fetchAll($listSql, $listParams);

// Özet (toplam ve personel bazı)
$summarySql = "
    SELECT u.full_name, SUM(sm.message_count) as total,
           COUNT(*) as days, MAX(sm.message_count) as max_day
    FROM support_messages sm
    JOIN users u ON sm.user_id = u.id
    WHERE sm.message_date BETWEEN ? AND ?
";
$summaryParams = [$filterStart, $filterEnd];
if ($filterUser !== '') {
    $summarySql .= " AND sm.user_id = ?";
    $summaryParams[] = (int)$filterUser;
}
$summarySql .= " GROUP BY sm.user_id, u.full_name ORDER BY total DESC";
$summary = $db->fetchAll($summarySql, $summaryParams);

$grandTotal = array_sum(array_column($summary, 'total'));
?>

<style>
    .sm-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; }
    @media(max-width:900px){ .sm-grid { grid-template-columns: 1fr; } }

    .card {
        background: #fff;
        border-radius: 14px;
        padding: 24px;
        box-shadow: 0 2px 10px rgba(0,0,0,.07);
        margin-bottom: 24px;
    }
    .card-title {
        font-size: 17px;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 20px;
        padding-bottom: 12px;
        border-bottom: 2px solid #f0f0f0;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .form-group { margin-bottom: 16px; }
    .form-group label { display: block; font-weight: 600; font-size: 13px; color: #555; margin-bottom: 6px; }
    .form-control {
        width: 100%; padding: 10px 14px;
        border: 2px solid #e0e0e0; border-radius: 8px;
        font-size: 14px; outline: none; transition: border-color .2s;
    }
    .form-control:focus { border-color: #667eea; }

    /* Toplu giriş tablosu */
    .bulk-table { width: 100%; border-collapse: collapse; }
    .bulk-table th {
        background: #f8f9fa; padding: 11px 14px;
        font-size: 13px; font-weight: 600; color: #555;
        text-align: left; border-bottom: 2px solid #e8e8e8;
    }
    .bulk-table td { padding: 8px 14px; border-bottom: 1px solid #f2f2f2; }
    .bulk-table tr:hover td { background: #fafafa; }
    .bulk-table input[type="number"] {
        width: 90px; padding: 7px 10px;
        border: 2px solid #e0e0e0; border-radius: 7px;
        font-size: 14px; text-align: center;
        transition: border-color .2s;
    }
    .bulk-table input[type="number"]:focus { border-color: #667eea; outline: none; }
    .bulk-table input[type="text"] {
        width: 100%; padding: 7px 10px;
        border: 2px solid #e0e0e0; border-radius: 7px;
        font-size: 13px; transition: border-color .2s;
    }
    .bulk-table input[type="text"]:focus { border-color: #667eea; outline: none; }

    /* Liste tablosu */
    .list-table { width: 100%; border-collapse: collapse; }
    .list-table th {
        background: #f8f9fa; padding: 12px 16px;
        font-size: 13px; font-weight: 600; color: #2c3e50;
        text-align: left; border-bottom: 2px solid #e0e0e0;
    }
    .list-table td { padding: 12px 16px; border-bottom: 1px solid #f0f0f0; font-size: 14px; }
    .list-table tr:hover td { background: #f8f9fa; }

    .badge-count {
        display: inline-block; padding: 4px 12px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: #fff; border-radius: 20px; font-weight: 700; font-size: 13px;
    }

    /* Özet kartları */
    .summary-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 14px; margin-bottom: 24px; }
    .summary-card {
        background: #fff; border-radius: 12px; padding: 18px 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,.06); text-align: center;
    }
    .summary-card .s-name { font-size: 13px; color: #888; margin-bottom: 6px; }
    .summary-card .s-total { font-size: 26px; font-weight: 800; color: #667eea; }
    .summary-card .s-sub { font-size: 12px; color: #aaa; margin-top: 4px; }

    .grand-total-card {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: #fff; border-radius: 12px; padding: 20px 24px;
        display: flex; align-items: center; justify-content: space-between;
        margin-bottom: 24px; box-shadow: 0 4px 15px rgba(102,126,234,.35);
    }
    .grand-total-card .gt-label { font-size: 15px; font-weight: 600; opacity: .9; }
    .grand-total-card .gt-value { font-size: 34px; font-weight: 800; }

    /* Filtre */
    .filter-bar { display: flex; gap: 12px; flex-wrap: wrap; align-items: flex-end; margin-bottom: 20px; }
    .filter-bar .form-group { margin-bottom: 0; }
    .filter-bar label { font-size: 12px; }

    .btn {
        padding: 10px 18px; border: none; border-radius: 8px;
        font-size: 14px; font-weight: 600; cursor: pointer;
        transition: all .25s; text-decoration: none; display: inline-flex; align-items: center; gap: 6px;
    }
    .btn:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(0,0,0,.15); }
    .btn-primary { background: linear-gradient(135deg,#667eea,#764ba2); color:#fff; }
    .btn-success { background: #27ae60; color:#fff; }
    .btn-danger  { background: #e74c3c; color:#fff; }
    .btn-warning { background: #f39c12; color:#fff; }
    .btn-secondary { background: #95a5a6; color:#fff; }
    .btn-sm { padding: 6px 12px; font-size: 12px; }

    .msg { padding: 14px 18px; border-radius: 10px; margin-bottom: 20px; font-weight: 500; }
    .msg.success { background:#d4edda; color:#155724; border:1px solid #c3e6cb; }
    .msg.error   { background:#f8d7da; color:#721c24; border:1px solid #f5c6cb; }

    /* Modal */
    .modal { display:none; position:fixed; top:0;left:0;width:100%;height:100%; background:rgba(0,0,0,.5); z-index:9999; align-items:center; justify-content:center; }
    .modal.active { display:flex; }
    .modal-content { background:#fff; border-radius:14px; padding:30px; width:90%; max-width:480px; }
    .modal-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; }
    .modal-title { font-size:18px; font-weight:700; color:#2c3e50; }
    .close-modal { background:none; border:none; font-size:26px; cursor:pointer; color:#999; }

    .date-nav { display:flex; align-items:center; gap:10px; margin-bottom:16px; }
    .date-nav button { background:#f0f0f0; border:none; border-radius:8px; padding:7px 14px; cursor:pointer; font-size:14px; font-weight:600; }
    .date-nav button:hover { background:#e0e0e0; }
    .date-nav .current-date { font-size:16px; font-weight:700; color:#2c3e50; }

    .no-data { text-align:center; padding:40px; color:#aaa; font-size:15px; }
</style>

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

<div class="sm-grid">

    <!-- SOL: Toplu Veri Girişi -->
    <div>
        <div class="card">
            <div class="card-title">💬 Günlük Mesaj Sayısı Girişi</div>

            <!-- Tarih Navigasyonu -->
            <div class="date-nav">
                <?php
                    $prevDay = date('Y-m-d', strtotime($bulkDate . ' -1 day'));
                    $nextDay = date('Y-m-d', strtotime($bulkDate . ' +1 day'));
                    $today   = date('Y-m-d');
                ?>
                <button onclick="location.href='?bulk_date=<?php echo $prevDay; ?>&start_date=<?php echo $filterStart; ?>&end_date=<?php echo $filterEnd; ?><?php echo $filterUser ? '&user_id='.$filterUser : ''; ?>'">← Önceki</button>
                <span class="current-date">
                    <?php
                        $turkishMonths = [1=>'Ocak',2=>'Şubat',3=>'Mart',4=>'Nisan',5=>'Mayıs',6=>'Haziran',
                                          7=>'Temmuz',8=>'Ağustos',9=>'Eylül',10=>'Ekim',11=>'Kasım',12=>'Aralık'];
                        $bd = new DateTime($bulkDate);
                        echo $bd->format('d') . ' ' . $turkishMonths[(int)$bd->format('n')] . ' ' . $bd->format('Y');
                    ?>
                </span>
                <?php if ($bulkDate < $today): ?>
                <button onclick="location.href='?bulk_date=<?php echo $nextDay; ?>&start_date=<?php echo $filterStart; ?>&end_date=<?php echo $filterEnd; ?><?php echo $filterUser ? '&user_id='.$filterUser : ''; ?>'">Sonraki →</button>
                <?php endif; ?>
                <button onclick="location.href='?bulk_date=<?php echo $today; ?>&start_date=<?php echo $filterStart; ?>&end_date=<?php echo $filterEnd; ?><?php echo $filterUser ? '&user_id='.$filterUser : ''; ?>'" style="margin-left:auto;background:#667eea;color:white;">Bugün</button>
            </div>

            <form method="POST" action="">
                <input type="hidden" name="action" value="bulk_save">
                <input type="hidden" name="bulk_date" value="<?php echo htmlspecialchars($bulkDate); ?>">

                <!-- Tarih değiştirme -->
                <div class="form-group">
                    <label>Tarih</label>
                    <input type="date" name="bulk_date_change" class="form-control" value="<?php echo htmlspecialchars($bulkDate); ?>"
                        onchange="location.href='?bulk_date='+this.value+'&start_date=<?php echo $filterStart; ?>&end_date=<?php echo $filterEnd; ?><?php echo $filterUser ? '&user_id='.$filterUser : ''; ?>'" style="max-width:200px;">
                </div>

                <table class="bulk-table">
                    <thead>
                        <tr>
                            <th>Personel</th>
                            <th style="width:100px">Mesaj Sayısı</th>
                            <th>Not</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($personnelList as $person): ?>
                        <?php
                            $existing = $existingForDate[$person['id']] ?? null;
                            $existingCount = $existing ? (int)$existing['message_count'] : 0;
                            $existingNote  = $existing ? ($existing['notes'] ?? '') : '';
                        ?>
                        <tr>
                            <td>
                                <strong><?php echo htmlspecialchars($person['full_name']); ?></strong>
                                <?php if ($existing): ?>
                                    <span style="font-size:11px;color:#27ae60;margin-left:6px;">● kayıtlı</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <input type="number" name="counts[<?php echo $person['id']; ?>]"
                                    value="<?php echo $existingCount; ?>" min="0" max="9999">
                            </td>
                            <td>
                                <input type="text" name="notes[<?php echo $person['id']; ?>]"
                                    value="<?php echo htmlspecialchars($existingNote); ?>" placeholder="İsteğe bağlı...">
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <div style="margin-top:16px;">
                    <button type="submit" class="btn btn-success">💾 Kaydet</button>
                </div>
            </form>
        </div>
    </div>

    <!-- SAĞ: Özet + Liste -->
    <div>

        <!-- Özet -->
        <?php if (!empty($summary)): ?>
        <div class="grand-total-card">
            <div>
                <div class="gt-label">Toplam Cevaplanan Mesaj</div>
                <div style="font-size:12px;opacity:.7;"><?php echo htmlspecialchars($filterStart); ?> — <?php echo htmlspecialchars($filterEnd); ?></div>
            </div>
            <div class="gt-value"><?php echo number_format($grandTotal); ?></div>
        </div>

        <div class="summary-cards">
            <?php foreach ($summary as $s): ?>
            <div class="summary-card">
                <div class="s-name"><?php echo htmlspecialchars($s['full_name']); ?></div>
                <div class="s-total"><?php echo number_format($s['total']); ?></div>
                <div class="s-sub"><?php echo $s['days']; ?> gün · max <?php echo $s['max_day']; ?>/gün</div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- Filtreler -->
        <div class="card">
            <div class="card-title">📋 Kayıt Listesi</div>

            <form method="GET" action="">
                <input type="hidden" name="bulk_date" value="<?php echo htmlspecialchars($bulkDate); ?>">
                <div class="filter-bar">
                    <div class="form-group">
                        <label>Başlangıç</label>
                        <input type="date" name="start_date" class="form-control" value="<?php echo htmlspecialchars($filterStart); ?>" style="width:160px;">
                    </div>
                    <div class="form-group">
                        <label>Bitiş</label>
                        <input type="date" name="end_date" class="form-control" value="<?php echo htmlspecialchars($filterEnd); ?>" style="width:160px;">
                    </div>
                    <div class="form-group">
                        <label>Personel</label>
                        <select name="user_id" class="form-control" style="width:180px;">
                            <option value="">Tüm Personeller</option>
                            <?php foreach ($personnelList as $p): ?>
                            <option value="<?php echo $p['id']; ?>" <?php echo ($filterUser == $p['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($p['full_name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary">Filtrele</button>
                    <a href="?bulk_date=<?php echo date('Y-m-d'); ?>" class="btn btn-secondary">Sıfırla</a>
                </div>
            </form>

            <?php if (empty($records)): ?>
                <div class="no-data">Bu tarih aralığında kayıt bulunamadı.</div>
            <?php else: ?>
            <div style="overflow-x:auto;">
                <table class="list-table">
                    <thead>
                        <tr>
                            <th>Tarih</th>
                            <th>Personel</th>
                            <th>Mesaj Sayısı</th>
                            <th>Not</th>
                            <th>İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($records as $rec): ?>
                        <tr>
                            <td><?php
                                $rd = new DateTime($rec['message_date']);
                                echo $rd->format('d') . ' ' . $turkishMonths[(int)$rd->format('n')] . ' ' . $rd->format('Y');
                            ?></td>
                            <td><?php echo htmlspecialchars($rec['full_name']); ?></td>
                            <td><span class="badge-count"><?php echo $rec['message_count']; ?></span></td>
                            <td style="color:#888;font-size:13px;"><?php echo htmlspecialchars($rec['notes'] ?? '-'); ?></td>
                            <td>
                                <div style="display:flex;gap:6px;">
                                    <button onclick="openEdit(<?php echo htmlspecialchars(json_encode($rec)); ?>)" class="btn btn-warning btn-sm">Düzenle</button>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Bu kaydı silmek istediğinizden emin misiniz?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo $rec['id']; ?>">
                                        <input type="hidden" name="bulk_date" value="<?php echo htmlspecialchars($bulkDate); ?>">
                                        <button type="submit" class="btn btn-danger btn-sm">Sil</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Düzenleme Modalı -->
<div id="editModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <span class="modal-title">Kaydı Düzenle</span>
            <button class="close-modal" onclick="closeModal()">×</button>
        </div>
        <form method="POST" action="">
            <input type="hidden" name="action" value="edit">
            <input type="hidden" name="id" id="edit_id">
            <input type="hidden" name="bulk_date" value="<?php echo htmlspecialchars($bulkDate); ?>">
            <input type="hidden" name="start_date" value="<?php echo htmlspecialchars($filterStart); ?>">
            <input type="hidden" name="end_date" value="<?php echo htmlspecialchars($filterEnd); ?>">
            <?php if ($filterUser): ?><input type="hidden" name="user_id" value="<?php echo $filterUser; ?>"><?php endif; ?>

            <div class="form-group">
                <label>Personel</label>
                <input type="text" id="edit_person" class="form-control" disabled>
            </div>
            <div class="form-group">
                <label>Tarih</label>
                <input type="date" name="message_date" id="edit_date" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Mesaj Sayısı</label>
                <input type="number" name="message_count" id="edit_count" class="form-control" min="0" required>
            </div>
            <div class="form-group">
                <label>Not</label>
                <input type="text" name="notes" id="edit_notes" class="form-control" placeholder="İsteğe bağlı...">
            </div>
            <div style="display:flex;gap:10px;margin-top:20px;">
                <button type="submit" class="btn btn-success">💾 Güncelle</button>
                <button type="button" class="btn btn-secondary" onclick="closeModal()">İptal</button>
            </div>
        </form>
    </div>
</div>

<script>
function openEdit(rec) {
    document.getElementById('edit_id').value    = rec.id;
    document.getElementById('edit_person').value = rec.full_name;
    document.getElementById('edit_date').value   = rec.message_date;
    document.getElementById('edit_count').value  = rec.message_count;
    document.getElementById('edit_notes').value  = rec.notes || '';
    document.getElementById('editModal').classList.add('active');
}
function closeModal() {
    document.getElementById('editModal').classList.remove('active');
}
// Modal dışına tıklayınca kapat
document.getElementById('editModal').addEventListener('click', function(e) {
    if (e.target === this) closeModal();
});
</script>

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