<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../functions/stok_fonksiyonlari.php';
yetkili_mi();

$sayfa_baslik = __("edit_product");

// Ürün ID'sini al
$urun_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$urun_id) {
    $_SESSION['hata'] = __("invalid_product_id");
    header("Location: urunler.php");
    exit();
}

// Aktif şirketin para birimi ayarlarını çek
$coklu_para_birimi = 0;
$sirket_para_birimi = 'TL';
$doviz_kurlari = [];
if (!empty($_SESSION['aktif_sirket_id'])) {
    $stmt = $db->prepare("SELECT coklu_para_birimi, para_birimi FROM sirketler WHERE id = ? LIMIT 1");
    $stmt->execute([$_SESSION['aktif_sirket_id']]);
    $sirket_ayar = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($sirket_ayar) {
        $coklu_para_birimi = (int)$sirket_ayar['coklu_para_birimi'];
        $sirket_para_birimi = $sirket_ayar['para_birimi'] ?: 'TL';
    }
    
    // Döviz kurlarını veritabanından çek
    if ($coklu_para_birimi) {
        try {
            $stmt_doviz = $db->prepare("SELECT para_birimi, alis, satis, guncelleme_tarihi FROM doviz_kurlari ORDER BY id");
            $stmt_doviz->execute();
            $doviz_kurlari = $stmt_doviz->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log('Döviz kurları çekilemedi: ' . $e->getMessage());
            $doviz_kurlari = [];
        }
    }
}
// --- Veritabanından Gerekli Bilgileri Getir Başlangıç ---
try {
    // Ürün bilgilerini getir
    $stmt = $db->prepare("
        SELECT u.*, ms.miktar as stok_miktari, ms.ortalama_maliyet, k.kategori_adi, u.mevcut_stok_baslangic
        FROM urunler u
        LEFT JOIN mevcut_stok ms ON u.id = ms.urun_id AND ms.sirket_id = u.sirket_id
        LEFT JOIN kategoriler k ON u.kategori_id = k.id AND k.sirket_id = u.sirket_id
        WHERE u.id = ? AND u.sirket_id = ? AND u.aktif = 1
    ");
    $stmt->execute([$urun_id, $_SESSION['aktif_sirket_id']]);
    $urun = $stmt->fetch();

    if (!$urun) {
        throw new Exception(__("product_not_found"));
    }

    // Ürüne ait resimleri getir
    $urun_resimleri = urunResimleriniGetir($db, $urun_id, $_SESSION['aktif_sirket_id']);

    // Ayarları getir
    $ayarlar_raw = $db->query("SELECT ayar_adi, ayar_degeri FROM ayarlar WHERE ayar_adi IN ('ikinci_fiyat_kdv_aktif', 'stok_resim_yukleme_aktif', 'stok_resim_yukleme_dizin')")->fetchAll(PDO::FETCH_KEY_PAIR);
    $ikinci_fiyat_aktif = $ayarlar_raw['ikinci_fiyat_kdv_aktif'] ?? '0';
    $stok_resim_yukleme_aktif = $ayarlar_raw['stok_resim_yukleme_aktif'] ?? '0';
    $stok_resim_yukleme_dizin = $ayarlar_raw['stok_resim_yukleme_dizin'] ?? 'uploads/urun_resimleri';
    
    // Kategorileri getir
    $kategori_stmt = $db->prepare("SELECT id, kategori_adi FROM kategoriler WHERE sirket_id = ? AND tip = 'urun' ORDER BY kategori_adi");
    $kategori_stmt->execute([$_SESSION['aktif_sirket_id']]);
    $kategoriler = $kategori_stmt->fetchAll();

    // Markaları getir
    $marka_stmt = $db->prepare("SELECT id, marka_adi FROM markalar WHERE sirket_id = ? ORDER BY marka_adi");
    $marka_stmt->execute([$_SESSION['aktif_sirket_id']]);
    $markalar = $marka_stmt->fetchAll();

    // Depo yönetimi modülünü kontrol et
    $depo_yonetimi_aktif = depoYonetimiAktifMi($db, $_SESSION['aktif_sirket_id']);
    $depolar = [];
    $raflar = [];
    $urun_depo_raf = [];
    if ($depo_yonetimi_aktif) {
        $depolar = depoGetir($db, $_SESSION['aktif_sirket_id']);
        $raflar = rafGetir($db, $_SESSION['aktif_sirket_id']);
        // Ürünün mevcut depo/raf bilgilerini getir
        $urun_depo_raf = depoRafStokGetir($db, $urun_id, $_SESSION['aktif_sirket_id']);
    }

} catch (Exception $e) {
    error_log("Ürün düzenleme sayfası yükleme hatası: " . $e->getMessage());
    $_SESSION['hata'] = "Sayfa yüklenirken bir hata oluştu: " . $e->getMessage();
    header("Location: urunler.php");
    exit();
}
// --- Veritabanından Gerekli Bilgileri Getir Bitiş ---

// Form gönderildiğinde (sadece ana ürün bilgileri için)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['urun_bilgi_guncelle'])) {
    if (!csrf_token_dogrula($_POST['csrf_token'] ?? '')) {
        $_SESSION['hata'] = "Geçersiz form gönderimi!";
    } else {
        // Form verilerini al ve temizle
        $urun_bilgileri = [
            'urun_adi' => temizle($_POST['urun_adi'] ?? ''),
            'barkod' => temizle($_POST['barkod'] ?? ''),
            'kategori_id' => filter_input(INPUT_POST, 'kategori_id', FILTER_VALIDATE_INT),
            'marka_id' => filter_input(INPUT_POST, 'marka_id', FILTER_VALIDATE_INT),
            'birim' => temizle($_POST['birim'] ?? 'adet'),
            'alis_fiyati' => ondalik($_POST['alis_fiyati'] ?? '0'),
            'satis_fiyati' => ondalik($_POST['satis_fiyati'] ?? '0'),
            'kdv_orani' => ondalik($_POST['kdv_orani'] ?? '0'),
            'kritik_stok' => tamsayi($_POST['kritik_stok'] ?? '0'),
            'mevcut_stok_baslangic' => tamsayi($_POST['mevcut_stok_baslangic'] ?? '0'),
            'aciklama' => temizle($_POST['aciklama'] ?? ''),
            'alis_para_birimi' => $coklu_para_birimi ? temizle($_POST['alis_para_birimi'] ?? $sirket_para_birimi) : $sirket_para_birimi,
            'satis_para_birimi' => $coklu_para_birimi ? temizle($_POST['satis_para_birimi'] ?? $sirket_para_birimi) : $sirket_para_birimi
        ];

        // Veri doğrulama
        $hatalar = [];
        if (empty($urun_bilgileri['urun_adi'])) $hatalar[] = __("product_name_required");
        if ($urun_bilgileri['alis_fiyati'] === false || $urun_bilgileri['alis_fiyati'] < 0) $hatalar[] = __("valid_purchase_price");
        if ($urun_bilgileri['satis_fiyati'] === false || $urun_bilgileri['satis_fiyati'] < 0) $hatalar[] = __("valid_sale_price");
        if ($urun_bilgileri['kdv_orani'] === false || $urun_bilgileri['kdv_orani'] < 0 || $urun_bilgileri['kdv_orani'] > 100) $hatalar[] = __("valid_vat_rate");

        // Barkod kontrolü (varsa ve değişmişse)
        if (!empty($urun_bilgileri['barkod']) && $urun_bilgileri['barkod'] !== $urun['barkod']) {
            $stmt = $db->prepare("SELECT id FROM urunler WHERE barkod = ? AND sirket_id = ? AND aktif = 1 AND id != ?");
            $stmt->execute([$urun_bilgileri['barkod'], $_SESSION['aktif_sirket_id'], $urun_id]);
            if ($stmt->fetch()) $hatalar[] = __("barcode_in_use");
        }

        if (empty($hatalar)) {
            if (urunGuncelle($db, $urun_id, $_SESSION['aktif_sirket_id'], $urun_bilgileri)) {
                $_SESSION['mesaj'] = __("product_updated");
                header("Location: urun_duzenle.php?id=" . $urun_id);
                exit();
            } else {
                $_SESSION['hata'] = __("product_update_error");
            }
        } else {
            $_SESSION['form_hatalari'] = $hatalar;
            $_SESSION['form_verileri'] = $_POST;
        }
    }
    header("Location: urun_duzenle.php?id=" . $urun_id);
    exit();
}

