<?php
/**
 * Admin Müşteri Düzenleme Sayfası
 * Konum: /magaza/admin/musteri/duzenle.php
 */

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

/**
 * GÜVENLİK KONTROLÜ
 */
adminCheck();

$mesaj = '';

// 1. URL'den gelen ID'yi kontrol et
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: index.php");
    exit;
}
$musteri_id = (int)$_GET['id'];

// --- GÜNCELLEME İŞLEMİ ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['musteri_guncelle'])) {
    $name    = trim($_POST['name']);
    $surname = trim($_POST['surname']);
    $email   = trim($_POST['email']);
    $phone   = trim($_POST['phone']);
    $status  = (int)$_POST['status'];

    if (empty($name) || empty($surname) || empty($email)) {
        $mesaj = "<div class='alert alert-warning shadow-sm'><i class='bi bi-exclamation-triangle me-2'></i>Lütfen zorunlu alanları (Ad, Soyad, E-posta) doldurun.</div>";
    } else {
        try {
            // E-posta çakışma kontrolü (Kendi ID'si hariç)
            $check = $db->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
            $check->execute([$email, $musteri_id]);
            
            if ($check->rowCount() > 0) {
                $mesaj = "<div class='alert alert-danger shadow-sm'>Bu e-posta adresi başka bir kullanıcı tarafından kullanılıyor.</div>";
            } else {
                $sql = "UPDATE users SET name = ?, surname = ?, email = ?, phone = ?, status = ? WHERE id = ? AND role = 'customer'";
                $stmt = $db->prepare($sql);
                $stmt->execute([$name, $surname, $email, $phone, $status, $musteri_id]);
                
                $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle-fill me-2'></i> Müşteri bilgileri başarıyla güncellendi. <a href='index.php' class='fw-bold text-decoration-none'>Listeye Dön</a></div>";
            }
        } catch (Exception $e) {
            $mesaj = "<div class='alert alert-danger shadow-sm'>Hata: " . $e->getMessage() . "</div>";
        }
    }
}

// --- MÜŞTERİ VERİSİNİ ÇEK ---
$stmt = $db->prepare("SELECT * FROM users WHERE id = ? AND role = 'customer'");
$stmt->execute([$musteri_id]);
$m = $stmt->fetch();

if (!$m) {
    die("<div class='alert alert-danger m-4'>Müşteri bulunamadı! <a href='index.php'>Geri Dön</a></div>");
}

// YENİ YAPI: Bir üst klasördeki header.php
require_once '../header.php';
?>

<div class="row mb-4 align-items-center">
    <div class="col-md-6">
        <h2 class="fw-bold mb-0 text-dark">
            <a href="index.php" class="btn btn-sm btn-outline-secondary me-3 shadow-sm"><i class="bi bi-arrow-left"></i> Geri</a>
            Müşteri Düzenle: <span class="text-primary"><?= htmlspecialchars($m['name'] . ' ' . $m['surname']) ?></span>
        </h2>
    </div>
</div>

<?= $mesaj; ?>

<div class="row">
    <div class="col-lg-8">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-dark text-white py-3">
                <h5 class="card-title mb-0 fw-bold small text-uppercase"><i class="bi bi-person-gear me-2"></i>Profil Bilgileri</h5>
            </div>
            <div class="card-body p-4">
                <form action="duzenle.php?id=<?= $musteri_id ?>" method="POST">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">Adı *</label>
                            <input type="text" name="name" class="form-control border-2" value="<?= htmlspecialchars($m['name']) ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">Soyadı *</label>
                            <input type="text" name="surname" class="form-control border-2" value="<?= htmlspecialchars($m['surname']) ?>" required>
                        </div>
                    </div>

                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">E-Posta Adresi *</label>
                            <input type="email" name="email" class="form-control border-2" value="<?= htmlspecialchars($m['email']) ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">Telefon</label>
                            <input type="text" name="phone" class="form-control border-2" value="<?= htmlspecialchars($m['phone']) ?>">
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Hesap Durumu</label>
                        <select name="status" class="form-select border-2 fw-bold">
                            <option value="1" <?= $m['status'] == 1 ? 'selected' : '' ?> class="text-success">AKTİF (Giriş Yapabilir)</option>
                            <option value="0" <?= $m['status'] == 0 ? 'selected' : '' ?> class="text-danger">ENGELLİ (Giriş Yapamaz)</option>
                        </select>
                    </div>

                    <hr>

                    <div class="d-flex justify-content-between align-items-center mt-4">
                        <span class="text-muted small">Kayıt Tarihi: <?= date('d.m.Y H:i', strtotime($m['created_at'])) ?></span>
                        <button type="submit" name="musteri_guncelle" class="btn btn-primary px-5 fw-bold shadow">
                            <i class="bi bi-save me-2"></i> DEĞİŞİKLİKLERİ KAYDET
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card shadow-sm border-0 border-top border-4 border-info mb-4">
            <div class="card-body p-4 text-center">
                <div class="mb-3">
                    <i class="bi bi-wallet2 fs-1 text-info"></i>
                </div>
                <h6 class="text-uppercase fw-bold text-muted small">Toplam Harcama</h6>
                <?php
                $spent = $db->prepare("SELECT SUM(total_amount) FROM orders WHERE user_id = ? AND status = 'completed'");
                $spent->execute([$musteri_id]);
                $total_spent = $spent->fetchColumn() ?: 0;
                ?>
                <h3 class="fw-bold text-dark"><?= number_format($total_spent, 2, ',', '.') ?> ₺</h3>
            </div>
        </div>

        <div class="card shadow-sm border-0 border-top border-4 border-primary mb-4">
            <div class="card-body p-4 text-center">
                <div class="mb-3">
                    <i class="bi bi-cart-check fs-1 text-primary"></i>
                </div>
                <h6 class="text-uppercase fw-bold text-muted small">Başarılı Siparişler</h6>
                <?php
                $count = $db->prepare("SELECT COUNT(id) FROM orders WHERE user_id = ? AND status = 'completed'");
                $count->execute([$musteri_id]);
                $order_count = $count->fetchColumn();
                ?>
                <h3 class="fw-bold text-dark"><?= $order_count ?> Adet</h3>
            </div>
        </div>
    </div>
</div>

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