<?php
/**
 * NEPHRO ERP - STOK LİSTESİ (Cihaz Tasarımı Uyumlu)
 * Modern minimal tasarım, cihaz ve stok sayfalarıyla %100 uyumlu
 * Güncellendi: Birim kombobox eklendi, sayfalama hatası düzeltildi
 */
global $pdo;

if (!function_exists('h')) { function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, "UTF-8"); } }
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(32));
$CSRF = $_SESSION['csrf'];

$arama  = trim($_GET['arama'] ?? '');
$filtre = $_GET['filtre'] ?? 'all';
$sort   = $_GET['sort'] ?? 'name';
$dirRaw = strtolower($_GET['dir'] ?? 'asc');
$dir    = ($dirRaw === 'desc') ? 'DESC' : 'ASC';

$page   = max(1, (int)($_GET['p'] ?? 1));
$per    = 18;
$offset = ($page - 1) * $per;

$today = (new DateTime('today'))->format('Y-m-d');
$expiringDay = (new DateTime('today'))->modify('+30 days')->format('Y-m-d');

// ---------- WHERE ----------
$where = [];
$params = [];

if ($arama !== '') {
  $where[] = "(urun_adi LIKE ? OR barkod LIKE ? OR lot_no LIKE ?)";
  $like = "%{$arama}%";
  $params[] = $like; $params[] = $like; $params[] = $like;
}
if ($filtre === 'low') {
  $where[] = "(stok_miktari <= kritik_seviye)";
}
if ($filtre === 'expired') {
  $where[] = "(skt IS NOT NULL AND skt <> '' AND skt < ?)";
  $params[] = $today;
}
if ($filtre === 'expiring') {
  $where[] = "(skt IS NOT NULL AND skt <> '' AND skt >= ? AND skt <= ?)";
  $params[] = $today;
  $params[] = $expiringDay;
}
$sqlWhere = $where ? (" WHERE " . implode(" AND ", $where)) : "";

// ---------- SORT ----------
$sortMap = [
  'name' => 'urun_adi',
  'qty'  => 'stok_miktari',
  'skt'  => 'skt',
];
$sortCol = $sortMap[$sort] ?? 'urun_adi';

// ---------- COUNT ----------
$stmtCount = $pdo->prepare("SELECT COUNT(*) FROM stok {$sqlWhere}");
$stmtCount->execute($params);
$total = (int)$stmtCount->fetchColumn();
$totalPages = max(1, (int)ceil($total / $per));

// ---------- DATA ----------
$sql = "SELECT * FROM stok {$sqlWhere} ORDER BY {$sortCol} {$dir} LIMIT {$per} OFFSET {$offset}";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$urunler = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------- Summary ----------
$sumWhere = [];
$sumParams = [];
if ($arama !== '') {
  $sumWhere[] = "(urun_adi LIKE ? OR barkod LIKE ? OR lot_no LIKE ?)";
  $like = "%{$arama}%";
  $sumParams[] = $like; $sumParams[] = $like; $sumParams[] = $like;
}
$sumSqlWhere = $sumWhere ? (" WHERE " . implode(" AND ", $sumWhere)) : "";

$sumSql = "
  SELECT
    COUNT(*) AS total,
    SUM(stok_miktari <= kritik_seviye) AS low_count,
    SUM(skt IS NOT NULL AND skt <> '' AND skt < CURDATE()) AS expired_count,
    SUM(skt IS NOT NULL AND skt <> '' AND skt >= CURDATE() AND skt <= DATE_ADD(CURDATE(), INTERVAL 30 DAY)) AS expiring_count
  FROM stok
  {$sumSqlWhere}
";
$sumStmt = $pdo->prepare($sumSql);
$sumStmt->execute($sumParams);
$summary = $sumStmt->fetch(PDO::FETCH_ASSOC) ?: ["total"=>0,"low_count"=>0,"expired_count"=>0,"expiring_count"=>0];

// ---------- Birim Listesi (Veritabanından al) ----------
$birimler = ['Adet', 'Kutu', 'Paket', 'Koli', 'Metre', 'Kilogram', 'Gram', 'Litre', 'Mililitre', 'Takım', 'Çift', 'Rulo'];
try {
    $birimSorgu = $pdo->query("SELECT DISTINCT birim FROM stok WHERE birim IS NOT NULL AND birim != '' ORDER BY birim");
    $dbBirimler = $birimSorgu->fetchAll(PDO::FETCH_COLUMN);
    if ($dbBirimler) {
        $birimler = array_unique(array_merge($dbBirimler, $birimler));
        sort($birimler);
    }
} catch (Exception $e) {
    // Hata durumunda varsayılan birimler kullanılacak
}