// Yeni resim yüklendiğinde
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['yeni_resim'])) {
    if (!csrf_token_dogrula($_POST['csrf_token'] ?? '')) {
        $_SESSION['hata'] = "Geçersiz form gönderimi!";
    } elseif ($stok_resim_yukleme_aktif == '1') {
        if (!resimYukle($db, $urun_id, $_SESSION['aktif_sirket_id'], $_FILES['yeni_resim'], $stok_resim_yukleme_dizin)) {
            $_SESSION['hata'] = $_SESSION['hata'] ?? "Ürün resmi yüklenirken bir hata oluştu.";
        } else {
            $_SESSION['mesaj'] = "Yeni resim başarıyla eklendi.";
        }
    }
    header("Location: urun_duzenle.php?id=" . $urun_id);
    exit();
}

$csrf_token = csrf_token_olustur();
// Hata ve form verilerini session'dan al
$form_hatalari = $_SESSION['form_hatalari'] ?? [];
$form_verileri = $_SESSION['form_verileri'] ?? [];
unset($_SESSION['form_hatalari'], $_SESSION['form_verileri']);

// Eğer formdan gelen veri yoksa, mevcut ürün bilgileriyle doldur
if (empty($form_verileri)) {
    $form_verileri = [
        'urun_adi' => $urun['urun_adi'],
        'barkod' => $urun['barkod'],
        'kategori_id' => $urun['kategori_id'],
        'marka_id' => $urun['marka_id'],
        'birim' => $urun['birim'],
        'alis_fiyati' => number_format($urun['alis_fiyati'], 2, '.', ''),
        'satis_fiyati' => number_format($urun['satis_fiyati'], 2, '.', ''),
        'kdv_orani' => $urun['kdv_orani'],
        'kritik_stok' => $urun['kritik_stok'],
        'mevcut_stok_baslangic' => $urun['mevcut_stok_baslangic'] ?? 0,
        'aciklama' => $urun['aciklama'],
        'alis_para_birimi' => $urun['alis_para_birimi'] ?? $sirket_para_birimi,
        'satis_para_birimi' => $urun['satis_para_birimi'] ?? $sirket_para_birimi
    ];
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Begeb Creative Yönetim - <?= temizle($sayfa_baslik) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body {
            background: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }

        .page-header {
            background: white;
            border-radius: 2px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            border: 1px solid #e2e8f0;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
        }

        .page-header h2 {
            color: #1e293b;
            font-size: 1.75rem;
            font-weight: 700;
            margin: 0;
        }

        .page-header .btn {
            border-radius: 2px;
            padding: 0.5rem 1rem;
            font-weight: 600;
            font-size: 0.875rem;
            border-width: 1.5px;
        }

        .modern-card {
            background: white;
            border-radius: 2px;
            border: 1px solid #e2e8f0;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            overflow: hidden;
            margin-bottom: 1.5rem;
        }

        .card-section {
            padding: 1.5rem;
            border-bottom: 1px solid #f1f5f9;
        }

        .card-section:last-child {
            border-bottom: none;
        }

        .section-title {
            color: #1e293b;
            font-size: 1rem;
            font-weight: 700;
            margin-bottom: 1.25rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .section-title i {
            color: #3b82f6;
            font-size: 1.125rem;
        }

        .form-label {
            color: #334155;
            font-weight: 600;
            font-size: 0.8125rem;
            margin-bottom: 0.375rem;
        }

        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 2px;
            padding: 0.5rem 0.75rem;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }

        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.08);
        }

        .form-text {
            font-size: 0.75rem;
            color: #64748b;
        }

        .btn-primary {
            background: #3b82f6;
            border: none;
            border-radius: 2px;
            padding: 0.625rem 1.25rem;
            font-weight: 600;
            font-size: 0.875rem;
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            background: #2563eb;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
        }

        .btn-success {
            background: #10b981;
            border: none;
            border-radius: 2px;
            padding: 0.625rem 1.25rem;
            font-weight: 600;
            font-size: 0.875rem;
        }

        .btn-success:hover {
            background: #059669;
        }

        .image-gallery .card {
            position: relative;
            overflow: hidden;
            border: 1px solid #e2e8f0;
            border-radius: 4px;
        }

        .image-gallery .card-img-top {
            width: 100%;
            height: 150px;
            object-fit: cover;
        }

        .image-gallery .default-badge {
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 10;
        }

        .image-gallery .card-body {
            padding: 0.75rem;
        }

        .image-gallery .btn-group {
            width: 100%;
        }

        .upload-preview {
            width: 100%;
            height: 150px;
            border: 2px dashed #cbd5e1;
            border-radius: 4px;
            display: flex;
            justify-content: center;
            align-items: center;
            text-align: center;
            color: #94a3b8;
            background-size: cover;
            background-position: center;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .upload-preview:hover {
            border-color: #3b82f6;
            color: #3b82f6;
        }

        .upload-preview .bi {
            font-size: 2rem;
        }

        @media (max-width: 768px) {
            .page-header {
                padding: 1rem;
            }

            .page-header h2 {
                font-size: 1.25rem;
            }

            .card-section {
                padding: 1.25rem;
            }
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>
    
    <div class="container mt-4 mb-5">
        <!-- Başlık ve Butonlar -->
        <div class="page-header">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                <h2>
                    <i class="bi bi-pencil-square me-2"></i><?= temizle($urun['urun_adi']) ?> 
                    <small class="text-muted" style="font-size: 0.875rem; font-weight: 400;">#<?= $urun_id ?></small>
                </h2>
                <div class="d-flex gap-2">
                    <a href="urunler.php" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-left me-1"></i><?= __('product_list') ?>
                    </a>
                    <a href="urun_sil.php?id=<?= $urun['id'] ?>&csrf_token=<?= $csrf_token ?>" 
                       class="btn btn-outline-danger" 
                       onclick="return confirm('<?= __('delete_confirm') ?>')">
                        <i class="bi bi-trash me-1"></i><?= __('delete') ?>
                    </a>
                </div>
            </div>
        </div>

        <!-- Mesaj ve Hata Alanı -->
        <?php if(isset($_SESSION['mesaj'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="bi bi-check-circle-fill me-2"></i><?= $_SESSION['mesaj']; unset($_SESSION['mesaj']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        <?php if(isset($_SESSION['hata'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="bi bi-exclamation-triangle-fill me-2"></i><?= $_SESSION['hata']; unset($_SESSION['hata']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        <?php if (!empty($form_hatalari)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <strong><i class="bi bi-exclamation-triangle-fill me-2"></i><?= __('please_fix_errors') ?></strong>
                <ul class="mb-0 mt-2">
                    <?php foreach ($form_hatalari as $hata): ?><li><?= htmlspecialchars($hata) ?></li><?php endforeach; ?>
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- Ürün Bilgileri Formu -->
        <div class="modern-card">
            <div class="card-section">
                <div class="section-title">
                    <i class="bi bi-info-circle"></i>
                    <span><?= __('product_information') ?></span>
                </div>
                <form method="post" id="urunForm">
                    <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                    <input type="hidden" name="urun_bilgi_guncelle" value="1">
                    <div class="row g-3">
                        <div class="col-md-8">
                            <label for="urun_adi" class="form-label">
                                <?= __('product_name') ?> <span class="text-danger">*</span>
                            </label>
                            <input type="text" class="form-control" id="urun_adi" name="urun_adi" 
                                   required value="<?= htmlspecialchars($form_verileri['urun_adi'] ?? '') ?>"
                                   placeholder="<?= __('enter_product_name') ?>">
                        </div>
                        <div class="col-md-4">
                            <label for="birim" class="form-label"><?= __('unit') ?></label>
                            <select class="form-select" id="birim" name="birim">
                                <option value="adet" <?= ($form_verileri['birim'] ?? 'adet') == 'adet' ? 'selected' : '' ?>><?= __('piece') ?></option>
                                <option value="kg" <?= ($form_verileri['birim'] ?? '') == 'kg' ? 'selected' : '' ?>><?= __('kg') ?></option>
                                <option value="gram" <?= ($form_verileri['birim'] ?? '') == 'gram' ? 'selected' : '' ?>><?= __('gram') ?></option>
                                <option value="litre" <?= ($form_verileri['birim'] ?? '') == 'litre' ? 'selected' : '' ?>><?= __('liter') ?></option>
                                <option value="metre" <?= ($form_verileri['birim'] ?? '') == 'metre' ? 'selected' : '' ?>><?= __('meter') ?></option>
                                <option value="paket" <?= ($form_verileri['birim'] ?? '') == 'paket' ? 'selected' : '' ?>><?= __('package') ?></option>
                                <option value="kutu" <?= ($form_verileri['birim'] ?? '') == 'kutu' ? 'selected' : '' ?>><?= __('box') ?></option>
                            </select>
                        </div>

                        <div class="col-md-3">
    <label for="alis_fiyati" class="form-label"><?= __('purchase_price') ?> <span class="text-danger">*</span></label>
    <div class="input-group">
        <input type="text" class="form-control" id="alis_fiyati" name="alis_fiyati" required value="<?= htmlspecialchars($form_verileri['alis_fiyati'] ?? '') ?>">
        <?php if ($coklu_para_birimi): ?>
            <select class="form-select" name="alis_para_birimi" id="alis_para_birimi">
                <option value="TL" <?= ($form_verileri['alis_para_birimi'] ?? $sirket_para_birimi) == 'TL' ? 'selected' : '' ?>>TL</option>
                <?php $___seen_pb = []; foreach ($doviz_kurlari as $kur): $pb = $kur['para_birimi']; if (in_array($pb, $___seen_pb)) continue; $___seen_pb[] = $pb; ?>
                    <option value="<?= $pb ?>" <?= ($form_verileri['alis_para_birimi'] ?? $sirket_para_birimi) == $pb ? 'selected' : '' ?>><?= $pb ?></option>
                <?php endforeach; ?>
            </select>
        <?php else: ?>
            <input type="hidden" name="alis_para_birimi" value="<?= $sirket_para_birimi ?>">
        <?php endif; ?>
    </div>
</div>
<div class="col-md-3">
    <label for="satis_fiyati" class="form-label"><?= __('sale_price') ?> <span class="text-danger">*</span></label>
    <div class="input-group">
        <input type="text" class="form-control" id="satis_fiyati" name="satis_fiyati" required value="<?= htmlspecialchars($form_verileri['satis_fiyati'] ?? '') ?>">
        <?php if ($coklu_para_birimi): ?>
            <select class="form-select" name="satis_para_birimi" id="satis_para_birimi">
                <option value="TL" <?= ($form_verileri['satis_para_birimi'] ?? $sirket_para_birimi) == 'TL' ? 'selected' : '' ?>>TL</option>
                <?php $___seen_pb = []; foreach ($doviz_kurlari as $kur): $pb = $kur['para_birimi']; if (in_array($pb, $___seen_pb)) continue; $___seen_pb[] = $pb; ?>
                    <option value="<?= $pb ?>" <?= ($form_verileri['satis_para_birimi'] ?? $sirket_para_birimi) == $pb ? 'selected' : '' ?>><?= $pb ?></option>
                <?php endforeach; ?>
            </select>
        <?php else: ?>
            <input type="hidden" name="satis_para_birimi" value="<?= $sirket_para_birimi ?>">
        <?php endif; ?>
    </div>
</div>

<div class="col-md-4">
    <label for="barkod" class="form-label"><?= __('barcode') ?></label>
                            <input type="text" class="form-control" id="barkod" name="barkod" value="<?= htmlspecialchars($form_verileri['barkod'] ?? '') ?>">
                        </div>
                        <div class="col-md-4">
                            <label for="kategori_id" class="form-label"><?= __('category') ?></label>
                            <select class="form-select" id="kategori_id" name="kategori_id">
                                <option value="">-- <?= __('select_category') ?> --</option>
                                <?php foreach ($kategoriler as $kategori): ?>
                                    <option value="<?= $kategori['id'] ?>" <?= ($form_verileri['kategori_id'] ?? '') == $kategori['id'] ? 'selected' : '' ?>>
                                        <?= temizle($kategori['kategori_adi']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="marka_id" class="form-label"><?= __('brand') ?></label>
                            <select class="form-select" id="marka_id" name="marka_id">
                                <option value="">-- <?= __('select_brand') ?> --</option>
                                <?php foreach ($markalar as $marka): ?>
                                    <option value="<?= $marka['id'] ?>" <?= ($form_verileri['marka_id'] ?? '') == $marka['id'] ? 'selected' : '' ?>>
                                        <?= temizle($marka['marka_adi']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                 
                        <div class="col-md-4">
                            <label for="kdv_orani" class="form-label"><?= __('vat_rate') ?> (%)</label>
                            <select class="form-select" id="kdv_orani" name="kdv_orani">
                                <option value="0" <?= ($form_verileri['kdv_orani'] ?? '0') == '0' ? 'selected' : '' ?>>%0</option>
                                <option value="1" <?= ($form_verileri['kdv_orani'] ?? '') == '1' ? 'selected' : '' ?>>%1</option>
                                <option value="8" <?= ($form_verileri['kdv_orani'] ?? '') == '8' ? 'selected' : '' ?>>%8</option>
                                <option value="18" <?= ($form_verileri['kdv_orani'] ?? '') == '18' ? 'selected' : '' ?>>%18</option>
                                <option value="20" <?= ($form_verileri['kdv_orani'] ?? '') == '20' ? 'selected' : '' ?>>%20</option>
                            </select>
                        </div>

                        <div class="col-12"><hr class="my-3"></div>
                        
                        <?php if ($depo_yonetimi_aktif): ?>
                        <div class="col-md-6">
                            <label for="depo_id" class="form-label"><?= __('warehouse') ?></label>
                            <select class="form-select" id="depo_id" name="depo_id" disabled>
                                <option value="">-- <?= __('select_warehouse') ?> --</option>
                                <?php foreach ($depolar as $depo): ?>
                                    <option value="<?= $depo['id'] ?>">
                                        <?= temizle($depo['depo_adi']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="form-text"><?= __('warehouse_info_view_only') ?></div>
                        </div>
                        <div class="col-md-6">
                            <label for="raf_id" class="form-label"><?= __('shelf') ?></label>
                            <select class="form-select" id="raf_id" name="raf_id" disabled>
                                <option value="">-- <?= __('select_shelf') ?> --</option>
                                <?php foreach ($raflar as $raf): ?>
                                    <option value="<?= $raf['id'] ?>">
                                        <?= temizle($raf['raf_adi']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="form-text"><?= __('shelf_info_view_only') ?></div>
                        </div>
                        
                        <?php if (!empty($urun_depo_raf)): ?>
                        <div class="col-12">
                            <div class="alert alert-info">
                                <strong><i class="bi bi-info-circle me-2"></i><?= __('warehouse_shelf_distribution') ?></strong>
                                <ul class="mb-0 mt-2">
                                    <?php foreach ($urun_depo_raf as $item): ?>
                                        <li>
                                            <?php if ($item['depo_adi']): ?>
                                                <strong><?= __('warehouse') ?>:</strong> <?= temizle($item['depo_adi']) ?>
                                            <?php endif; ?>
                                            <?php if ($item['raf_adi']): ?>
                                                | <strong><?= __('shelf') ?>:</strong> <?= temizle($item['raf_adi']) ?>
                                            <?php endif; ?>
                                            | <strong><?= __('stock') ?>:</strong> <?= number_format($item['miktar'], 2, ',', '.') ?>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        </div>
                        <?php endif; ?>
                        <?php endif; ?>
                        
                        <div class="col-md-6">
                            <label for="kritik_stok" class="form-label"><?= __('critical_stock_amount') ?></label>
                            <input type="number" class="form-control" id="kritik_stok" name="kritik_stok" min="0" value="<?= htmlspecialchars($form_verileri["kritik_stok"] ?? "0") ?>">
                            <div class="form-text"><?= __('low_stock_warning') ?></div>
                        </div>
                        <div class="col-md-6">
                             <label for="mevcut_stok_baslangic" class="form-label"><?= __('initial_stock') ?></label>
                             <input type="number" class="form-control" id="mevcut_stok_baslangic" name="mevcut_stok_baslangic" value="<?= htmlspecialchars($form_verileri["mevcut_stok_baslangic"] ?? "0") ?>" readonly>
                             <div class="form-text"><?= __('initial_stock_note') ?></div>
                        </div>

                        <div class="col-12">
                            <label for="aciklama" class="form-label"><?= __('description') ?></label>
                            <textarea class="form-control" id="aciklama" name="aciklama" rows="3" 
                                      placeholder="<?= __('enter_product_description') ?>"><?= htmlspecialchars($form_verileri["aciklama"] ?? "") ?></textarea>
                        </div>

                        <div class="col-12">
                            <div class="d-flex gap-2 flex-wrap">
                                <button type="submit" class="btn btn-success">
                                    <i class="bi bi-check-lg me-1"></i><?= __('update_information') ?>
                                </button>
                                <a href="stok_hareketleri.php?urun_id=<?= $urun["id"] ?>" class="btn btn-info">
                                    <i class="bi bi-clock-history me-1"></i><?= __('stock_movements') ?>
                                </a>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Ürün Resimleri Yönetimi -->
        <?php if ($stok_resim_yukleme_aktif == '1'): ?>
        <div class="modern-card">
            <div class="card-section">
                <div class="section-title">
                    <i class="bi bi-images"></i>
                    <span><?= __('product_images') ?></span>
                </div>
                <div class="row g-3 image-gallery">
                    <!-- Mevcut Resimler -->
                    <?php foreach ($urun_resimleri as $resim): 
                        $resim_url = BASE_URL . '/' . htmlspecialchars(trim($stok_resim_yukleme_dizin, '/') . '/' . $resim['resim_yolu']);
                    ?>
                    <div class="col-md-3 mb-3">
                        <div class="card h-100 image-gallery-item">
                            <?php if($resim['varsayilan']): ?>
                                <span class="badge bg-success default-badge"><?= __('default') ?></span>
                            <?php endif; ?>
                            <a href="<?= BASE_URL . '/' . htmlspecialchars($resim['resim_yolu']) ?>" target="_blank">
                                <img src="<?= BASE_URL . '/' . htmlspecialchars($resim['resim_yolu']) ?>" class="card-img-top" alt="Ürün Resmi">
                            </a>
                            <div class="card-body text-center p-2">
                                <div class="d-flex flex-column gap-1">
                                    <form method="post" action="<?= BASE_URL ?>/ajax/resim_islemleri.php">
                                        <input type="hidden" name="urun_id" value="<?= $urun_id; ?>">
                                        <input type="hidden" name="resim_id" value="<?= $resim['id']; ?>">
                                        <input type="hidden" name="action" value="set_default">
                                        <button type="submit" class="btn btn-sm btn-outline-primary w-100" 
                                                title="<?= __('set_as_default') ?>" <?= $resim['varsayilan'] ? 'disabled' : '' ?>>
                                            <i class="bi bi-star me-1"></i><?= __('set_default') ?>
                                        </button>
                                    </form>
                                    <form method="post" action="<?= BASE_URL ?>/ajax/resim_islemleri.php" 
                                          onsubmit="return confirm('<?= __('confirm_delete_image') ?>')">
                                        <input type="hidden" name="urun_id" value="<?= $urun_id; ?>">
                                        <input type="hidden" name="resim_id" value="<?= $resim['id']; ?>">
                                        <input type="hidden" name="action" value="delete_image">
                                        <button type="submit" class="btn btn-sm btn-outline-danger w-100" title="<?= __('delete') ?>">
                                            <i class="bi bi-trash me-1"></i><?= __('delete') ?>
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>

                    <!-- Yeni Resim Ekleme -->
                    <div class="col-6 col-md-4 col-lg-3">
                        <form method="post" enctype="multipart/form-data" id="resimEkleForm">
                            <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                            <input type="file" name="yeni_resim[]" id="yeni_resim_input" class="d-none" accept="image/*" required multiple>
                            <label for="yeni_resim_input" class="upload-preview" id="uploadPreview">
                                <div>
                                    <i class="bi bi-plus-circle-dotted"></i>
                                    <br>
                                    <small><?= __('add_image') ?></small>
                                </div>
                            </label>
                            <button type="submit" class="btn btn-primary btn-sm w-100 mt-2">
                                <i class="bi bi-upload me-1"></i><?= __('upload_selected') ?>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

    </div>

    <?php include __DIR__ . '/../includes/footer.php'; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Resim yükleme önizlemesi için
        document.getElementById('yeni_resim_input').addEventListener('change', function(event) {
            const preview = document.getElementById('uploadPreview');
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.style.backgroundImage = `url(${e.target.result})`;
                    preview.innerHTML = ''; // İkonu kaldır
                }
                reader.readAsDataURL(file);
            }
        });
        document.getElementById('uploadPreview').addEventListener('click', function() {
            document.getElementById('yeni_resim_input').click();
        });
    </script>
</body>
</html>

