<?php
/**
 * NEPHRO ERP - CİHAZ BAKIM GEÇMİŞİ (FULL WIDTH + layout bozmayan scoped CSS)
 */
global $pdo;

if (!function_exists('h')) {
    function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, "UTF-8"); }
}

/** -------------------------------------------------
 *  Filtre Parametreleri
 * ------------------------------------------------- */
$sayfa = $_GET['sayfa'] ?? '';

$q         = trim($_GET['q'] ?? '');
$cihaz_id  = (int)($_GET['cihaz_id'] ?? 0);
$tip       = trim($_GET['tip'] ?? '');
$t1        = trim($_GET['t1'] ?? '');
$t2        = trim($_GET['t2'] ?? '');
$due       = trim($_GET['due'] ?? '');

$allowed_tip = ['periyodik','ariza','kalibrasyon','parca_degisim','diger'];
if ($tip !== '' && !in_array($tip, $allowed_tip, true)) $tip = '';

/** -------------------------------------------------
 *  Cihaz listesi (dropdown için)
 * ------------------------------------------------- */
$cihazList = $pdo->query("SELECT id, marka_model, seri_no, oda_no FROM cihazlar ORDER BY oda_no ASC, marka_model ASC")
                 ->fetchAll(PDO::FETCH_ASSOC);

/** -------------------------------------------------
 *  URL builder
 * ------------------------------------------------- */
function buildUrl(array $set = [], array $unset = []) {
    $qs = $_GET;
    foreach ($unset as $k) unset($qs[$k]);
    foreach ($set as $k => $v) {
        if ($v === null || $v === '') unset($qs[$k]);
        else $qs[$k] = $v;
    }
    if (!empty($_GET['sayfa'])) $qs['sayfa'] = $_GET['sayfa'];
    return "?" . http_build_query($qs);
}

/** -------------------------------------------------
 *  İstatistikler (genel)
 * ------------------------------------------------- */
$monthStart = date('Y-m-01');
$monthEnd   = date('Y-m-t');

