<?php
/**
 * Admin Kargo ve Sepet Kampanyaları Yönetimi
 * Konum: /magaza/admin/ayarlar/kargo_ayarlari.php
 */

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

// Güvenlik
adminCheck();

$mesaj = '';

// Form gönderildiyse güncelle
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['kargo_guncelle'])) {
    $fixed_fee = (float)$_POST['fixed_fee'];
    $free_amount_limit = (float)$_POST['free_amount_limit'];
    $free_amount_status = isset($_POST['free_amount_status']) ? 1 : 0;
    
    $free_quantity_limit = (int)$_POST['free_quantity_limit'];
    $free_quantity_status = isset($_POST['free_quantity_status']) ? 1 : 0;
    
    // YENİ: Seçilen kategorileri araya virgül koyarak metin (string) yapalım
    $target_categories = (isset($_POST['target_categories']) && is_array($_POST['target_categories'])) ? implode(',', $_POST['target_categories']) : NULL;

    try {
        $stmt = $db->prepare("UPDATE shipping_settings SET 
            fixed_fee = ?, 
            free_amount_limit = ?, 
            free_amount_status = ?, 
            free_quantity_limit = ?, 
            free_quantity_status = ?,
            target_categories = ?
            WHERE id = 1");
            
        $stmt->execute([
            $fixed_fee, 
            $free_amount_limit, 
            $free_amount_status, 
            $free_quantity_limit, 
            $free_quantity_status,
            $target_categories
        ]);
        
        $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle-fill me-2'></i> Kargo ve Kampanya ayarları başarıyla güncellendi!</div>";
    } catch (Exception $e) {
        $mesaj = "<div class='alert alert-danger shadow-sm'><i class='bi bi-exclamation-triangle-fill me-2'></i> Hata: " . $e->getMessage() . "</div>";
    }
}

// Mevcut ayarları çek
$ayarlar = $db->query("SELECT * FROM shipping_settings WHERE id = 1")->fetch();

// Kategorileri çek (Adet kampanyasında seçtirmek için)
$kategoriler = $db->query("SELECT id, name FROM categories ORDER BY name ASC")->fetchAll();
$secili_kategoriler = $ayarlar['target_categories'] ? explode(',', $ayarlar['target_categories']) : [];

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

<div class="row mb-4 align-items-center">
    <div class="col-12">
        <h2 class="fw-bold mb-0 text-dark"><i class="bi bi-truck text-primary me-2"></i>Kargo & Sepet Kampanyaları</h2>
        <p class="text-muted small mt-1">Mağazanızın kargo ücretlerini ve müşterileri teşvik edecek otomatik sepet kampanyalarını buradan yönetin.</p>
    </div>
</div>

<?= $mesaj; ?>

<form action="" method="POST">
    <div class="row">
        <div class="col-md-4 mb-4">
            <div class="card shadow-sm border-0 h-100">
                <div class="card-header bg-dark text-white py-3">
                    <h6 class="card-title mb-0 fw-bold small text-uppercase"><i class="bi bi-box me-2"></i>Temel Kargo Ücreti</h6>
                </div>
                <div class="card-body p-4">
                    <div class="alert alert-secondary small py-2 mb-4 border-0">
                        Hiçbir kampanyaya girmeyen veya özel olarak ücretsiz kargo tanımlanmamış siparişlerde uygulanacak standart kargo ücretidir.
                    </div>
                    <label class="form-label fw-bold text-muted small text-uppercase">Sabit Kargo Bedeli (₺)</label>
                    <div class="input-group mb-3">
                        <span class="input-group-text bg-light fw-bold border-2 border-end-0">₺</span>
                        <input type="number" step="0.01" name="fixed_fee" class="form-control form-control-lg fw-bold text-primary border-2 border-start-0" required value="<?= $ayarlar['fixed_fee'] ?>">
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-4 mb-4">
            <div class="card shadow-sm border-0 border-top border-warning border-4 h-100">
                <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
                    <h6 class="card-title mb-0 fw-bold small text-uppercase text-warning"><i class="bi bi-wallet2 me-2"></i>Tutar Kampanyası</h6>
                    <div class="form-check form-switch fs-5 mb-0">
                        <input class="form-check-input" type="checkbox" name="free_amount_status" value="1" <?= $ayarlar['free_amount_status'] == 1 ? 'checked' : '' ?>>
                    </div>
                </div>
                <div class="card-body p-4 opacity-<?= $ayarlar['free_amount_status'] == 1 ? '100' : '50' ?>">
                    <div class="alert alert-warning bg-warning bg-opacity-10 small py-2 mb-4 border-0 text-dark">
                        Müşterinin sepet <b>toplam tutarı</b> belirlediğiniz baraja ulaşırsa kargo otomatik <b>ÜCRETSİZ</b> olur.
                    </div>
                    <label class="form-label fw-bold text-muted small text-uppercase">Ücretsiz Kargo Barajı (₺)</label>
                    <div class="input-group mb-3">
                        <span class="input-group-text bg-light fw-bold border-2 border-end-0">₺</span>
                        <input type="number" step="0.01" name="free_amount_limit" class="form-control form-control-lg fw-bold text-dark border-2 border-start-0" required value="<?= $ayarlar['free_amount_limit'] ?>">
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-4 mb-4">
            <div class="card shadow-sm border-0 border-top border-success border-4 h-100">
                <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
                    <h6 class="card-title mb-0 fw-bold small text-uppercase text-success"><i class="bi bi-collection me-2"></i>Kategori Bazlı Adet Kampanyası</h6>
                    <div class="form-check form-switch fs-5 mb-0">
                        <input class="form-check-input" type="checkbox" name="free_quantity_status" value="1" <?= $ayarlar['free_quantity_status'] == 1 ? 'checked' : '' ?>>
                    </div>
                </div>
                <div class="card-body p-4 opacity-<?= $ayarlar['free_quantity_status'] == 1 ? '100' : '50' ?>">
                    <div class="alert alert-success bg-success bg-opacity-10 small py-2 mb-3 border-0 text-dark">
                        Sadece aşağıda <b>seçtiğiniz kategorilerden</b>, belirttiğiniz adet kadar ürün alınırsa kargo <b>ÜCRETSİZ</b> olur. (Çakışmaları önler)
                    </div>
                    
                    <label class="form-label fw-bold text-muted small text-uppercase">Geçerli Kategoriler</label>
                    <select name="target_categories[]" class="form-select border-2 mb-3" multiple style="height: 90px;">
                        <?php foreach($kategoriler as $kat): ?>
                            <option value="<?= $kat['id'] ?>" <?= in_array($kat['id'], $secili_kategoriler) ? 'selected' : '' ?>><?= htmlspecialchars($kat['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    
                    <label class="form-label fw-bold text-muted small text-uppercase">Hedef Ürün Adedi</label>
                    <div class="input-group mb-0">
                        <input type="number" name="free_quantity_limit" class="form-control form-control-lg fw-bold text-dark border-2 border-end-0" required value="<?= $ayarlar['free_quantity_limit'] ?>">
                        <span class="input-group-text bg-light fw-bold border-2 border-start-0">ADET</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="text-end">
        <button type="submit" name="kargo_guncelle" class="btn btn-primary btn-lg fw-bold px-5 shadow-sm rounded-pill">
            <i class="bi bi-save me-2"></i> Kuralları Kaydet ve Uygula
        </button>
    </div>
</form>

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