// helpers
function fmt_skt($skt): string {
  if (!$skt) return '-';
  $ts = strtotime($skt);
  if (!$ts) return '-';
  return date('d.m.Y', $ts);
}
function qlink(array $overrides = []): string {
  $q = $_GET;
  foreach($overrides as $k=>$v) $q[$k] = $v;
  return "index.php?" . http_build_query($q);
}
?>

<style>
/* === Cihaz Yönetimi Stilinde Değişkenler === */
:root {
    --primary: #3b82f6;
    --primary-light: #eff6ff;
    --success: #10b981;
    --danger: #ef4444;
    --warning: #f59e0b;
    --dark: #1e293b;
    --light: #f8fafc;
    --border: #e2e8f0;
    --card: #ffffff;
    --muted: #64748b;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
}

body {
    background: var(--light);
    padding: 20px;
    color: var(--dark);
}

/* === Container === */
.container {
    max-width: 1400px;
    margin: 0 auto;
}

/* === Header === */
.header {
    margin-bottom: 30px;
}

.header h1 {
    font-size: 24px;
    font-weight: 700;
    color: var(--dark);
    margin-bottom: 5px;
}

.header p {
    color: var(--muted);
    font-size: 14px;
}

/* === Stats Grid (Cihazdaki gibi) === */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
    gap: 12px;
    margin-bottom: 30px;
}

.stat-item {
    background: var(--card);
    padding: 20px;
    border-radius: 16px;
    border: 1px solid var(--border);
    transition: all 0.2s ease;
}

.stat-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.stat-number {
    font-size: 28px;
    font-weight: 700;
    margin-bottom: 5px;
}

.stat-label {
    font-size: 12px;
    color: var(--muted);
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

/* === Search Bar (Cihazdaki gibi) === */
.search-container {
    background: var(--card);
    border-radius: 18px;
    padding: 20px;
    border: 1px solid var(--border);
    margin-bottom: 20px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
}

.search-row {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    margin-bottom: 15px;
}

.search-box {
    flex: 1;
    min-width: 300px;
    position: relative;
}

.search-box input {
    width: 100%;
    padding: 12px 45px 12px 15px;
    border: 1px solid var(--border);
    border-radius: 12px;
    font-size: 14px;
    outline: none;
    transition: all 0.2s;
}

.search-box input:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.search-box i {
    position: absolute;
    right: 15px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--muted);
}

/* === Filter Chips (Cihazdaki badge'ler gibi) === */
.filter-chips {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.chip {
    padding: 8px 16px;
    background: var(--light);
    border: 1px solid var(--border);
    border-radius: 20px;
    font-size: 13px;
    font-weight: 600;
    color: var(--muted);
    cursor: pointer;
    transition: all 0.2s;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.chip:hover {
    background: #e2e8f0;
}

.chip.active {
    background: var(--primary-light);
    border-color: var(--primary);
    color: var(--primary);
}

/* === Ürün Grid (Cihaz kartları gibi) === */
.stok-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 16px;
}

.stok-card {
    background: var(--card);
    border-radius: 18px;
    padding: 20px;
    border: 1px solid var(--border);
    position: relative;
    transition: all 0.25s ease;
}

.stok-card:hover {
    border-color: var(--primary);
    box-shadow: 0 8px 24px rgba(59, 130, 246, 0.08);
}

/* === Status Badge === */
.status-badge {
    position: absolute;
    top: 20px;
    right: 20px;
    width: 10px;
    height: 10px;
    border-radius: 50%;
}

.status-low { background: var(--danger); }
.status-expired { background: var(--warning); }
.status-normal { background: var(--success); }

/* === Card Content === */
.product-name {
    font-size: 16px;
    font-weight: 700;
    color: var(--dark);
    margin-bottom: 10px;
    line-height: 1.4;
}

.product-code {
    display: flex;
    gap: 12px;
    margin-bottom: 15px;
    flex-wrap: wrap;
}

.code-item {
    background: var(--light);
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 12px;
    color: var(--muted);
    font-weight: 600;
}

.code-item i {
    margin-right: 4px;
}

/* === Info Grid (Cihazdaki gibi) === */
.info-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    margin-bottom: 20px;
}

