<?php
session_start();
require_once '../includes/db.php';
require_once '../includes/functions.php';

// Oturum Güvenliği
if (!isset($_SESSION['user_id'])) {
    header("Location: ../giris.php");
    exit;
}

$user_id = (int)$_SESSION['user_id'];
$mesaj = '';

// 1. ADRES SİLME İŞLEMİ (Sıfır Güven - IDOR Korumalı)
if (isset($_GET['sil']) && is_numeric($_GET['sil'])) {
    $sil_id = (int)$_GET['sil'];
    $del_stmt = $db->prepare("DELETE FROM user_addresses WHERE id = ? AND user_id = ?");
    if ($del_stmt->execute([$sil_id, $user_id])) {
        $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-trash me-2'></i> Adres başarıyla silindi.</div>";
    }
}

// 2. YENİ ADRES EKLEME İŞLEMİ
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['adres_ekle'])) {
    $purpose = isset($_POST['address_purpose']) ? $_POST['address_purpose'] : 'shipping';
    $baslik_raw = trim($_POST['title']);
    
    // Veritabanında ayırt edebilmek için başlığın sonuna gizli etiket ekliyoruz
    $baslik = $baslik_raw . ($purpose == 'billing' ? ' [Fatura]' : ' [Teslimat]');
    
    $il = trim($_POST['city']);
    $ilce = trim($_POST['district']);
    $adres_detay = trim($_POST['full_address']);

    // Eğer Teslimat adresi ise kurumsal bilgileri yoksay
    if ($purpose == 'shipping') {
        $tip = 'individual';
    } else {
        $tip = isset($_POST['address_type']) ? $_POST['address_type'] : 'individual';
    }
    
    if ($tip == 'corporate') {
        $firma = trim($_POST['company_name']);
        $vd = trim($_POST['tax_office']);
        $vkn = trim($_POST['tax_number']);
        $adres_detay = "Firma: $firma | VD: $vd | VKN: $vkn \n" . $adres_detay;
    }

    if (empty($baslik_raw) || empty($il) || empty($ilce) || empty($adres_detay)) {
        $mesaj = "<div class='alert alert-danger shadow-sm'>Lütfen adres formundaki zorunlu alanları doldurun.</div>";
    } else {
        $ins = $db->prepare("INSERT INTO user_addresses (user_id, title, city, district, full_address) VALUES (?, ?, ?, ?, ?)");
        if ($ins->execute([$user_id, $baslik, $il, $ilce, $adres_detay])) {
            $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle-fill me-2'></i> Yeni adres başarıyla eklendi!</div>";
        } else {
            $mesaj = "<div class='alert alert-danger shadow-sm'>Adres eklenirken bir hata oluştu.</div>";
        }
    }
}

// 3. YENİ: ADRES GÜNCELLEME İŞLEMİ
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['adres_guncelle'])) {
    $edit_id = (int)$_POST['edit_id'];
    $purpose = $_POST['edit_purpose']; // 'billing' veya 'shipping'
    $baslik_raw = trim($_POST['title']);
    
    // Etiketi koruyarak başlığı yeniden oluştur
    $baslik = $baslik_raw . ($purpose == 'billing' ? ' [Fatura]' : ' [Teslimat]');
    
    $il = trim($_POST['city']);
    $ilce = trim($_POST['district']);
    $adres_detay = trim($_POST['full_address']);

    if (empty($baslik_raw) || empty($il) || empty($ilce) || empty($adres_detay)) {
        $mesaj = "<div class='alert alert-danger shadow-sm'>Lütfen güncellenecek zorunlu alanları doldurun.</div>";
    } else {
        // Güvenlik: AND user_id = ? diyerek başkasının adresini değiştirmesini engelliyoruz
        $upd = $db->prepare("UPDATE user_addresses SET title = ?, city = ?, district = ?, full_address = ? WHERE id = ? AND user_id = ?");
        if ($upd->execute([$baslik, $il, $ilce, $adres_detay, $edit_id, $user_id])) {
            $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle-fill me-2'></i> Adresiniz başarıyla güncellendi!</div>";
        } else {
            $mesaj = "<div class='alert alert-danger shadow-sm'>Adres güncellenirken bir hata oluştu.</div>";
        }
    }
}

// Müşteri Bilgisi (Sol menü)
$user_stmt = $db->prepare("SELECT name, surname, email FROM users WHERE id = ?");
$user_stmt->execute([$user_id]);
$musteri = $user_stmt->fetch();

// Müşterinin Kayıtlı Adreslerini Çek
$adres_stmt = $db->prepare("SELECT * FROM user_addresses WHERE user_id = ? ORDER BY id DESC");
$adres_stmt->execute([$user_id]);
$adresler = $adres_stmt->fetchAll();

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