$istat = $pdo->query("
    SELECT
      (SELECT COUNT(*) FROM cihaz_bakimlari) AS toplam_bakim,
      (SELECT COUNT(*) FROM cihaz_bakimlari WHERE bakim_tarihi BETWEEN '$monthStart' AND '$monthEnd') AS bu_ay,
      (SELECT COUNT(*) FROM cihaz_bakimlari WHERE sonraki_bakim_tarihi IS NOT NULL AND sonraki_bakim_tarihi <= DATE_ADD(CURDATE(), INTERVAL 30 DAY)) AS yaklasan,
      (SELECT IFNULL(SUM(maliyet),0) FROM cihaz_bakimlari WHERE bakim_tarihi BETWEEN '$monthStart' AND '$monthEnd') AS bu_ay_maliyet
")->fetch(PDO::FETCH_ASSOC);

$istat = $istat ?: ['toplam_bakim'=>0,'bu_ay'=>0,'yaklasan'=>0,'bu_ay_maliyet'=>0];

/** -------------------------------------------------
 *  Liste sorgusu (filtreli)
 * ------------------------------------------------- */
$where = [];
$params = [];

if ($q !== '') {
    $where[] = "(c.marka_model LIKE ? OR c.seri_no LIKE ? OR c.oda_no LIKE ? OR b.servis_firma LIKE ? OR b.yapan_kisi LIKE ? OR b.aciklama LIKE ?)";
    for ($i=0;$i<6;$i++) $params[] = "%$q%";
}
if ($cihaz_id > 0) { $where[] = "b.cihaz_id = ?"; $params[] = $cihaz_id; }
if ($tip !== '')   { $where[] = "b.bakim_tipi = ?"; $params[] = $tip; }
if ($t1 !== '')    { $where[] = "b.bakim_tarihi >= ?"; $params[] = $t1; }
if ($t2 !== '')    { $where[] = "b.bakim_tarihi <= ?"; $params[] = $t2; }
if ($due === '1')  { $where[] = "(b.sonraki_bakim_tarihi IS NOT NULL AND b.sonraki_bakim_tarihi <= DATE_ADD(CURDATE(), INTERVAL 30 DAY))"; }

$whereSql = $where ? (" WHERE " . implode(" AND ", $where)) : "";

$stmt = $pdo->prepare("
    SELECT b.*, c.marka_model, c.seri_no AS cihaz_seri_no, c.oda_no
    FROM cihaz_bakimlari b
    INNER JOIN cihazlar c ON c.id = b.cihaz_id
    $whereSql
    ORDER BY b.bakim_tarihi DESC, b.id DESC
");
$stmt->execute($params);
$bakimlar = $stmt->fetchAll(PDO::FETCH_ASSOC);

$liste_sayisi = count($bakimlar);

/** aktif filtre highlight */
$isAll       = ($q==='' && $cihaz_id===0 && $tip==='' && $t1==='' && $t2==='' && $due!=='1');
$isThisMonth = ($t1===$monthStart && $t2===$monthEnd);
$isDue       = ($due==='1');
?>

<!-- İkonlar -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<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;900&display=swap" rel="stylesheet">

<style>
/* ✅ SCOPE: Bu CSS sadece bu sayfayı etkiler, panel header/sidebar bozulmaz */
.page-bakim{
    --primary:#3b82f6;
    --primary-600:#2563eb;
    --primary-light:#eff6ff;
    --success:#10b981;
    --danger:#ef4444;
    --warning:#f59e0b;
    --dark:#0f172a;
    --text:#1e293b;
    --muted:#64748b;
    --light:#f8fafc;
    --border:#e2e8f0;
    --card:#ffffff;

    font-family:'Inter',-apple-system,BlinkMacSystemFont,sans-serif;
    color:var(--text);
    width:100%;
    min-width:0;
    padding:18px 22px 92px;
    overflow-x:clip;
}

/* Layout içinde Bootstrap .container daraltıyorsa: full width override */
.page-bakim .container,
.page-bakim .container-fluid,
.page-bakim .content-container,
.page-bakim .page-container{
    width:100% !important;
    max-width:100% !important;
    margin:0 !important;
    padding:0 !important;
}

.page-bakim *{ box-sizing:border-box; }

.page-bakim .header{
    margin-bottom:16px;
}
.page-bakim .header h1{
    font-size:clamp(18px,2vw,24px);
    font-weight:900;
    letter-spacing:-.3px;
    color:var(--dark);
    margin:0 0 6px;
}
.page-bakim .header p{
    color:var(--muted);
    font-size:13px;
    margin:0;
}

/* Stats */
.page-bakim .stats-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(170px,1fr));
    gap:12px;
    margin:14px 0;
}
.page-bakim .stat-item{
    background:var(--card);
    padding:16px;
    border-radius:16px;
    border:1px solid var(--border);
    transition:.2s;
    text-decoration:none;
    display:block;
    box-shadow:0 4px 12px rgba(0,0,0,.02);
}
.page-bakim .stat-item:hover{
    transform:translateY(-2px);
    box-shadow:0 12px 26px rgba(2,6,23,.06);
    border-color:rgba(59,130,246,.28);
}
.page-bakim .stat-item.active-filter{
    border-color:var(--primary);
    box-shadow:0 10px 26px rgba(59,130,246,.12);
}
.page-bakim .stat-number{
    font-size:26px;
    font-weight:900;
    letter-spacing:-.4px;
    margin-bottom:6px;
    color:var(--dark);
}
.page-bakim .stat-label{
    font-size:12px;
    color:var(--muted);
    font-weight:800;
    text-transform:uppercase;
    letter-spacing:.5px;
}

