<?php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../functions/log_fonksiyonlari.php';
yetkili_mi('yonetici'); // Sadece yöneticiler silebilir

$marka_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$csrf_token = $_GET['csrf_token'] ?? '';

if (!$marka_id || !csrf_token_dogrula($csrf_token)) {
    $_SESSION['hata'] = __("invalid_request");
    header("Location: ../ayarlar.php?section=markalar");
    exit();
}

try {
    // Marka bilgilerini al
    $stmt = $db->prepare("SELECT marka_adi FROM markalar WHERE id = ? AND sirket_id = ?");
    $stmt->execute([$marka_id, $_SESSION['aktif_sirket_id']]);
    $marka = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$marka) {
        throw new Exception(__("brand_not_found"));
    }
    
    // Markayı kullanan ürün var mı kontrol et
    $stmt_check = $db->prepare("SELECT COUNT(*) FROM urunler WHERE marka_id = ? AND sirket_id = ? AND aktif = 1");
    $stmt_check->execute([$marka_id, $_SESSION['aktif_sirket_id']]);
    $urun_sayisi = $stmt_check->fetchColumn();
    
    if ($urun_sayisi > 0) {
        throw new Exception(__("brand_in_use"));
    }
    
    // Markayı sil
    $stmt_delete = $db->prepare("DELETE FROM markalar WHERE id = ? AND sirket_id = ?");
    $stmt_delete->execute([$marka_id, $_SESSION['aktif_sirket_id']]);
    
    // Log ekle
    sistem_log_ekle(
        $db,
        'sil',
        'markalar',
        $marka_id,
        ['marka_adi' => $marka['marka_adi']],
        null,
        __('brand_deleted_log', ['brand' => $marka['marka_adi']]),
        $_SESSION['kullanici_id']
    );
    
    $_SESSION['mesaj'] = __("brand_deleted_successfully");
} catch (Exception $e) {
    error_log("Marka silme hatası: " . $e->getMessage());
    $_SESSION['hata'] = $e->getMessage();
}

header("Location: ../ayarlar.php?section=markalar");
exit();