.info-item {
    padding: 10px;
    background: var(--light);
    border-radius: 10px;
}

.info-label {
    font-size: 10px;
    color: var(--muted);
    font-weight: 600;
    margin-bottom: 3px;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

.info-value {
    font-size: 13px;
    font-weight: 600;
    color: var(--dark);
}

/* === Stock Progress === */
.stock-progress {
    margin: 15px 0;
}

.progress-bar {
    height: 6px;
    background: #e2e8f0;
    border-radius: 3px;
    overflow: hidden;
    margin-bottom: 5px;
}

.progress-fill {
    height: 100%;
    background: var(--primary);
    border-radius: 3px;
    transition: width 0.3s ease;
}

.progress-fill.low { background: var(--danger); }
.progress-fill.expiring { background: var(--warning); }

.stock-info {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: var(--muted);
}

/* === Action Bar (Cihazdaki gibi) === */
.action-bar {
    display: flex;
    gap: 8px;
    padding-top: 18px;
    border-top: 1px solid var(--border);
}

.btn {
    flex: 1;
    padding: 10px 15px;
    border-radius: 10px;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    transition: all 0.2s ease;
    text-decoration: none;
}

.btn-edit {
    background: var(--primary-light);
    color: var(--primary);
}

.btn-edit:hover {
    background: var(--primary);
    color: white;
}

.btn-delete {
    background: #fef2f2;
    color: var(--danger);
}

.btn-delete:hover {
    background: var(--danger);
    color: white;
}

/* === FAB Button (Cihazdaki gibi) === */
.fab {
    position: fixed;
    bottom: 30px;
    right: 30px;
    width: 56px;
    height: 56px;
    background: var(--primary);
    color: white;
    border-radius: 50%;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    box-shadow: 0 6px 20px rgba(59, 130, 246, 0.3);
    transition: all 0.2s ease;
    z-index: 100;
}

.fab:hover {
    transform: scale(1.1);
    box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
}

/* === Modal (Cihazdaki gibi) === */
.modal-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(15, 23, 42, 0.7);
    backdrop-filter: blur(4px);
    z-index: 1000;
    align-items: center;
    justify-content: center;
    padding: 20px;
}

.modal-overlay.show {
    display: flex;
}

.modal-content {
    background: white;
    border-radius: 20px;
    width: 100%;
    max-width: 500px;
    animation: modalSlide 0.3s ease;
}

@keyframes modalSlide {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.modal-header {
    padding: 25px 25px 0;
}

.modal-header h3 {
    font-size: 18px;
    font-weight: 700;
    color: var(--dark);
}

.modal-body {
    padding: 25px;
}

.form-group {
    margin-bottom: 18px;
}

.form-label {
    display: block;
    font-size: 12px;
    font-weight: 600;
    color: var(--muted);
    margin-bottom: 6px;
}

.form-input {
    width: 100%;
    padding: 12px 15px;
    border: 1px solid var(--border);
    border-radius: 10px;
    font-size: 14px;
    transition: all 0.2s;
}

.form-input:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-select {
    width: 100%;
    padding: 12px 15px;
    border: 1px solid var(--border);
    border-radius: 10px;
    font-size: 14px;
    background: white;
    color: var(--dark);
    transition: all 0.2s;
}

.form-select:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
}

.btn-submit {
    width: 100%;
    padding: 14px;
    background: var(--primary);
    color: white;
    border: none;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-submit:hover {
    background: #2563eb;
}

.btn-cancel {
    width: 100%;
    padding: 10px;
    background: transparent;
    border: none;
    color: var(--muted);
    font-size: 13px;
    cursor: pointer;
    margin-top: 10px;
}

/* === Empty State (Cihazdaki gibi) === */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: var(--muted);
}

.empty-state i {
    font-size: 48px;
    color: #cbd5e1;
    margin-bottom: 20px;
}

/* === Pagination === */
.pagination {
    display: flex;
    justify-content: center;
    gap: 8px;
    flex-wrap: wrap;
    margin-top: 30px;
}

.page-btn {
    padding: 8px 16px;
    border: 1px solid var(--border);
    border-radius: 10px;
    background: var(--card);
    color: var(--dark);
    text-decoration: none;
    font-size: 14px;
    font-weight: 600;
    transition: all 0.2s;
}

