<?php
/**
 * Admin Müşteri Yönetimi - Liste (Veri Hatası Düzeltilmiş Sürüm)
 * Konum: /magaza/admin/musteri/index.php
 */

require_once '../../includes/db.php';
require_once '../../includes/functions.php';
require_once '../../includes/mail.php';
require_once '../../includes/sms.php';

adminCheck();

$mesaj = '';

// --- PHP İLETİŞİM MOTORU (Hata Düzeltildi: user_id artık gönderiliyor) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 1. SMS GÖNDERME
    if (isset($_POST['hizli_sms_gonder'])) {
        $u_id = $_POST['target_user_id']; // Modal'dan gelen müşteri ID'si
        $tel = $_POST['target_phone'];
        $sms_icerik = trim($_POST['sms_message']);
        
        if (!empty($sms_icerik)) {
            // DÜZELTME: 3. parametre olarak $u_id eklendi
            sms_send_simple($tel, $sms_icerik, $u_id); 
            $mesaj = "<div class='alert alert-success shadow-sm alert-dismissible fade show'><i class='bi bi-check-circle me-2'></i> SMS başarıyla gönderildi ve günlüğe işlendi!<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
        }
    }
    // 2. EMAIL GÖNDERME
    if (isset($_POST['hizli_mail_gonder'])) {
        $u_id = $_POST['target_user_id']; // Modal'dan gelen müşteri ID'si
        $email = $_POST['target_email'];
        $konu = trim($_POST['mail_subject']);
        $mail_icerik = nl2br(trim($_POST['mail_message']));
        
        if (!empty($mail_icerik)) {
            // DÜZELTME: 4. parametre olarak $u_id eklendi
            sendSystemMail($email, $konu, $mail_icerik, $u_id);
            $mesaj = "<div class='alert alert-success shadow-sm alert-dismissible fade show'><i class='bi bi-envelope-check me-2'></i> E-posta başarıyla gönderildi ve günlüğe işlendi!<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
        }
    }
}

// --- VERİ ÇEKME ---
$where_clauses = ["role = 'customer'"];
$params = [];
$arama = isset($_GET['q']) ? trim($_GET['q']) : '';
if ($arama !== '') {
    $where_clauses[] = "(name LIKE ? OR surname LIKE ? OR email LIKE ? OR phone LIKE ?)";
    $val = "%$arama%";
    $params = array_merge($params, [$val, $val, $val, $val]);
}
$where_sql = "WHERE " . implode(" AND ", $where_clauses);
$sql = "SELECT u.*, 
    (SELECT COUNT(id) FROM orders WHERE user_id = u.id AND status != 'cancelled') as total_orders,
    (SELECT SUM(total_amount) FROM orders WHERE user_id = u.id AND status = 'completed') as total_spent
    FROM users u $where_sql ORDER BY u.id DESC";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$musteriler = $stmt->fetchAll();

require_once '../header.php';
?>

<div class="row mb-4 align-items-center text-dark">
    <div class="col-md-6">
        <h2 class="fw-bold mb-0"><i class="bi bi-people-fill text-primary me-2"></i>Müşteri Yönetimi</h2>
    </div>
</div>

<?= $mesaj; ?>

