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

$sayfa_baslik = __("add_product");

// 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 = [];
        }
    }
}
$paraBirimi = getParaBirimiSembolu($sirket_para_birimi);

// Stok ayarlarını getir
$ikinci_fiyat_aktif = '0';
$stok_resim_yukleme_aktif = '0';
$stok_resim_yukleme_dizin = 'uploads/urun_resimleri';

try {
    $stmt = $db->prepare("SELECT ayar_degeri FROM ayarlar WHERE ayar_adi = 'ikinci_fiyat_kdv_aktif'");
    $stmt->execute();
    $ikinci_fiyat_aktif = $stmt->fetchColumn() ?: '0';

    $stmt = $db->prepare("SELECT ayar_degeri FROM ayarlar WHERE ayar_adi = 'stok_resim_yukleme_aktif'");
    $stmt->execute();
    $stok_resim_yukleme_aktif = $stmt->fetchColumn() ?: '0';

    $stmt = $db->prepare("SELECT ayar_degeri FROM ayarlar WHERE ayar_adi = 'stok_resim_yukleme_dizin'");
    $stmt->execute();
    $stok_resim_yukleme_dizin = $stmt->fetchColumn() ?: 'uploads/urun_resimleri';
} catch (PDOException $e) {
    error_log("Stok ayarları getirme hatası: " . $e->getMessage());
    $ikinci_fiyat_aktif = '0';
    $stok_resim_yukleme_aktif = '0';
    $stok_resim_yukleme_dizin = 'uploads/urun_resimleri';
}

// Depo yönetimi modülünü kontrol et
$depo_yonetimi_aktif = depoYonetimiAktifMi($db, $_SESSION['aktif_sirket_id']);
$depolar = [];
$raflar = [];
if ($depo_yonetimi_aktif) {
    $depolar = depoGetir($db, $_SESSION['aktif_sirket_id']);
    $raflar = rafGetir($db, $_SESSION['aktif_sirket_id']);
}

// Form gönderildiğinde
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!csrf_token_dogrula($_POST['csrf_token'] ?? '')) {
        $_SESSION['hata'] = __("invalid_form_submission");
        header("Location: urun_ekle.php");
        exit();
    }

    // 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[] = __("invalid_price");
    }
    if ($urun_bilgileri['satis_fiyati'] === false || $urun_bilgileri['satis_fiyati'] < 0) {
        $hatalar[] = __("invalid_price");
    }
    if ($urun_bilgileri['kdv_orani'] === false || $urun_bilgileri['kdv_orani'] < 0 || $urun_bilgileri['kdv_orani'] > 100) {
        $hatalar[] = __("invalid_vat_rate");
    }
    if ($urun_bilgileri['kritik_stok'] === false || $urun_bilgileri['kritik_stok'] < 0) {
        $hatalar[] = __("invalid_stock_value");
    }

    // Barkod kontrolü (varsa)
    if (!empty($urun_bilgileri['barkod'])) {
        try {
            $stmt = $db->prepare("SELECT id FROM urunler WHERE barkod = ? AND sirket_id = ? AND aktif = 1");
            $stmt->execute([$urun_bilgileri['barkod'], $_SESSION['aktif_sirket_id']]);
            if ($stmt->fetch()) {
                $hatalar[] = __("barcode_already_exists");
            }
        } catch (PDOException $e) {
            $hatalar[] = "Barkod kontrolü yapılamadı.";
        }
    }

    // Hata yoksa ürünü ekle
    if (empty($hatalar)) {
        $urun_id = urunEkle($db, $urun_bilgileri, $_SESSION['aktif_sirket_id']);
        if ($urun_id) {
            // Depo/Raf yönetimi aktifse ve seçim yapılmışsa kaydet
            if ($depo_yonetimi_aktif) {
                $depo_id = filter_input(INPUT_POST, 'depo_id', FILTER_VALIDATE_INT) ?: null;
                $raf_id = filter_input(INPUT_POST, 'raf_id', FILTER_VALIDATE_INT) ?: null;
                $baslangic_stok = $urun_bilgileri['mevcut_stok_baslangic'];
                
                if (($depo_id || $raf_id) && $baslangic_stok > 0) {
                    urunDepoRafEkle($db, $urun_id, $depo_id, $raf_id, $baslangic_stok, $_SESSION['aktif_sirket_id']);
                }
            }
            
            // Resim yükleme aktifse ve resimler yüklendiyse
            if ($stok_resim_yukleme_aktif == '1' && isset($_FILES['urun_resimleri']) && !empty($_FILES['urun_resimleri']['name'][0])) {
                if (!resimYukle($db, $urun_id, $_SESSION['aktif_sirket_id'], $_FILES['urun_resimleri'], $stok_resim_yukleme_dizin)) {
                    $_SESSION['hata'] = __("image_upload_error");
                }
            }
            $_SESSION['mesaj'] = __("product_added_success");
            header("Location: urunler.php");
            exit();
        } else {
            $_SESSION['hata'] = __("error_adding_product");
        }
    } else {
        $_SESSION['form_hatalari'] = $hatalar;
        $_SESSION['form_verileri'] = $_POST;
    }
}