.page-btn:hover {
    background: var(--light);
}

.page-btn.active {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}

/* === Mobile Responsive === */
@media (max-width: 768px) {
    body {
        padding: 10px;
    }
    
    .stok-grid {
        grid-template-columns: 1fr;
    }
    
    .search-row {
        flex-direction: column;
    }
    
    .search-box {
        min-width: 100%;
    }
    
    .form-grid {
        grid-template-columns: 1fr;
    }
}
</style>

<div class="container">
    <!-- Header -->
    <div class="header">
        <h1>Stok Envanteri</h1>
        <p>Sistemde kayıtlı tüm malzemeler ve stok durumları</p>
    </div>

    <!-- Statistics -->
    <div class="stats-grid">
        <div class="stat-item">
            <div class="stat-number"><?= $summary['total'] ?></div>
            <div class="stat-label">Toplam Malzeme</div>
        </div>
        <div class="stat-item">
            <div class="stat-number" style="color: var(--danger);"><?= $summary['low_count'] ?></div>
            <div class="stat-label">Kritik Stok</div>
        </div>
        <div class="stat-item">
            <div class="stat-number" style="color: var(--warning);"><?= $summary['expired_count'] ?></div>
            <div class="stat-label">SKT Geçmiş</div>
        </div>
        <div class="stat-item">
            <div class="stat-number" style="color: var(--warning);"><?= $summary['expiring_count'] ?></div>
            <div class="stat-label">SKT Yakın</div>
        </div>
    </div>

    <!-- Search and Filters -->
    <div class="search-container">
        <form id="filterForm" method="GET">
            <input type="hidden" name="sayfa" value="stok-liste">
            <input type="hidden" name="filtre" id="filtreInput" value="<?= h($filtre) ?>">
            <input type="hidden" name="p" value="1">

            <div class="search-row">
                <div class="search-box">
                    <input type="text" name="arama" value="<?= h($arama) ?>" 
                           placeholder="Malzeme adı, barkod veya lot no ile ara...">
                    <i class="fas fa-search"></i>
                </div>

                <div style="display: flex; gap: 10px; align-items: center;">
                    <select name="sort" onchange="this.form.submit()" class="form-select" style="width: 180px;">
                        <option value="name" <?= $sort == 'name' ? 'selected' : '' ?>>Ada Göre Sırala</option>
                        <option value="qty" <?= $sort == 'qty' ? 'selected' : '' ?>>Stok Miktarı</option>
                        <option value="skt" <?= $sort == 'skt' ? 'selected' : '' ?>>Son Kullanma Tarihi</option>
                    </select>

                    <select name="dir" onchange="this.form.submit()" class="form-select" style="width: 140px;">
                        <option value="asc" <?= strtolower($dir) == 'asc' ? 'selected' : '' ?>>Artan</option>
                        <option value="desc" <?= strtolower($dir) == 'desc' ? 'selected' : '' ?>>Azalan</option>
                    </select>
                </div>
            </div>

            <div class="filter-chips">
                <div class="chip <?= $filtre == 'all' ? 'active' : '' ?>" onclick="setFilter('all')">
                    <i class="fas fa-layer-group"></i> Tümü
                </div>
                <div class="chip <?= $filtre == 'low' ? 'active' : '' ?>" onclick="setFilter('low')">
                    <i class="fas fa-exclamation-triangle"></i> Kritik Stok
                </div>
                <div class="chip <?= $filtre == 'expired' ? 'active' : '' ?>" onclick="setFilter('expired')">
                    <i class="fas fa-hourglass-end"></i> SKT Geçmiş
                </div>
                <div class="chip <?= $filtre == 'expiring' ? 'active' : '' ?>" onclick="setFilter('expiring')">
                    <i class="fas fa-hourglass-half"></i> 30 Gün İçinde
                </div>
            </div>
        </form>
    </div>

    <!-- Product Grid -->
    <?php if (empty($urunler)): ?>
        <div class="empty-state">
            <i class="fas fa-box-open"></i>
            <h3 style="margin-bottom:10px;">Malzeme Bulunamadı</h3>
            <p>Henüz kayıtlı malzeme bulunmuyor veya arama kriterlerinize uygun malzeme yok</p>
        </div>
    <?php else: ?>
        <div class="stok-grid">
            <?php foreach ($urunler as $u):
                $qty = (float)($u['stok_miktari'] ?? 0);
                $kritik = (float)($u['kritik_seviye'] ?? 0);
                $is_low = ($kritik > 0 && $qty <= $kritik);

                $sktRaw = $u['skt'] ?? null;
                $sktTs = $sktRaw ? strtotime($sktRaw) : false;
                $is_expired = ($sktTs && $sktTs < strtotime($today));
                $is_expiring = ($sktTs && $sktTs >= strtotime($today) && $sktTs <= strtotime($expiringDay));

                $den = ($kritik > 0 ? ($kritik * 2) : 100);
                $pct = $den > 0 ? max(0, min(100, ($qty / $den) * 100)) : 0;

                $payload = [
                    "id" => (int)$u["id"],
                    "urun_adi" => (string)($u["urun_adi"] ?? ""),
                    "barkod" => (string)($u["barkod"] ?? ""),
                    "lot_no" => (string)($u["lot_no"] ?? ""),
                    "skt" => (string)($u["skt"] ?? ""),
                    "stok_miktari" => (string)($u["stok_miktari"] ?? ""),
                    "kritik_seviye" => (string)($u["kritik_seviye"] ?? ""),
                    "birim" => (string)($u["birim"] ?? ""),
                ];

                $statusClass = 'status-normal';
                if ($is_low) $statusClass = 'status-low';
                if ($is_expired || $is_expiring) $statusClass = 'status-expired';
            ?>
                <div class="stok-card">
                    <div class="status-badge <?= $statusClass ?>"></div>
                    
                    <div class="product-name"><?= h($u['urun_adi']) ?></div>
                    
                    <div class="product-code">
                        <div class="code-item">
                            <i class="fas fa-barcode"></i> <?= h($u['barkod'] ?: '-') ?>
                        </div>
                        <div class="code-item">
                            <i class="fas fa-tag"></i> LOT: <?= h($u['lot_no'] ?: '-') ?>
                        </div>
                    </div>

                    <div class="info-grid">
                        <div class="info-item">
                            <div class="info-label">Son Kullanma Tarihi</div>
                            <div class="info-value"><?= h(fmt_skt($u['skt'] ?? null)) ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Kritik Seviye</div>
                            <div class="info-value"><?= h($u['kritik_seviye'] ?? '-') ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Birim</div>
                            <div class="info-value"><?= h($u['birim'] ?? 'Adet') ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Durum</div>
                            <div class="info-value" style="color: <?=
                                $is_low ? 'var(--danger)' :
                                ($is_expired ? 'var(--warning)' :
                                ($is_expiring ? 'var(--warning)' : 'var(--success)'))
                            ?>">
                                <?=
                                    $is_low ? 'KRİTİK' :
                                    ($is_expired ? 'SKT GEÇMİŞ' :
                                    ($is_expiring ? 'SKT YAKIN' : 'NORMAL'))
                                ?>
                            </div>
                        </div>
                    </div>

                    <div class="stock-progress">
                        <div class="stock-info">
                            <span>Stok Seviyesi: <?= h($u['stok_miktari']) ?> <?= h($u['birim'] ?? '') ?></span>
                            <span><?= round($pct) ?>%</span>
                        </div>
                        <div class="progress-bar">
                            <div class="progress-fill <?= $is_low ? 'low' : ($is_expiring ? 'expiring' : '') ?>" 
                                 style="width: <?= $pct ?>%"></div>
                        </div>
                    </div>

                    <div class="action-bar">
                        <a href="index.php?sayfa=stok-hareket&urun_id=<?= (int)$u['id'] ?>" 
                           class="btn btn-edit" title="Hareket Geçmişi">
                            <i class="fas fa-history"></i> Geçmiş
                        </a>
                        
                        <button type="button" class="btn btn-edit" onclick="openEdit(<?= htmlspecialchars(json_encode($payload), ENT_QUOTES, 'UTF-8') ?>)">
                            <i class="fas fa-edit"></i> Düzenle
                        </button>
                        
                        <form method="POST" action="islem.php" style="display: contents;"
                              onsubmit="return confirm('Bu malzemeyi silmek istediğinize emin misiniz?')">
                            <input type="hidden" name="_csrf" value="<?= h($CSRF) ?>">
                            <input type="hidden" name="islem" value="stok_sil">
                            <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">
                            <button type="submit" class="btn btn-delete" title="Sil">
                                <i class="fas fa-trash"></i> Sil
                            </button>
                        </form>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <!-- Pagination (DÜZELTİLDİ) -->
    <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="<?= h(qlink(['p' => $page - 1])) ?>" class="page-btn">
                    <i class="fas fa-chevron-left"></i>
                </a>
            <?php endif; ?>

            <?php
            $start = max(1, $page - 2);
            $end = min($totalPages, $page + 2);
            
            if ($start > 1) {
                echo '<a href="' . h(qlink(['p' => 1])) . '" class="page-btn">1</a>';
                if ($start > 2) {
                    echo '<span class="page-btn" style="cursor: default; opacity: 0.6;">...</span>';
                }
            }
            
            for ($i = $start; $i <= $end; $i++):
                $active = $i == $page ? ' active' : '';
            ?>
                <a href="<?= h(qlink(['p' => $i])) ?>" class="page-btn<?= $active ?>">
                    <?= $i ?>
                </a>
            <?php endfor; ?>
            
            <?php if ($end < $totalPages): ?>
                <?php if ($end < $totalPages - 1): ?>
                    <span class="page-btn" style="cursor: default; opacity: 0.6;">...</span>
                <?php endif; ?>
                <a href="<?= h(qlink(['p' => $totalPages])) ?>" class="page-btn">
                    <?= $totalPages ?>
                </a>
            <?php endif; ?>

            <?php if ($page < $totalPages): ?>
                <a href="<?= h(qlink(['p' => $page + 1])) ?>" class="page-btn">
                    <i class="fas fa-chevron-right"></i>
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<!-- FAB Button -->
<button class="fab" onclick="openModal('addModal')">
    <i class="fas fa-plus"></i>
