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

Auth::requireAdmin();

$db = new Database();
$pageTitle = 'Gelen Aramalar - Kayıt Düzeltme (E=cevaplanan, F=cevapsız)';
include 'includes/header.php';

// Kullanıcı listesi
$users = $db->fetchAll("SELECT id, full_name, username, extension FROM users WHERE is_active = 1 ORDER BY full_name");

$selectedUserId = isset($_REQUEST['user_id']) ? trim($_REQUEST['user_id']) : '';
$startDate = isset($_REQUEST['start_date']) ? trim($_REQUEST['start_date']) : '';
$endDate = isset($_REQUEST['end_date']) ? trim($_REQUEST['end_date']) : '';
$applyFix = ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['apply_fix']));

// Tarih aralığı normalize
function normalizeDate($d) {
    if (!$d) return '';
    $d = trim($d);
    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $d)) return $d;
    $ts = strtotime($d);
    return $ts ? date('Y-m-d', $ts) : '';
}

$startDate = normalizeDate($startDate);
$endDate = normalizeDate($endDate);

$message = '';
$messageType = '';
$rows = [];

if ($selectedUserId) {
    $params = [$selectedUserId];
    $where = 'user_id = ?';
    if ($startDate) { $where .= ' AND call_date >= ?'; $params[] = $startDate; }
    if ($endDate)   { $where .= ' AND call_date <= ?'; $params[] = $endDate; }

    if ($applyFix) {
        // Uygulama: answered_count = old_unanswered_count, unanswered_count = call_count - old_unanswered_count
        // answer_percentage = new_answered / call_count
        $sql = "UPDATE incoming_calls
                SET answered_count = unanswered_count,
                    unanswered_count = GREATEST(call_count - unanswered_count, 0),
                    answer_percentage = CASE WHEN call_count > 0 THEN ROUND((unanswered_count / call_count) * 100, 2) ELSE 0 END
                WHERE $where";
        $db->query($sql, $params);
        $message = 'Düzeltme uygulandı.';
        $messageType = 'success';
    }

    // Önizleme: mevcut değerler ve uygulanınca olacak değerler
    $rows = $db->fetchAll(
        "SELECT id, call_date, call_count, answered_count, unanswered_count
         FROM incoming_calls WHERE $where ORDER BY call_date DESC",
        $params
    );
}
?>

<style>
    .card { background: #fff; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,.06); margin-bottom: 20px; }
    .message { padding: 12px 16px; border-radius: 8px; margin-bottom: 15px; font-size: 14px; }
    .message.success { background:#d4edda; border:1px solid #c3e6cb; color:#155724; }
    .message.error { background:#f8d7da; border:1px solid #f5c6cb; color:#721c24; }
    .message.info { background:#e8f4fd; border:1px solid #cfe8fc; color:#0b5cad; }
    table { width: 100%; border-collapse: collapse; }
    th, td { padding: 8px 10px; border-bottom: 1px solid #f0f0f0; font-size: 14px; }
    th { text-align: left; color:#2c3e50; }
    .muted { color:#7f8c8d; font-size:12px; }
    .actions { display:flex; gap:10px; }
    .btn { display:inline-flex; align-items:center; gap:8px; padding:10px 14px; border-radius:8px; text-decoration:none; border:none; cursor:pointer; }
    .btn-primary { background:#667eea; color:#fff; }
    .btn-danger { background:#e74c3c; color:#fff; }
    .btn-secondary { background:#f1f3f5; color:#2c3e50; }
    .grid { display:grid; grid-template-columns: repeat(auto-fit,minmax(220px,1fr)); gap:16px; }
    input, select { width:100%; padding:10px 12px; border:2px solid #e0e0e0; border-radius:8px; }
    label { display:block; margin-bottom:6px; font-weight:600; color:#333; font-size:13px; }
</style>

<div class="card">
    <h2 style="margin:0 0 12px 0;">Gelen Aramalar Kayıt Düzeltme</h2>
    <p class="muted">E sütunu (Cevaplanan) ve F sütunu (Cevapsız) ters okunan geçmiş kayıtları düzeltmek için kullanın. Önce önizleme yapın.</p>

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

    <form method="get" class="grid" style="margin-bottom: 12px;">
        <div>
            <label>Personel</label>
            <select name="user_id" required>
                <option value="">Seçin…</option>
                <?php foreach ($users as $u): ?>
                    <option value="<?php echo $u['id']; ?>" <?php echo ($selectedUserId==$u['id']?'selected':''); ?>>
                        <?php echo htmlspecialchars($u['full_name'] . ' ('.$u['username'].') Dahili: '.$u['extension']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>Başlangıç Tarih (opsiyonel)</label>
            <input type="date" name="start_date" value="<?php echo htmlspecialchars($startDate); ?>">
        </div>
        <div>
            <label>Bitiş Tarih (opsiyonel)</label>
            <input type="date" name="end_date" value="<?php echo htmlspecialchars($endDate); ?>">
        </div>
        <div style="display:flex; align-items:flex-end;">
            <button class="btn btn-primary" type="submit">Önizle</button>
        </div>
    </form>

    <?php if ($rows && !$applyFix): ?>
        <form method="post">
            <input type="hidden" name="user_id" value="<?php echo htmlspecialchars($selectedUserId); ?>">
            <input type="hidden" name="start_date" value="<?php echo htmlspecialchars($startDate); ?>">
            <input type="hidden" name="end_date" value="<?php echo htmlspecialchars($endDate); ?>">

            <div class="message info">Aşağıda yeni değerlere dönüştürme önizlemesi yer alıyor. Uygula dediğinizde tüm listelenen satırlar güncellenecek.</div>

            <table>
                <thead>
                    <tr>
                        <th>Tarih</th>
                        <th>Toplam</th>
                        <th>Eski Cevaplanan</th>
                        <th>Eski Cevapsız</th>
                        <th>Yeni Cevaplanan</th>
                        <th>Yeni Cevapsız</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($rows as $r):
                        $newAnswered = (int)$r['unanswered_count'];
                        $newUnanswered = max(((int)$r['call_count']) - ((int)$r['unanswered_count']), 0);
                    ?>
                        <tr>
                            <td><?php echo htmlspecialchars($r['call_date']); ?></td>
                            <td><strong><?php echo (int)$r['call_count']; ?></strong></td>
                            <td><?php echo (int)$r['answered_count']; ?></td>
                            <td><?php echo (int)$r['unanswered_count']; ?></td>
                            <td style="color:#27ae60;"><strong><?php echo $newAnswered; ?></strong></td>
                            <td style="color:#e74c3c;"><strong><?php echo $newUnanswered; ?></strong></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <div class="actions" style="margin-top:12px;">
                <a class="btn btn-secondary" href="<?php echo strtok($_SERVER['REQUEST_URI'], '?'); ?>">Temizle</a>
                <button class="btn btn-danger" type="submit" name="apply_fix" value="1" onclick="return confirm('Listelenen satırlara düzeltmeyi uygulamak istediğinize emin misiniz?');">Düzeltmeyi Uygula</button>
            </div>
        </form>
    <?php elseif ($selectedUserId && !$rows): ?>
        <div class="message info">Seçili filtrelere göre kayıt bulunamadı.</div>
    <?php endif; ?>
</div>

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

