<?php
/**
 * Leads Management (Contact Forms)
 * Aegean Dominance Admin Panel
 */

session_start();
require_once __DIR__ . '/../config/config.php';

$auth = new Auth();
$auth->requireLogin();

$db = Database::getInstance();

// AJAX İşlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    header('Content-Type: application/json');
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';
    
    try {
        switch ($action) {
            case 'update_status':
                $id = (int)($input['id'] ?? 0);
                $status = $input['status'] ?? 'read';
                $db->execute("UPDATE contact_forms SET status = ? WHERE id = ?", [$status, $id]);
                echo json_encode(['success' => true, 'message' => 'Durum güncellendi.']);
                break;
                
            case 'delete':
                $id = (int)($input['id'] ?? 0);
                $db->execute("DELETE FROM contact_forms WHERE id = ?", [$id]);
                echo json_encode(['success' => true, 'message' => 'Başvuru silindi.']);
                break;
                
            case 'add_note':
                $id = (int)($input['id'] ?? 0);
                $note = trim($input['note'] ?? '');
                $db->execute("UPDATE contact_forms SET admin_note = ? WHERE id = ?", [$note, $id]);
                echo json_encode(['success' => true, 'message' => 'Not eklendi.']);
                break;
                
            default:
                echo json_encode(['success' => false, 'error' => 'Geçersiz işlem.']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// Filtre
$status = $_GET['status'] ?? '';
$where = $status ? "WHERE status = ?" : "";
$params = $status ? [$status] : [];

$leads = $db->fetchAll("SELECT * FROM contact_forms {$where} ORDER BY created_at DESC", $params);

$statusCounts = [
    'new' => $db->fetchColumn("SELECT COUNT(*) FROM contact_forms WHERE status = 'new'"),
    'read' => $db->fetchColumn("SELECT COUNT(*) FROM contact_forms WHERE status = 'read'"),
    'replied' => $db->fetchColumn("SELECT COUNT(*) FROM contact_forms WHERE status = 'replied'"),
    'closed' => $db->fetchColumn("SELECT COUNT(*) FROM contact_forms WHERE status = 'closed'")
];

include 'partials/header.php';
?>

<div class="p-6">
    <!-- Stats -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <a href="?status=new" class="glass-card rounded-xl p-4 <?= $status === 'new' ? 'ring-2 ring-gold' : '' ?>">
            <p class="text-white/60 text-sm">Yeni</p>
            <p class="text-2xl font-bold text-gold"><?= $statusCounts['new'] ?></p>
        </a>
        <a href="?status=read" class="glass-card rounded-xl p-4 <?= $status === 'read' ? 'ring-2 ring-blue-400' : '' ?>">
            <p class="text-white/60 text-sm">Okundu</p>
            <p class="text-2xl font-bold text-blue-400"><?= $statusCounts['read'] ?></p>
        </a>
        <a href="?status=replied" class="glass-card rounded-xl p-4 <?= $status === 'replied' ? 'ring-2 ring-green-400' : '' ?>">
            <p class="text-white/60 text-sm">Yanıtlandı</p>
            <p class="text-2xl font-bold text-green-400"><?= $statusCounts['replied'] ?></p>
        </a>
        <a href="?status=closed" class="glass-card rounded-xl p-4 <?= $status === 'closed' ? 'ring-2 ring-white/40' : '' ?>">
            <p class="text-white/60 text-sm">Kapatıldı</p>
            <p class="text-2xl font-bold text-white/40"><?= $statusCounts['closed'] ?></p>
        </a>
    </div>
    
    <!-- Clear Filter -->
    <?php if ($status): ?>
    <div class="mb-4">
        <a href="leads.php" class="text-gold text-sm hover:underline">← Tüm başvurular</a>
    </div>
    <?php endif; ?>
    
    <!-- Leads List -->
    <div class="space-y-4">
        <?php if (empty($leads)): ?>
        <div class="glass-card rounded-2xl p-12 text-center">
            <i data-lucide="inbox" class="w-16 h-16 mx-auto mb-4 text-white/20"></i>
            <p class="text-white/40">Henüz başvuru yok</p>
        </div>
        <?php else: ?>
        <?php foreach ($leads as $lead): ?>
        <div class="glass-card rounded-2xl p-6" data-id="<?= $lead['id'] ?>">
            <div class="flex flex-wrap items-start justify-between gap-4 mb-4">
                <div class="flex items-center gap-4">
                    <div class="w-12 h-12 rounded-full bg-gold/20 flex items-center justify-center">
                        <span class="text-gold font-bold text-lg"><?= strtoupper(mb_substr($lead['name'], 0, 1)) ?></span>
                    </div>
                    <div>
                        <h3 class="text-white font-semibold"><?= htmlspecialchars($lead['name']) ?></h3>
                        <p class="text-white/60 text-sm"><?= htmlspecialchars($lead['phone']) ?></p>
                        <?php if ($lead['email']): ?>
                        <p class="text-white/40 text-sm"><?= htmlspecialchars($lead['email']) ?></p>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="flex items-center gap-2">
                    <select onchange="updateStatus(<?= $lead['id'] ?>, this.value)" class="bg-dark-800 border border-white/10 rounded-lg px-3 py-1 text-sm text-white">
                        <option value="new" <?= $lead['status'] === 'new' ? 'selected' : '' ?>>Yeni</option>
                        <option value="read" <?= $lead['status'] === 'read' ? 'selected' : '' ?>>Okundu</option>
                        <option value="replied" <?= $lead['status'] === 'replied' ? 'selected' : '' ?>>Yanıtlandı</option>
                        <option value="closed" <?= $lead['status'] === 'closed' ? 'selected' : '' ?>>Kapatıldı</option>
                    </select>
                    <button onclick="deleteLead(<?= $lead['id'] ?>)" class="p-2 rounded-lg hover:bg-red-500/20 text-white/60 hover:text-red-400">
                        <i data-lucide="trash-2" class="w-4 h-4"></i>
                    </button>
                </div>
            </div>
            
            <?php if ($lead['service_type']): ?>
            <div class="mb-3">
                <span class="px-2 py-1 rounded bg-blue-500/20 text-blue-400 text-xs"><?= htmlspecialchars($lead['service_type']) ?></span>
            </div>
            <?php endif; ?>
            
            <?php if ($lead['message']): ?>
            <p class="text-white/70 mb-4"><?= nl2br(htmlspecialchars($lead['message'])) ?></p>
            <?php endif; ?>
            
            <div class="flex flex-wrap items-center justify-between gap-4 pt-4 border-t border-white/10">
                <div class="flex items-center gap-4 text-sm text-white/40">
                    <span><?= date('d.m.Y H:i', strtotime($lead['created_at'])) ?></span>
                    <span><?= htmlspecialchars($lead['ip_address']) ?></span>
                </div>
                <div class="flex gap-2">
                    <a href="tel:<?= $lead['phone'] ?>" class="bg-green-500 text-white py-1 px-3 rounded-lg text-sm flex items-center gap-1">
                        <i data-lucide="phone" class="w-4 h-4"></i>
                        Ara
                    </a>
                    <a href="https://wa.me/90<?= preg_replace('/\D/', '', $lead['phone']) ?>" target="_blank" class="bg-[#25D366] text-white py-1 px-3 rounded-lg text-sm flex items-center gap-1">
                        <i data-lucide="message-circle" class="w-4 h-4"></i>
                        WhatsApp
                    </a>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<script>
async function updateStatus(id, status) {
    const result = await apiRequest('leads.php', { action: 'update_status', id, status });
    if (result.success) showToast(result.message, 'success');
    else showToast(result.error, 'error');
}

async function deleteLead(id) {
    const confirmed = await confirmAction('Bu başvuruyu silmek istediğinize emin misiniz?');
    if (!confirmed) return;
    const result = await apiRequest('leads.php', { action: 'delete', id });
    if (result.success) { showToast(result.message, 'success'); location.reload(); }
    else showToast(result.error, 'error');
}
</script>

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