</button>

<!-- Add/Edit Modal -->
<div class="modal-overlay" id="addModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">Yeni Malzeme Ekle</h3>
        </div>
        
        <form id="productForm" method="POST" action="islem.php">
            <input type="hidden" name="_csrf" value="<?= h($CSRF) ?>">
            <input type="hidden" name="islem" id="modalIslem" value="stok_ekle">
            <input type="hidden" name="id" id="f_id" value="">

            <div class="modal-body">
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Ürün Adı *</label>
                        <input type="text" name="urun_adi" id="f_urun_adi" class="form-input" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Barkod</label>
                        <input type="text" name="barkod" id="f_barkod" class="form-input">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Lot No</label>
                        <input type="text" name="lot_no" id="f_lot_no" class="form-input">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Son Kullanma Tarihi</label>
                        <input type="date" name="skt" id="f_skt" class="form-input">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Stok Miktarı *</label>
                        <input type="number" step="0.01" name="stok_miktari" id="f_stok_miktari" class="form-input" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Kritik Seviye</label>
                        <input type="number" step="0.01" name="kritik_seviye" id="f_kritik_seviye" class="form-input" value="0">
                    </div>

                    <!-- BİRİM KOMBOBOX EKLENDİ -->
                    <div class="form-group">
                        <label class="form-label">Birim</label>
                        <select name="birim" id="f_birim" class="form-select">
                            <option value="">Birim Seçiniz</option>
                            <?php foreach ($birimler as $birim): ?>
                                <option value="<?= h($birim) ?>"><?= h($birim) ?></option>
                            <?php endforeach; ?>
                            <option value="other">Diğer...</option>
                        </select>
                        <input type="text" name="birim_other" id="f_birim_other" class="form-input" 
                               placeholder="Diğer birim giriniz" style="margin-top: 8px; display: none;">
                    </div>
                </div>
            </div>

            <div style="padding: 0 25px 25px;">
                <button type="submit" class="btn-submit" id="modalSubmitBtn">
                    <i class="fas fa-save"></i> Kaydet
                </button>
                <button type="button" class="btn-cancel" onclick="closeModal('addModal')">
                    İptal
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Font Awesome Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">