<main class="container py-5">
    <div class="row">
        
        <div class="col-lg-3 mb-4">
            <?php include 'sidebar.php'; ?>
        </div>

        <div class="col-lg-9">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2 class="h4 fw-bold mb-0">Adres Bilgilerim</h2>
                <button type="button" class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#yeniAdresModal">
                    <i class="bi bi-plus-lg me-1"></i> Yeni Adres Ekle
                </button>
            </div>
            
            <?= $mesaj ?>

            <div class="row g-4">
                <?php if(count($adresler) > 0): ?>
                    <?php foreach($adresler as $adres): ?>
                    <?php 
                        // Veritabanındaki [Fatura] veya [Teslimat] ekini algıla ve şık bir görünüme çevir
                        $is_billing = (strpos($adres['title'], '[Fatura]') !== false);
                        $clean_title = str_replace(['[Fatura]', '[Teslimat]'], '', $adres['title']);
                        $border_color = $is_billing ? 'border-info' : 'border-success';
                        $icon = $is_billing ? '<i class="bi bi-receipt text-info"></i>' : '<i class="bi bi-truck text-success"></i>';
                        $badge = $is_billing ? '<span class="badge bg-info text-dark ms-2" style="font-size:10px;">FATURA ADRESİ</span>' : '<span class="badge bg-success ms-2" style="font-size:10px;">TESLİMAT ADRESİ</span>';
                    ?>
                    <div class="col-md-6">
                        <div class="card shadow-sm border-0 h-100 border-start <?= $border_color ?> border-4">
                            <div class="card-body bg-light d-flex flex-column">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <h5 class="fw-bold mb-0 text-dark d-flex align-items-center">
                                        <?= $icon ?> <span class="ms-2"><?= htmlspecialchars(trim($clean_title)) ?></span> <?= $badge ?>
                                    </h5>
                                    <div class="d-flex text-nowrap">
                                        <button type="button" class="btn btn-sm btn-outline-primary border-0 me-1 edit-address-btn" 
                                            data-id="<?= $adres['id'] ?>"
                                            data-title="<?= htmlspecialchars(trim($clean_title)) ?>"
                                            data-city="<?= htmlspecialchars($adres['city']) ?>"
                                            data-district="<?= htmlspecialchars($adres['district']) ?>"
                                            data-address="<?= htmlspecialchars($adres['full_address']) ?>"
                                            data-purpose="<?= $is_billing ? 'billing' : 'shipping' ?>"
                                            title="Adresi Düzenle">
                                            <i class="bi bi-pencil-square"></i>
                                        </button>
                                        <a href="adresler.php?sil=<?= $adres['id'] ?>" class="btn btn-sm btn-outline-danger border-0" onclick="return confirm('Bu adresi silmek istediğinize emin misiniz?');" title="Adresi Sil"><i class="bi bi-trash-fill"></i></a>
                                    </div>
                                </div>
                                <hr class="my-2 border-secondary">
                                <p class="mb-1 fw-bold text-muted small"><?= htmlspecialchars($adres['city'] . ' / ' . $adres['district']) ?></p>
                                <p class="mb-0 small text-secondary lh-lg flex-grow-1"><?= nl2br(htmlspecialchars($adres['full_address'])) ?></p>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="col-12">
                        <div class="text-center py-5 bg-white rounded shadow-sm border">
                            <i class="bi bi-signpost-split text-muted mb-3 d-block" style="font-size: 4rem;"></i>
                            <h5 class="fw-bold text-dark">Kayıtlı Adresiniz Bulunmuyor</h5>
                            <p class="text-muted">Hızlı alışveriş için hemen bir teslimat veya fatura adresi ekleyin.</p>
                            <button type="button" class="btn btn-primary mt-2" data-bs-toggle="modal" data-bs-target="#yeniAdresModal">Adres Ekle</button>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>