/* Filter Bar */
.page-bakim .filter-bar{
    background:var(--card);
    border:1px solid var(--border);
    border-radius:16px;
    padding:14px;
    display:grid;
    grid-template-columns: 1.4fr 1.1fr 1fr 1fr 1fr auto;
    gap:10px;
    align-items:center;
    margin-bottom:18px;
    box-shadow:0 4px 12px rgba(0,0,0,.03);
}
.page-bakim .filter-input,
.page-bakim .filter-select,
.page-bakim .filter-date{
    width:100%;
    padding:11px 12px;
    border:1px solid var(--border);
    border-radius:12px;
    font-size:13px;
    font-weight:650;
    transition:.2s;
    background:#fff;
    color:var(--dark);
}
.page-bakim .filter-input:focus,
.page-bakim .filter-select:focus,
.page-bakim .filter-date:focus{
    outline:none;
    border-color:var(--primary);
    box-shadow:0 0 0 3px rgba(59,130,246,.10);
}
.page-bakim .clear-btn{
    padding:10px 12px;
    border-radius:12px;
    border:1px solid var(--border);
    background:#fff;
    cursor:pointer;
    font-size:12px;
    font-weight:900;
    color:#475569;
    transition:.2s;
    white-space:nowrap;
}
.page-bakim .clear-btn:hover{
    border-color:rgba(59,130,246,.45);
    color:var(--primary-600);
    box-shadow:0 10px 22px rgba(59,130,246,.10);
}
.page-bakim .filter-meta{
    grid-column:1 / -1;
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:10px;
    padding-top:10px;
    border-top:1px solid #f1f5f9;
    color:var(--muted);
    font-size:12px;
    font-weight:700;
}
.page-bakim .filter-badges{
    display:flex;
    flex-wrap:wrap;
    gap:6px;
}
.page-bakim .badge{
    background:var(--primary-light);
    color:var(--primary-600);
    border-radius:999px;
    padding:4px 10px;
    font-size:11px;
    font-weight:900;
    border:1px solid rgba(59,130,246,.14);
}

@media (max-width: 980px){
    .page-bakim{ padding:12px 12px 92px; }
    .page-bakim .filter-bar{ grid-template-columns:1fr 1fr; }
    .page-bakim .clear-btn{ grid-column:1 / -1; width:100%; }
}

/* List grid */
.page-bakim .bakim-grid{
    display:grid;
    grid-template-columns:repeat(auto-fill,minmax(320px,1fr));
    gap:16px;
    margin-top:10px;
}
.page-bakim .bakim-card{
    background:var(--card);
    border-radius:18px;
    padding:18px;
    border:1px solid var(--border);
    position:relative;
    transition:.25s;
}
.page-bakim .bakim-card:hover{
    border-color:rgba(59,130,246,.32);
    box-shadow:0 12px 26px rgba(59,130,246,.08);
}