<script>
// Modal Functions
function openModal(id) {
    document.getElementById(id).classList.add('show');
}

function closeModal(id) {
    document.getElementById(id).classList.remove('show');
}

// Open modal when clicking outside
document.getElementById('addModal').addEventListener('click', function(e) {
    if (e.target === this) closeModal('addModal');
});

// Search debounce
(function() {
    const form = document.getElementById('filterForm');
    if (!form) return;
    
    let timeout = null;
    const searchInput = form.querySelector('input[name="arama"]');
    
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                form.submit();
            }, 350);
        });
    }
})();

// Filter functions
function setFilter(filter) {
    document.getElementById('filtreInput').value = filter;
    document.getElementById('filterForm').submit();
}

// Edit product
function openEdit(product) {
    document.getElementById('modalTitle').textContent = 'Malzeme Düzenle';
    document.getElementById('modalIslem').value = 'stok_guncelle';
    document.getElementById('modalSubmitBtn').innerHTML = '<i class="fas fa-check"></i> Güncelle';
    
    document.getElementById('f_id').value = product.id || '';
    document.getElementById('f_urun_adi').value = product.urun_adi || '';
    document.getElementById('f_barkod').value = product.barkod || '';
    document.getElementById('f_lot_no').value = product.lot_no || '';
    document.getElementById('f_skt').value = product.skt ? product.skt.substring(0, 10) : '';
    document.getElementById('f_stok_miktari').value = product.stok_miktari || '';
    document.getElementById('f_kritik_seviye').value = product.kritik_seviye || '0';
    
    // Birim seçimi
    const birimSelect = document.getElementById('f_birim');
    const birimOtherInput = document.getElementById('f_birim_other');
    const birimValue = product.birim || '';
    
    // Mevcut birim listede var mı kontrol et
    let found = false;
    for (let i = 0; i < birimSelect.options.length; i++) {
        if (birimSelect.options[i].value === birimValue) {
            birimSelect.value = birimValue;
            found = true;
            birimOtherInput.style.display = 'none';
            break;
        }
    }
    
    // Eğer listede yoksa "Diğer" seçeneğini aktif et
    if (!found && birimValue) {
        birimSelect.value = 'other';
        birimOtherInput.value = birimValue;
        birimOtherInput.style.display = 'block';
    } else if (!birimValue) {
        birimSelect.value = '';
        birimOtherInput.style.display = 'none';
    }
    
    openModal('addModal');
}