<div class="modal fade" id="yeniAdresModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title fw-bold"><i class="bi bi-house-add me-2"></i>Yeni Adres Ekle</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="adresler.php" method="POST">
                <div class="modal-body p-4">
                    <div class="row g-3">
                        
                        <div class="col-12 mb-2 bg-light p-3 rounded border">
                            <label class="form-label small text-muted fw-bold d-block mb-2"><i class="bi bi-question-circle"></i> Bu adres ne için kullanılacak? *</label>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="address_purpose" id="purpose_shipping" value="shipping" checked onchange="togglePurpose()">
                                <label class="form-check-label fw-bold text-dark" for="purpose_shipping">Kargo / Teslimat Adresi</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="address_purpose" id="purpose_billing" value="billing" onchange="togglePurpose()">
                                <label class="form-check-label fw-bold text-dark" for="purpose_billing">Fatura Adresi</label>
                            </div>
                        </div>

                        <div class="col-12">
                            <label class="form-label small text-muted fw-bold">Adres Başlığı *</label>
                            <input type="text" name="title" class="form-control" placeholder="Örn: Evim, İş Yerim" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small text-muted fw-bold">İl *</label>
                            <input type="text" name="city" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small text-muted fw-bold">İlçe *</label>
                            <input type="text" name="district" class="form-control" required>
                        </div>
                        
                        <div id="invoiceTypeSection" class="col-12 mt-3 mb-2" style="display: none;">
                            <hr>
                            <label class="form-label small text-muted fw-bold d-block mb-2">Fatura Tipi *</label>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="address_type" id="bireysel" value="individual" checked onchange="toggleCorporateFields()">
                                <label class="form-check-label fw-bold text-dark" for="bireysel">Bireysel</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="address_type" id="kurumsal" value="corporate" onchange="toggleCorporateFields()">
                                <label class="form-check-label fw-bold text-dark" for="kurumsal">Kurumsal (Şirket)</label>
                            </div>
                        </div>

                        <div class="row g-3 mt-0" id="corporateFields" style="display: none; background-color: #f8f9fa; padding: 15px; border-radius: 8px;">
                            <div class="col-12">
                                <label class="form-label small text-muted fw-bold">Firma Ünvanı *</label>
                                <input type="text" name="company_name" class="form-control corp-req">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small text-muted fw-bold">Vergi Dairesi *</label>
                                <input type="text" name="tax_office" class="form-control corp-req">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small text-muted fw-bold">Vergi Numarası (VKN) *</label>
                                <input type="text" name="tax_number" class="form-control corp-req">
                            </div>
                        </div>

                        <div class="col-12 mt-3">
                            <label class="form-label small text-muted fw-bold">Açık Adres *</label>
                            <textarea name="full_address" class="form-control" rows="3" placeholder="Mahalle, sokak, bina ve daire no..." required></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" name="adres_ekle" class="btn btn-primary fw-bold">Adresi Kaydet</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="duzenleAdresModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title fw-bold"><i class="bi bi-pencil-square me-2"></i>Adresi Düzenle</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="adresler.php" method="POST">
                <input type="hidden" name="edit_id" id="edit_id">
                <input type="hidden" name="edit_purpose" id="edit_purpose">

                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label small text-muted fw-bold">Adres Başlığı *</label>
                            <input type="text" name="title" id="edit_title" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small text-muted fw-bold">İl *</label>
                            <input type="text" name="city" id="edit_city" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small text-muted fw-bold">İlçe *</label>
                            <input type="text" name="district" id="edit_district" class="form-control" required>
                        </div>
                        <div class="col-12 mt-3">
                            <label class="form-label small text-muted fw-bold">Açık Adres (Firma Bilgileri Dahil) *</label>
                            <textarea name="full_address" id="edit_full_address" class="form-control" rows="4" required></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" name="adres_guncelle" class="btn btn-primary fw-bold">Değişiklikleri Kaydet</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Teslimat / Fatura Amacını Kontrol Eden Fonksiyon (Yeni Adres Formu İçin)
function togglePurpose() {
    let isBilling = document.getElementById('purpose_billing').checked;
    let invoiceTypeSection = document.getElementById('invoiceTypeSection');
    
    if (isBilling) {
        invoiceTypeSection.style.display = 'block';
    } else {
        invoiceTypeSection.style.display = 'none';
        document.getElementById('bireysel').checked = true;
        toggleCorporateFields();
    }
}

// Bireysel / Kurumsal Kontrol Eden Fonksiyon (Yeni Adres Formu İçin)
function toggleCorporateFields() {
    let isCorporate = document.getElementById('kurumsal').checked;
    let corpDiv = document.getElementById('corporateFields');
    let reqFields = document.querySelectorAll('.corp-req');
    
    if(isCorporate && document.getElementById('purpose_billing').checked) {
        corpDiv.style.display = 'flex';
        reqFields.forEach(el => el.setAttribute('required', 'required'));
    } else {
        corpDiv.style.display = 'none';
        reqFields.forEach(el => el.removeAttribute('required'));
    }
}

// YENİ: Düzenle Butonuna Basıldığında Verileri Modal'a Aktaran Motor
document.addEventListener('DOMContentLoaded', function() {
    const editButtons = document.querySelectorAll('.edit-address-btn');
    
    editButtons.forEach(button => {
        button.addEventListener('click', function() {
            // Butondaki verileri al
            const id = this.getAttribute('data-id');
            const title = this.getAttribute('data-title');
            const city = this.getAttribute('data-city');
            const district = this.getAttribute('data-district');
            const address = this.getAttribute('data-address');
            const purpose = this.getAttribute('data-purpose');
            
            // Modal içindeki form elemanlarına yerleştir
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_purpose').value = purpose;
            document.getElementById('edit_title').value = title;
            document.getElementById('edit_city').value = city;
            document.getElementById('edit_district').value = district;
            document.getElementById('edit_full_address').value = address;
            
            // Modalı Aç
            const editModal = new bootstrap.Modal(document.getElementById('duzenleAdresModal'));
            editModal.show();
        });
    });
});
</script>

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