// Kategorileri getir
try {
    $stmt = $db->prepare("SELECT id, kategori_adi FROM kategoriler WHERE sirket_id = ? AND tip = 'urun' ORDER BY kategori_adi");
    $stmt->execute([$_SESSION['aktif_sirket_id']]);
    $kategoriler = $stmt->fetchAll();
} catch (PDOException $e) {
    error_log("Kategori listesi hatası: " . $e->getMessage());
    $kategoriler = [];
}

// Markaları getir
try {
    $stmt = $db->prepare("SELECT id, marka_adi FROM markalar WHERE sirket_id = ? ORDER BY marka_adi");
    $stmt->execute([$_SESSION['aktif_sirket_id']]);
    $markalar = $stmt->fetchAll();
} catch (PDOException $e) {
    error_log("Marka listesi hatası: " . $e->getMessage());
    $markalar = [];
}



$csrf_token = csrf_token_olustur();
$form_hatalari = $_SESSION['form_hatalari'] ?? [];
$form_verileri = $_SESSION['form_verileri'] ?? [];
unset($_SESSION['form_hatalari'], $_SESSION['form_verileri']);
?>
<!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;
        }

        .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;
            height: auto;
        }

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

        .input-group .btn {
            border-radius: 0 2px 2px 0;
            border: 1px solid #3b82f6;
            border-left: none;
            padding: 0.5rem 0.875rem;
            font-size: 0.875rem;
        }

        .input-group .form-control {
            border-radius: 2px 0 0 2px;
        }

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

        textarea.form-control {
            min-height: 80px;
        }

        .alert {
            border-radius: 2px;
            border: none;
            padding: 1rem 1.25rem;
            margin-bottom: 2rem;
        }

        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
        }

        .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-secondary {
            background: #f1f5f9;
            color: #475569;
            border: none;
            border-radius: 2px;
            padding: 0.625rem 1.25rem;
            font-weight: 600;
            font-size: 0.875rem;
        }

        .btn-secondary:hover {
            background: #e2e8f0;
            color: #334155;
        }

        .image-preview-card {
            border-radius: 2px;
            overflow: hidden;
            border: 1px solid #e2e8f0;
        }

        .image-preview-card img {
            height: 140px;
            object-fit: contain;
            background: #f8fafc;
        }

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

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

            .card-section {
                padding: 1.25rem;
            }

            .form-control, .form-select {
                padding: 0.45rem 0.65rem;
                font-size: 0.8125rem;
            }

            .btn-primary, .btn-secondary {
                padding: 0.5rem 1rem;
                font-size: 0.8125rem;
            }
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

    <div class="container mt-4 mb-5">
        <div class="page-header">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                <h2><i class="bi bi-plus-circle me-2"></i><?= temizle($sayfa_baslik) ?></h2>
                <a href="urunler.php" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left me-2"></i>Ürün Listesi
                </a>
            </div>
        </div>

        <?php if (!empty($form_hatalari)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <div class="d-flex align-items-start">
                    <i class="bi bi-exclamation-triangle-fill me-3" style="font-size: 1.25rem;"></i>
                    <div class="flex-grow-1">
                        <strong><?= __('please_fix_errors') ?>:</strong>
                        <ul class="mb-0 mt-2">
                            <?php foreach ($form_hatalari as $hata): ?>
                                <li><?= htmlspecialchars($hata) ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="<?= __('close') ?>"></button>
            </div>
        <?php endif; ?>

        <div class="modern-card">
            <div class="card-section">
                <div class="section-title">
                    <i class="bi bi-box-seam"></i>
                    <span><?= __('product_information') ?></span>
                </div>
                <form method="post" id="urunForm" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                    
                    <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'] ?? '') ?>">
                                </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-6">
                                    <label for="barkod" class="form-label"><?= __('barcode') ?></label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="barkod" name="barkod"
                                               value="<?= htmlspecialchars($form_verileri['barkod'] ?? '') ?>">
                                        <button type="button" class="btn btn-outline-primary" id="barkodOkuBtn">
                                            <i class="bi bi-upc-scan"></i> <?= __('barcode_scan') ?>
                                        </button>
                                    </div>
                                    <div class="form-text"><?= __('barcode_scan_help') ?></div>
                                </div>
                                <div class="col-md-3">
                                    <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-3">
                                    <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="alis_fiyati" class="form-label"><?= __('purchase_price') ?> <span class="text-danger">*</span></label>
    <input type="number" step="0.01" class="form-control" id="alis_fiyati" name="alis_fiyati" required value="<?= htmlspecialchars($form_verileri['alis_fiyati'] ?? '') ?>">
</div>
<?php if ($coklu_para_birimi): ?>
<div class="col-md-2">
    <label for="alis_para_birimi" class="form-label"><?= __('currency') ?></label>
    <select class="form-select" id="alis_para_birimi" name="alis_para_birimi" required>
        <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'] ?? '') == $pb ? 'selected' : '' ?>><?= $pb ?></option>
        <?php endforeach; ?>
    </select>
</div>
<?php else: ?>
    <input type="hidden" name="alis_para_birimi" value="<?= htmlspecialchars($sirket_para_birimi) ?>">
<?php endif; ?>
                                <div class="col-md-4">
    <label for="satis_fiyati" class="form-label"><?= __('sale_price') ?></label>
    <input type="text" inputmode="decimal" class="form-control" id="satis_fiyati" name="satis_fiyati"
           value="<?= htmlspecialchars($form_verileri['satis_fiyati'] ?? '0.00') ?>">
</div>
<?php if ($coklu_para_birimi): ?>
<div class="col-md-2">
    <label for="satis_para_birimi" class="form-label"><?= __('currency') ?></label>
    <select class="form-select" id="satis_para_birimi" name="satis_para_birimi" required>
        <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'] ?? '') == $pb ? 'selected' : '' ?>><?= $pb ?></option>
        <?php endforeach; ?>
    </select>
</div>
<?php else: ?>
    <input type="hidden" name="satis_para_birimi" value="<?= htmlspecialchars($sirket_para_birimi) ?>">
<?php endif; ?>
                                <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 (<?= __('vat_free') ?>)</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-md-4">
                                    <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-4">
                                    <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" min="0"
                                           value="<?= htmlspecialchars($form_verileri["mevcut_stok_baslangic"] ?? "0") ?>">
                                    <div class="form-text"><?= __('initial_stock_note') ?></div>
                                </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">
                                        <option value="">-- <?= __('select_warehouse') ?> --</option>
                                        <?php foreach ($depolar as $depo): ?>
                                            <option value="<?= $depo['id'] ?>" 
                                                    <?= ($form_verileri['depo_id'] ?? '') == $depo['id'] ? 'selected' : '' ?>>
                                                <?= temizle($depo['depo_adi']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="form-text"><?= __('warehouse_shelf_info') ?></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">
                                        <option value="">-- <?= __('select_shelf') ?> --</option>
                                        <?php foreach ($raflar as $raf): ?>
                                            <option value="<?= $raf['id'] ?>" 
                                                    <?= ($form_verileri['raf_id'] ?? '') == $raf['id'] ? 'selected' : '' ?>>
                                                <?= temizle($raf['raf_adi']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="form-text"><?= __('warehouse_shelf_info') ?></div>
                                </div>
                                <?php endif; ?>

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

                    </div>
                </form>
            </div>

            <?php if ($stok_resim_yukleme_aktif == '1'): ?>
            <div class="card-section">
                <div class="section-title">
                    <i class="bi bi-image"></i>
                    <span><?= __('product_images') ?></span>
                </div>
                <div class="mb-3">
                    <label for="urun_resimleri" class="form-label"><?= __('upload_image') ?></label>
                    <input class="form-control" type="file" id="urun_resimleri" name="urun_resimleri[]" multiple accept="image/*" form="urunForm">
                    <div class="form-text"><?= __('multiple_images_help') ?></div>
                </div>
                <div id="resim_onizleme" class="row row-cols-1 row-cols-md-3 g-4"></div>
            </div>
            <?php endif; ?>

            <div class="card-section">
                <div class="d-flex gap-3 flex-wrap">
                    <button type="submit" class="btn btn-primary" form="urunForm">
                        <i class="bi bi-save me-2"></i><?= __('save_product') ?>
                    </button>
                    <a href="urunler.php" class="btn btn-secondary">
                        <i class="bi bi-x-circle me-2"></i><?= __('cancel') ?>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/quagga@0.12.1/dist/quagga.min.js"></script>
    <script src="js/barkod-okuyucu.js"></script>
    
    <script>
        let barkodOkuyucu;

        document.addEventListener("DOMContentLoaded", function() {
            // Barkod okuyucuyu başlat
            barkodOkuyucu = new BarkodOkuyucu();
            barkodOkuyucu.init(function(barkod) {
                document.getElementById("barkod").value = barkod;
            });

            // Barkod oku butonuna tıklandığında
            document.getElementById("barkodOkuBtn").addEventListener("click", function() {
                barkodOkuyucu.show();
            });
        });

        // Fiyat hesaplama yardımcısı
        document.getElementById("alis_fiyati").addEventListener("blur", function() {
            const alisFiyati = parseFloat(this.value) || 0;
            const satisFiyatiInput = document.getElementById("satis_fiyati");
            
            // Eğer satış fiyatı boşsa, %30 kar marjı ile otomatik hesapla
            if (!satisFiyatiInput.value || parseFloat(satisFiyatiInput.value) === 0) {
                const satisFiyati = alisFiyati * 1.3; // %30 kar marjı
                satisFiyatiInput.value = satisFiyati.toFixed(2);
            }
        });

        // Resim önizleme
        const urunResimleriInput = document.getElementById("urun_resimleri");
        const resimOnizlemeDiv = document.getElementById("resim_onizleme");

        if (urunResimleriInput) {
            urunResimleriInput.addEventListener("change", function() {
                resimOnizlemeDiv.innerHTML = ""; // Önceki önizlemeleri temizle
                if (this.files) {
                    Array.from(this.files).forEach(file => {
                        if (file.type.startsWith("image/")) {
                            const reader = new FileReader();
                            reader.onload = function(e) {
                                const colDiv = document.createElement("div");
                                colDiv.className = "col";
                                colDiv.innerHTML = `
                                    <div class="image-preview-card">
                                        <img src="${e.target.result}" class="w-100" alt="Resim Önizleme">
                                    </div>
                                `;
                                resimOnizlemeDiv.appendChild(colDiv);
                            };
                            reader.readAsDataURL(file);
                        }
                    });
                }
            });
        }
    </script>
    
    <?php include __DIR__ . '/../includes/footer.php'; ?>
</body>
</html>