// Reset form for new product
function resetToAdd() {
    document.getElementById('modalTitle').textContent = 'Yeni Malzeme Ekle';
    document.getElementById('modalIslem').value = 'stok_ekle';
    document.getElementById('modalSubmitBtn').innerHTML = '<i class="fas fa-save"></i> Kaydet';
    
    document.getElementById('f_id').value = '';
    document.getElementById('f_urun_adi').value = '';
    document.getElementById('f_barkod').value = '';
    document.getElementById('f_lot_no').value = '';
    document.getElementById('f_skt').value = '';
    document.getElementById('f_stok_miktari').value = '';
    document.getElementById('f_kritik_seviye').value = '0';
    document.getElementById('f_birim').value = '';
    document.getElementById('f_birim_other').value = '';
    document.getElementById('f_birim_other').style.display = 'none';
}

// Birim seçimi değiştiğinde "Diğer" input'unu göster/gizle
document.getElementById('f_birim').addEventListener('change', function() {
    const otherInput = document.getElementById('f_birim_other');
    if (this.value === 'other') {
        otherInput.style.display = 'block';
        otherInput.focus();
    } else {
        otherInput.style.display = 'none';
        otherInput.value = '';
    }
});

// Form gönderilirken birim değerini ayarla
document.getElementById('productForm').addEventListener('submit', function(e) {
    const birimSelect = document.getElementById('f_birim');
    const birimOther = document.getElementById('f_birim_other');
    
    if (birimSelect.value === 'other' && birimOther.value.trim()) {
        // "Diğer" seçeneği seçilmiş ve değer girilmiş
        // Input'u hidden field olarak ekle
        const hiddenInput = document.createElement('input');
        hiddenInput.type = 'hidden';
        hiddenInput.name = 'birim';
        hiddenInput.value = birimOther.value.trim();
        this.appendChild(hiddenInput);
        
        // Select'i disabled yap ki gönderilmesin
        birimSelect.disabled = true;
    } else if (birimSelect.value === 'other' && !birimOther.value.trim()) {
        // "Diğer" seçilmiş ama değer girilmemiş, varsayılan birim ata
        e.preventDefault();
        alert('Lütfen bir birim giriniz veya listeden seçiniz.');
        birimOther.focus();
        return false;
    }
    // Diğer durumlarda normal birim değeri gönderilecek
});

// FAB button click
document.querySelector('.fab').addEventListener('click', function() {
    resetToAdd();
    openModal('addModal');
});

// ESC key closes modal
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeModal('addModal');
    }
});
</script>