.page-bakim .type-dot{
    position:absolute;
    top:18px;
    right:18px;
    width:10px;height:10px;
    border-radius:50%;
}
.page-bakim .dot-periyodik{ background:var(--success); }
.page-bakim .dot-ariza{ background:var(--danger); }
.page-bakim .dot-kalibrasyon{ background:var(--primary); }
.page-bakim .dot-parca_degisim{ background:var(--warning); }
.page-bakim .dot-diger{ background:#94a3b8; }

.page-bakim .oda-tag{
    display:inline-block;
    background:var(--primary-light);
    color:var(--primary-600);
    font-size:11px;
    font-weight:900;
    padding:4px 10px;
    border-radius:999px;
    margin-bottom:12px;
    border:1px solid rgba(59,130,246,.14);
}

.page-bakim .title{
    font-size:15px;
    font-weight:900;
    color:var(--dark);
    margin-bottom:8px;
    line-height:1.35;
}
.page-bakim .subline{
    color:var(--muted);
    font-size:12px;
    margin-bottom:14px;
    font-weight:700;
}

.page-bakim .info-grid{
    display:grid;
    grid-template-columns:repeat(2,1fr);
    gap:10px;
    margin-bottom:14px;
}
.page-bakim .info-item{
    padding:10px;
    background:linear-gradient(180deg,#fff 0%, #f8fafc 100%);
    border-radius:12px;
    border:1px solid rgba(226,232,240,.9);
}
.page-bakim .info-label{
    font-size:10px;
    color:var(--muted);
    font-weight:900;
    margin-bottom:3px;
    text-transform:uppercase;
    letter-spacing:.35px;
}
.page-bakim .info-value{
    font-size:13px;
    font-weight:900;
    color:var(--dark);
}

.page-bakim .action-bar{
    display:flex;
    gap:8px;
    padding-top:12px;
    border-top:1px solid #f1f5f9;
}
.page-bakim .btn{
    flex:1;
    padding:10px 12px;
    border-radius:12px;
    font-size:12px;
    font-weight:900;
    cursor:pointer;
    border:none;
    display:flex;
    align-items:center;
    justify-content:center;
    gap:7px;
    transition:.2s;
    text-decoration:none;
    user-select:none;
}
.page-bakim .btn-edit{
    background:var(--primary-light);
    color:var(--primary-600);
}
.page-bakim .btn-edit:hover{ background:var(--primary-600); color:#fff; }
.page-bakim .btn-delete{
    background:#fef2f2;
    color:var(--danger);
}
.page-bakim .btn-delete:hover{ background:var(--danger); color:#fff; }

.page-bakim .empty-state{
    text-align:center;
    padding:60px 20px;
    color:var(--muted);
}
.page-bakim .empty-state i{
    font-size:48px;
    color:#cbd5e1;
    margin-bottom:16px;
}

/* FAB */
.page-bakim .fab{
    position:fixed;
    bottom:30px;
    right:30px;
    width:56px;height:56px;
    background:var(--primary-600);
    color:#fff;
    border-radius:50%;
    border:none;
    cursor:pointer;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:20px;
    box-shadow:0 10px 26px rgba(37,99,235,.28);
    transition:.2s;
    z-index:1000;
}
.page-bakim .fab:hover{ transform:scale(1.06); box-shadow:0 14px 32px rgba(37,99,235,.35); }

/* Modal */
.page-bakim .modal-overlay{
    display:none;
    position:fixed;
    inset:0;
    background:rgba(15,23,42,.65);
    backdrop-filter:blur(4px);
    z-index:2000;
    align-items:center;
    justify-content:center;
    padding:18px;
}
.page-bakim .modal-content{
    background:#fff;
    border-radius:20px;
    width:100%;
    max-width:560px;
    border:1px solid rgba(226,232,240,.9);
    box-shadow:0 24px 64px rgba(2,6,23,.18);
    overflow:hidden;
    animation:modalIn .18s ease;
}
@keyframes modalIn{
    from{ transform:translateY(10px); opacity:0; }
    to{ transform:translateY(0); opacity:1; }
}
.page-bakim .modal-header{
    padding:18px 18px 0;
}
.page-bakim .modal-header h3{
    font-size:16px;
    font-weight:900;
    color:var(--dark);
    margin:0;
}
.page-bakim .modal-body{ padding:18px; }

.page-bakim .form-group{ margin-bottom:12px; }
.page-bakim .form-label{
    display:block;
    font-size:12px;
    font-weight:900;
    color:var(--muted);
    margin-bottom:6px;
}
.page-bakim .form-input{
    width:100%;
    padding:12px 14px;
    border:1px solid var(--border);
    border-radius:12px;
    font-size:14px;
    font-weight:650;
    transition:.2s;
}
.page-bakim .form-input:focus{
    outline:none;
    border-color:var(--primary);
    box-shadow:0 0 0 3px rgba(59,130,246,.10);
}
.page-bakim .form-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:12px;
}
@media(max-width:640px){
    .page-bakim .form-grid{ grid-template-columns:1fr; }
}

.page-bakim .btn-submit{
    width:100%;
    padding:13px 14px;
    background:var(--primary-600);
    color:#fff;
    border:none;
    border-radius:12px;
    font-size:14px;
    font-weight:900;
    cursor:pointer;
    transition:.2s;
}
.page-bakim .btn-submit:hover{ background:var(--primary); }
.page-bakim .btn-cancel{
    width:100%;
    padding:10px 12px;
    background:transparent;
    border:none;
    color:var(--muted);
    font-size:13px;
    font-weight:800;
    cursor:pointer;
    margin-top:8px;
}
</style>

<div class="page-bakim">
    <div class="container">

        <div class="header">
            <h1>Cihaz Bakım Geçmişi</h1>
            <p>Bakım kayıtlarını ekleyin, filtreleyin ve geçmişi görüntüleyin</p>
        </div>

        <!-- Stats (click = filter) -->
        <div class="stats-grid">
            <a class="stat-item <?= $isAll ? 'active-filter' : '' ?>" href="<?= h(buildUrl([], ['q','cihaz_id','tip','t1','t2','due'])) ?>">
                <div class="stat-number"><?= (int)$istat['toplam_bakim'] ?></div>
                <div class="stat-label">Toplam Bakım</div>
            </a>

            <a class="stat-item <?= $isThisMonth ? 'active-filter' : '' ?>" href="<?= h(buildUrl(['t1'=>$monthStart,'t2'=>$monthEnd,'due'=>''], [])) ?>">
                <div class="stat-number" style="color:var(--primary-600);"><?= (int)$istat['bu_ay'] ?></div>
                <div class="stat-label">Bu Ay</div>
            </a>

            <a class="stat-item <?= $isDue ? 'active-filter' : '' ?>" href="<?= h(buildUrl(['due'=>'1'], [])) ?>">
                <div class="stat-number" style="color:var(--warning);"><?= (int)$istat['yaklasan'] ?></div>
                <div class="stat-label">Yaklaşan (30g)</div>
            </a>

            <a class="stat-item" href="<?= h(buildUrl(['t1'=>$monthStart,'t2'=>$monthEnd], [])) ?>">
                <div class="stat-number" style="color:var(--success);"><?= number_format((float)$istat['bu_ay_maliyet'], 2, ',', '.') ?> ₺</div>
                <div class="stat-label">Bu Ay Maliyet</div>
            </a>
        </div>

        <!-- Filters -->
        <form class="filter-bar" method="GET" id="filterForm">
            <?php if ($sayfa !== ''): ?>
                <input type="hidden" name="sayfa" value="<?= h($sayfa) ?>">
            <?php endif; ?>

            <input class="filter-input" type="text" name="q" value="<?= h($q) ?>" placeholder="Ara: model/seri/oda/servis/kişi/açıklama…">

            <select class="filter-select" name="cihaz_id" id="f_cihaz">
                <option value="0">Tüm Cihazlar</option>
                <?php foreach($cihazList as $c): ?>
                    <option value="<?= (int)$c['id'] ?>" <?= ($cihaz_id==(int)$c['id'] ? 'selected' : '') ?>>
                        <?= h($c['oda_no']) ?> • <?= h($c['marka_model']) ?> <?= $c['seri_no'] ? ('(' . h($c['seri_no']) . ')') : '' ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <select class="filter-select" name="tip" id="f_tip">
                <option value="">Tüm Tipler</option>
                <option value="periyodik" <?= $tip==='periyodik' ? 'selected' : '' ?>>Periyodik</option>
                <option value="ariza" <?= $tip==='ariza' ? 'selected' : '' ?>>Arıza</option>
                <option value="kalibrasyon" <?= $tip==='kalibrasyon' ? 'selected' : '' ?>>Kalibrasyon</option>
                <option value="parca_degisim" <?= $tip==='parca_degisim' ? 'selected' : '' ?>>Parça Değişim</option>
                <option value="diger" <?= $tip==='diger' ? 'selected' : '' ?>>Diğer</option>
            </select>

            <input class="filter-date" type="date" name="t1" value="<?= h($t1) ?>" title="Başlangıç tarihi">
            <input class="filter-date" type="date" name="t2" value="<?= h($t2) ?>" title="Bitiş tarihi">

            <button type="button" class="clear-btn"
                    onclick="window.location.href='<?= h(buildUrl([], ['q','cihaz_id','tip','t1','t2','due'])) ?>'">
                <i class="fas fa-broom"></i> Temizle
            </button>

            <div class="filter-meta">
                <div><strong><?= (int)$liste_sayisi ?></strong> kayıt listeleniyor</div>
                <div class="filter-badges">
                    <?php if ($q !== ''): ?><span class="badge">Ara: <?= h($q) ?></span><?php endif; ?>
                    <?php if ($cihaz_id>0): ?><span class="badge">Cihaz: <?= (int)$cihaz_id ?></span><?php endif; ?>
                    <?php if ($tip !== ''): ?><span class="badge">Tip: <?= h($tip) ?></span><?php endif; ?>
                    <?php if ($t1 !== ''): ?><span class="badge">Başlangıç: <?= h($t1) ?></span><?php endif; ?>
                    <?php if ($t2 !== ''): ?><span class="badge">Bitiş: <?= h($t2) ?></span><?php endif; ?>
                    <?php if ($due === '1'): ?><span class="badge">Yaklaşan: 30g</span><?php endif; ?>
                </div>
            </div>
        </form>

        <?php if(empty($bakimlar)): ?>
            <div class="empty-state">
                <i class="fas fa-screwdriver-wrench"></i>
                <h3 style="margin:0 0 8px; color:var(--dark); font-weight:900;">Bakım Kaydı Bulunamadı</h3>
                <p style="margin:0;">Bu filtrelere uygun kayıt yok</p>
            </div>
        <?php else: ?>
            <div class="bakim-grid">
                <?php foreach($bakimlar as $b): ?>
                    <?php
                        $dot = 'dot-diger';
                        if ($b['bakim_tipi'] === 'periyodik') $dot = 'dot-periyodik';
                        elseif ($b['bakim_tipi'] === 'ariza') $dot = 'dot-ariza';
                        elseif ($b['bakim_tipi'] === 'kalibrasyon') $dot = 'dot-kalibrasyon';
                        elseif ($b['bakim_tipi'] === 'parca_degisim') $dot = 'dot-parca_degisim';
                    ?>
                    <div class="bakim-card">
                        <div class="type-dot <?= $dot ?>"></div>

                        <div class="oda-tag"><?= h($b['oda_no']) ?></div>

                        <div class="title"><?= h($b['marka_model']) ?></div>

                        <div class="subline">
                            Seri: <strong><?= h($b['cihaz_seri_no'] ?: '-') ?></strong> •
                            Tip: <strong><?= h($b['bakim_tipi']) ?></strong>
                        </div>

                        <div class="info-grid">
                            <div class="info-item">
                                <div class="info-label">Bakım Tarihi</div>
                                <div class="info-value"><?= $b['bakim_tarihi'] ? date('d.m.Y', strtotime($b['bakim_tarihi'])) : '-' ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Maliyet</div>
                                <div class="info-value"><?= $b['maliyet'] !== null ? number_format((float)$b['maliyet'], 2, ',', '.') . " ₺" : '-' ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Servis Firma</div>
                                <div class="info-value"><?= h($b['servis_firma'] ?: '-') ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Sonraki Bakım</div>
                                <?php
                                    $warn = ($b['sonraki_bakim_tarihi'] && strtotime($b['sonraki_bakim_tarihi']) <= strtotime('+30 days'));
                                ?>
                                <div class="info-value" style="color:<?= $warn ? 'var(--warning)' : 'var(--dark)' ?>">
                                    <?= $b['sonraki_bakim_tarihi'] ? date('d.m.Y', strtotime($b['sonraki_bakim_tarihi'])) : '-' ?>
                                </div>
                            </div>
                        </div>

                        <?php if(!empty($b['aciklama'])): ?>
                            <div style="color:var(--muted); font-size:12px; line-height:1.45; margin-bottom:12px; font-weight:700;">
                                <?= h(mb_strimwidth($b['aciklama'], 0, 180, '…', 'UTF-8')) ?>
                            </div>
                        <?php endif; ?>

                        <div class="action-bar">
                            <button class="btn btn-edit" type="button"
                                    onclick='editBakim(<?= json_encode($b, JSON_UNESCAPED_UNICODE) ?>)'>
                                <i class="fas fa-pen"></i> Düzenle
                            </button>

                            <a class="btn btn-delete"
                               href="islem.php?islem=bakim_sil&id=<?= (int)$b['id'] ?>"
                               onclick="return confirm('Bu bakım kaydını silmek istediğinize emin misiniz?')">
                                <i class="fas fa-trash"></i> Sil
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

    </div>

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

    <!-- Modal -->
    <div class="modal-overlay" id="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">Yeni Bakım Kaydı</h3>
            </div>

            <form action="islem.php" method="POST" class="modal-body" id="bakimForm">
                <input type="hidden" name="id" id="bakimId" value="0">
                <input type="hidden" name="bakim_islem" value="1">

                <div class="form-group">
                    <label class="form-label">Cihaz</label>
                    <select class="form-input" name="cihaz_id" id="bakimCihaz" required>
                        <option value="">Seçiniz…</option>
                        <?php foreach($cihazList as $c): ?>
                            <option value="<?= (int)$c['id'] ?>">
                                <?= h($c['oda_no']) ?> • <?= h($c['marka_model']) ?> <?= $c['seri_no'] ? ('(' . h($c['seri_no']) . ')') : '' ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Bakım Tarihi</label>
                        <input class="form-input" type="date" name="bakim_tarihi" id="bakimTarih" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Bakım Tipi</label>
                        <select class="form-input" name="bakim_tipi" id="bakimTip">
                            <option value="periyodik">Periyodik</option>
                            <option value="ariza">Arıza</option>
                            <option value="kalibrasyon">Kalibrasyon</option>
                            <option value="parca_degisim">Parça Değişim</option>
                            <option value="diger">Diğer</option>
                        </select>
                    </div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Servis Firma</label>
                        <input class="form-input" type="text" name="servis_firma" id="bakimFirma" placeholder="Örn: Yetkili Servis">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Yapan Kişi</label>
                        <input class="form-input" type="text" name="yapan_kisi" id="bakimKisi" placeholder="Örn: Ali Veli">
                    </div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Maliyet (₺)</label>
                        <input class="form-input" type="number" step="0.01" name="maliyet" id="bakimMaliyet" placeholder="0.00">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Sonraki Bakım Tarihi</label>
                        <input class="form-input" type="date" name="sonraki_bakim_tarihi" id="bakimNext">
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Açıklama</label>
                    <textarea class="form-input" name="aciklama" id="bakimAciklama" rows="3" placeholder="Yapılan işlemler, notlar..."></textarea>
                </div>

                <button type="submit" class="btn-submit">
                    <i class="fas fa-save"></i> Kaydet
                </button>
                <button type="button" class="btn-cancel" onclick="closeModal()">İptal</button>
            </form>
        </div>
    </div>
</div>

<script>
/* Filtre dropdown değişince otomatik uygula */
(function(){
    const f = document.getElementById('filterForm');
    if (!f) return;
    ['f_cihaz','f_tip'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.addEventListener('change', () => f.submit());
    });
})();

/* Modal */
function showModal(){ document.getElementById('modal').style.display = 'flex'; }
function closeModal(){ document.getElementById('modal').style.display = 'none'; }

function openModal(){
    showModal();
    document.getElementById('modalTitle').innerText = 'Yeni Bakım Kaydı';
    document.getElementById('bakimId').value = '0';
    document.getElementById('bakimForm').reset();

    const selectedDevice = document.getElementById('f_cihaz') ? document.getElementById('f_cihaz').value : '0';
    if (selectedDevice && selectedDevice !== '0') document.getElementById('bakimCihaz').value = selectedDevice;

    document.getElementById('bakimTarih').value = new Date().toISOString().slice(0,10);
}

function editBakim(b){
    showModal();
    document.getElementById('modalTitle').innerText = 'Bakım Kaydını Düzenle';
    document.getElementById('bakimForm').reset();

    document.getElementById('bakimId').value = b.id || 0;
    document.getElementById('bakimCihaz').value = b.cihaz_id || '';
    document.getElementById('bakimTarih').value = b.bakim_tarihi || '';
    document.getElementById('bakimTip').value = b.bakim_tipi || 'periyodik';
    document.getElementById('bakimFirma').value = b.servis_firma || '';
    document.getElementById('bakimKisi').value  = b.yapan_kisi || '';
    document.getElementById('bakimMaliyet').value = (b.maliyet !== null && b.maliyet !== undefined) ? b.maliyet : '';
    document.getElementById('bakimNext').value = b.sonraki_bakim_tarihi || '';
    document.getElementById('bakimAciklama').value = b.aciklama || '';
}

/* dışarı tıklayınca kapat */
document.getElementById('modal').addEventListener('click', function(e){
    if (e.target === this) closeModal();
});

/* ESC kapatsın, Ctrl+Plus yeni kayıt açsın */
document.addEventListener('keydown', function(e){
    if (e.key === 'Escape') closeModal();
    if (e.key === '+' && e.ctrlKey) { e.preventDefault(); openModal(); }
});
</script>