<div class="card shadow-sm border-0 mb-4">
    <div class="card-body bg-light rounded-3 p-4">
        <form action="index.php" method="GET" class="row g-2">
            <div class="col-md-10">
                <input type="text" name="q" class="form-control border-0 shadow-sm" value="<?= htmlspecialchars($arama) ?>" placeholder="Müşteri ara...">
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100 fw-bold shadow">Filtrele</button>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm border-0 mb-5 text-dark">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-dark">
                    <tr>
                        <th class="ps-3">ID</th>
                        <th>Müşteri</th>
                        <th class="text-center">Hızlı İletişim</th>
                        <th class="text-center">Sipariş / Harcama</th>
                        <th class="text-center">Durum</th>
                        <th class="text-end pe-3">İşlemler</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($musteriler): foreach ($musteriler as $m): ?>
                    <tr>
                        <td class="ps-3 text-muted">#<?= $m['id'] ?></td>
                        <td>
                            <div class="fw-bold"><?= htmlspecialchars($m['name'] . ' ' . $m['surname']) ?></div>
                            <small class="text-muted"><?= htmlspecialchars($m['email']) ?></small>
                        </td>
                        <td class="text-center">
                            <div class="btn-group shadow-sm">
                                <button type="button" class="btn btn-sm btn-white border" data-bs-toggle="modal" data-bs-target="#mailModal<?= $m['id'] ?>" title="E-posta Gönder">
                                    <i class="bi bi-envelope-at-fill text-primary"></i>
                                </button>
                                
                                <?php if($m['phone']): ?>
                                    <button type="button" class="btn btn-sm btn-white border" data-bs-toggle="modal" data-bs-target="#smsModal<?= $m['id'] ?>" title="SMS Gönder">
                                        <i class="bi bi-chat-left-dots-fill text-success"></i>
                                    </button>
                                    <a href="https://wa.me/<?= preg_replace('/[^0-9]/', '', $m['phone']) ?>" target="_blank" class="btn btn-sm btn-white border" title="WhatsApp">
                                        <i class="bi bi-whatsapp text-success"></i>
                                    </a>
                                <?php endif; ?>
                            </div>

                            <div class="modal fade" id="smsModal<?= $m['id'] ?>" tabindex="-1">
                                <div class="modal-dialog">
                                    <form action="index.php" method="POST" class="modal-content">
                                        <input type="hidden" name="target_user_id" value="<?= $m['id'] ?>">
                                        <input type="hidden" name="target_phone" value="<?= $m['phone'] ?>">
                                        <div class="modal-header bg-success text-white">
                                            <h5 class="modal-title fw-bold">SMS Gönder: <?= $m['name'] ?></h5>
                                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                        </div>
                                        <div class="modal-body text-start">
                                            <textarea name="sms_message" class="form-control" rows="4" placeholder="Mesajınız..." required></textarea>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="submit" name="hizli_sms_gonder" class="btn btn-success fw-bold">SMS Gönder ve Logla</button>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <div class="modal fade" id="mailModal<?= $m['id'] ?>" tabindex="-1">
                                <div class="modal-dialog">
                                    <form action="index.php" method="POST" class="modal-content">
                                        <input type="hidden" name="target_user_id" value="<?= $m['id'] ?>">
                                        <input type="hidden" name="target_email" value="<?= $m['email'] ?>">
                                        <div class="modal-header bg-primary text-white">
                                            <h5 class="modal-title fw-bold">Email Gönder: <?= $m['name'] ?></h5>
                                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                        </div>
                                        <div class="modal-body text-start">
                                            <input type="text" name="mail_subject" class="form-control mb-3" placeholder="Konu" required>
                                            <textarea name="mail_message" class="form-control" rows="6" placeholder="Mesajınız..." required></textarea>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="submit" name="hizli_mail_gonder" class="btn btn-primary fw-bold">E-posta Gönder ve Logla</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </td>

                        <td class="text-center small">
                            <span class="badge bg-light text-dark border"><?= $m['total_orders'] ?> Sipariş</span><br>
                            <span class="text-success fw-bold"><?= number_format($m['total_spent'] ?? 0, 2, ',', '.') ?> ₺</span>
                        </td>
                        <td class="text-center">
                            <span class="badge <?= $m['status'] == 1 ? 'bg-success' : 'bg-danger' ?> rounded-pill"><?= $m['status'] == 1 ? 'Aktif' : 'Pasif' ?></span>
                        </td>
                        <td class="text-end pe-3">
                            <div class="btn-group">
                                <a href="detay.php?id=<?= $m['id'] ?>" class="btn btn-sm btn-outline-dark" title="Detay"><i class="bi bi-eye-fill"></i></a>
                                <a href="duzenle.php?id=<?= $m['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-pencil-fill"></i></a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once '../footer.php'; ?>