<?php
/**
 * NEPHRO ERP - CİHAZ YÖNETİMİ (Premium Minimal Tasarım + Filtreler)
 * ✅ Tam genişlik (ortada durma bitti)
 * ✅ FontAwesome 6 uyumlu ikonlar
 */
global $pdo;

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

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

$q      = trim($_GET['q'] ?? '');
$oda    = trim($_GET['oda'] ?? '');
$durum  = trim($_GET['durum'] ?? '');
$izole  = trim($_GET['izole'] ?? ''); // "1" | "0" | ""

$allowed_durum = ['aktif','arizali','bakimda'];
if ($durum !== '' && !in_array($durum, $allowed_durum, true)) $durum = '';

if ($izole !== '' && !in_array($izole, ['0','1'], true)) $izole = '';

/** ---------------------------
 *  İstatistik (HER ZAMAN genel)
 * --------------------------- */
$istat_sql = $pdo->query("
    SELECT
        COUNT(*) as toplam,
        SUM(durum='aktif') as aktif,
        SUM(durum='arizali') as arizali,
        SUM(izolasyon_durumu=1) as izole
    FROM cihazlar
");
$istatistik = $istat_sql->fetch(PDO::FETCH_ASSOC) ?: ['toplam'=>0,'aktif'=>0,'arizali'=>0,'izole'=>0];

/** ---------------------------
 *  Oda listesi (filtre dropdown)
 * --------------------------- */
$odaList = $pdo->query("SELECT DISTINCT oda_no FROM cihazlar ORDER BY oda_no ASC")->fetchAll(PDO::FETCH_COLUMN);

/** ---------------------------
 *  Link helper
 * --------------------------- */
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);
}

$isFilterTotal   = ($q==='' && $oda==='' && $durum==='' && $izole==='');
$isFilterAktif   = ($durum==='aktif' && $izole==='' );
$isFilterArizali = ($durum==='arizali' && $izole==='' );
$isFilterIzole   = ($izole==='1');

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

// cihazlar alias: c
if ($q !== '') {
    $where[] = "(c.marka_model LIKE ? OR c.seri_no LIKE ?)";
    $params[] = "%$q%";
    $params[] = "%$q%";
}
if ($oda !== '') {
    $where[] = "c.oda_no = ?";
    $params[] = $oda;
}
if ($durum !== '') {
    $where[] = "c.durum = ?";
    $params[] = $durum;
}
if ($izole !== '') {
    $where[] = "c.izolasyon_durumu = ?";
    $params[] = (int)$izole;
}

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

// son bakım: MAX(bakim_tarihi)
$stmt = $pdo->prepare("
    SELECT
        c.*,
        lb.son_bakim_tarihi
    FROM cihazlar c
    LEFT JOIN (
        SELECT cihaz_id, MAX(bakim_tarihi) AS son_bakim_tarihi
        FROM cihaz_bakimlari
        GROUP BY cihaz_id
    ) lb ON lb.cihaz_id = c.id
    $whereSql
    ORDER BY c.oda_no ASC, c.id ASC
");
$stmt->execute($params);
$cihazlar = $stmt->fetchAll(PDO::FETCH_ASSOC);

$liste_sayisi = count($cihazlar);
?>
<!-- ✅ Font Awesome (ikonlar kaybolmasın diye üstte) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<!-- ✅ Inter Font -->
<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">

<style>
/* Sayfayı bozmamak için her şeyi scope ettim */
.cihaz-page{
    --primary: #3b82f6;
    --primary-light: #eff6ff;
    --success: #10b981;
    --danger: #ef4444;
    --warning: #f59e0b;
    --dark: #1e293b;
    --light: #f8fafc;
    --border: #e2e8f0;
    --card: #ffffff;
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
    color: var(--dark);
}

/* ✅ En kritik fix: ortada durma bitti, alan komple doluyor */
.cihaz-page .container{
    width: 100% !important;
    max-width: none !important;
    margin: 0 !important;
    padding: 18px 22px;
    min-width: 0;
}

/* Header */
.cihaz-page .header{ margin-bottom: 18px; text-align:left; }
.cihaz-page .header h1{ font-size: 22px; font-weight: 800; margin-bottom: 4px; }
.cihaz-page .header p{ color:#64748b; font-size: 13px; }

/* Stats */
.cihaz-page .stats-grid{
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 12px;
    margin-bottom: 14px;
}
.cihaz-page .stat-item{
    background: var(--card);
    padding: 18px;
    border-radius: 16px;
    border: 1px solid var(--border);
    transition: all .2s ease;
    text-decoration: none;
    display: block;
}
.cihaz-page .stat-item:hover{
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0,0,0,.05);
}
.cihaz-page .stat-item.active-filter{
    border-color: var(--primary);
    box-shadow: 0 10px 22px rgba(59,130,246,.10);
}
.cihaz-page .stat-number{ font-size: 26px; font-weight: 800; margin-bottom: 4px; }
.cihaz-page .stat-label{
    font-size: 11px;
    color: #64748b;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .4px;
}

/* Filter Bar */
.cihaz-page .filter-bar{
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 14px;
    display: grid;
    grid-template-columns: 1.4fr 1fr 1fr 1fr auto;
    gap: 10px;
    align-items: center;
    margin-bottom: 18px;
}
.cihaz-page .filter-input,
.cihaz-page .filter-select{
    width: 100%;
    padding: 11px 12px;
    border: 1px solid var(--border);
    border-radius: 12px;
    font-size: 13px;
    transition: all .2s;
    background: #fff;
}
.cihaz-page .filter-input:focus,
.cihaz-page .filter-select:focus{
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(59,130,246,.10);
}
.cihaz-page .clear-btn{
    padding: 11px 12px;
    border-radius: 12px;
    border: 1px solid var(--border);
    background: #fff;
    cursor: pointer;
    font-size: 12px;
    font-weight: 800;
    color: #475569;
    transition: all .2s;
    white-space: nowrap;
}
.cihaz-page .clear-btn:hover{
    border-color: var(--primary);
    color: var(--primary);
    box-shadow: 0 10px 20px rgba(59,130,246,.10);
}
.cihaz-page .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:#64748b;
    font-size:12px;
}
.cihaz-page .filter-badges{ display:flex; flex-wrap:wrap; gap:6px; }
.cihaz-page .badge{
    background: var(--primary-light);
    color: var(--primary);
    border-radius: 999px;
    padding: 4px 10px;
    font-size: 11px;
    font-weight: 800;
}

/* Grid */
.cihaz-page .cihaz-grid{
    display:grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 14px;
    margin-top: 8px;
}
.cihaz-page .cihaz-card{
    background: var(--card);
    border-radius: 18px;
    padding: 18px;
    border: 1px solid var(--border);
    position: relative;
    transition: all .25s ease;
}
.cihaz-page .cihaz-card:hover{
    border-color: var(--primary);
    box-shadow: 0 10px 26px rgba(59,130,246,.08);
}

/* status dot */
.cihaz-page .status-badge{
    position:absolute;
    top: 18px;
    right: 18px;
    width: 10px;
    height: 10px;
    border-radius: 50%;
}
.cihaz-page .status-aktif{ background: var(--success); }
.cihaz-page .status-arizali{ background: var(--danger); }
.cihaz-page .status-bakimda{ background: var(--warning); }

/* content */
.cihaz-page .oda-tag{
    display:inline-block;
    background: var(--primary-light);
    color: var(--primary);
    font-size: 11px;
    font-weight: 800;
    padding: 4px 10px;
    border-radius: 999px;
    margin-bottom: 12px;
}
.cihaz-page .cihaz-ad{
    font-size: 15px;
    font-weight: 800;
    margin-bottom: 12px;
    line-height: 1.35;
}

/* info grid */
.cihaz-page .info-grid{
    display:grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
    margin-bottom: 16px;
}
.cihaz-page .info-item{
    padding: 10px;
    background: var(--light);
    border-radius: 12px;
}
.cihaz-page .info-label{
    font-size: 10px;
    color:#64748b;
    font-weight: 700;
    margin-bottom: 3px;
    text-transform: uppercase;
    letter-spacing: .3px;
}
.cihaz-page .info-value{
    font-size: 13px;
    font-weight: 700;
}

/* actions */
.cihaz-page .action-bar{
    display:flex;
    gap: 8px;
    padding-top: 14px;
    border-top: 1px solid #f1f5f9;
}
.cihaz-page .btn{
    flex:1;
    padding: 10px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 800;
    cursor:pointer;
    border:none;
    display:flex;
    align-items:center;
    justify-content:center;
    gap:6px;
    transition: all .2s ease;
    text-decoration:none;
}
.cihaz-page .btn-edit{ background: var(--primary-light); color: var(--primary); }
.cihaz-page .btn-edit:hover{ background: var(--primary); color:#fff; }
.cihaz-page .btn-delete{ background:#fef2f2; color: var(--danger); }
.cihaz-page .btn-delete:hover{ background: var(--danger); color:#fff; }

/* FAB */
.cihaz-page .fab{
    position: fixed;
    bottom: 26px;
    right: 26px;
    width: 56px;
    height: 56px;
    border-radius: 50%;
    border:none;
    cursor:pointer;
    background: var(--primary);
    color:#fff;
    font-size: 18px;
    display:flex;
    align-items:center;
    justify-content:center;
    box-shadow: 0 10px 22px rgba(59,130,246,.30);
    transition: all .2s ease;
    z-index: 999;
}
.cihaz-page .fab:hover{ transform: scale(1.08); box-shadow: 0 14px 26px rgba(59,130,246,.38); }

/* Modal */
.cihaz-page .modal-overlay{
    display:none;
    position:fixed;
    inset:0;
    background: rgba(15,23,42,.70);
    backdrop-filter: blur(4px);
    z-index: 1000;
    align-items:center;
    justify-content:center;
    padding: 18px;
}
.cihaz-page .modal-content{
    background:#fff;
    border-radius: 20px;
    width:100%;
    max-width: 460px;
    animation: modalSlide .25s ease;
    border: 1px solid rgba(226,232,240,.8);
}
@keyframes modalSlide{
    from{ opacity:0; transform: translateY(16px); }
    to{ opacity:1; transform: translateY(0); }
}
.cihaz-page .modal-header{ padding: 20px 20px 0; }
.cihaz-page .modal-header h3{ font-size: 18px; font-weight: 900; }
.cihaz-page .modal-body{ padding: 20px; }
.cihaz-page .form-group{ margin-bottom: 14px; }
.cihaz-page .form-label{ display:block; font-size: 12px; font-weight: 800; color:#64748b; margin-bottom: 6px; }
.cihaz-page .form-input{
    width:100%;
    padding: 12px 12px;
    border: 1px solid var(--border);
    border-radius: 12px;
    font-size: 14px;
}
.cihaz-page .form-input:focus{
    outline:none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(59,130,246,.10);
}
.cihaz-page .form-grid{ display:grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.cihaz-page .btn-submit{
    width:100%;
    padding: 13px;
    border-radius: 12px;
    border:none;
    cursor:pointer;
    background: var(--primary);
    color:#fff;
    font-weight: 900;
}
.cihaz-page .btn-submit:hover{ background:#2563eb; }
.cihaz-page .btn-cancel{
    width:100%;
    padding: 10px;
    margin-top: 8px;
    border:none;
    background: transparent;
    color:#64748b;
    cursor:pointer;
    font-weight: 800;
}

/* Empty */
.cihaz-page .empty-state{
    text-align:center;
    padding: 56px 14px;
    color:#64748b;
}
.cihaz-page .empty-state i{
    font-size: 42px;
    color:#cbd5e1;
    margin-bottom: 14px;
}

/* Responsive */
@media (max-width: 980px){
    .cihaz-page .filter-bar{ grid-template-columns: 1fr 1fr; }
    .cihaz-page .clear-btn{ grid-column: 1 / -1; width:100%; }
    .cihaz-page .info-grid{ grid-template-columns: 1fr 1fr; }
}
@media (max-width: 640px){
    .cihaz-page .container{ padding: 12px; }
    .cihaz-page .filter-bar{ grid-template-columns: 1fr; }
    .cihaz-page .info-grid{ grid-template-columns: 1fr 1fr; }
}
</style>

<div class="cihaz-page">
    <div class="container">
        <div class="header">       
			<h1>Cihaz Yönetimi</h1>
            <p>Sistemde kayıtlı tüm tıbbi cihazlar</p>
        </div>

        <!-- Statistics (click = filter) -->
        <div class="stats-grid">
            <a class="stat-item <?= $isFilterTotal ? 'active-filter' : '' ?>" href="<?= h(buildUrl([], ['q','oda','durum','izole'])) ?>">
                <div class="stat-number"><?= (int)$istatistik['toplam'] ?></div>
                <div class="stat-label">Toplam Cihaz</div>
            </a>

            <a class="stat-item <?= $isFilterAktif ? 'active-filter' : '' ?>" href="<?= h(buildUrl(['durum'=>'aktif','izole'=>''], [])) ?>">
                <div class="stat-number" style="color: var(--success);"><?= (int)$istatistik['aktif'] ?></div>
                <div class="stat-label">Aktif Cihaz</div>
            </a>

            <a class="stat-item <?= $isFilterArizali ? 'active-filter' : '' ?>" href="<?= h(buildUrl(['durum'=>'arizali','izole'=>''], [])) ?>">
                <div class="stat-number" style="color: var(--danger);"><?= (int)$istatistik['arizali'] ?></div>
                <div class="stat-label">Arızalı</div>
            </a>

            <a class="stat-item <?= $isFilterIzole ? 'active-filter' : '' ?>" href="<?= h(buildUrl(['izole'=>'1'], [])) ?>">
                <div class="stat-number" style="color: var(--warning);"><?= (int)$istatistik['izole'] ?></div>
                <div class="stat-label">İzole Cihaz</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: Marka/Model veya Seri No…">

            <select class="filter-select" name="oda" id="f_oda">
                <option value="">Tüm Odalar</option>
                <?php foreach($odaList as $o): ?>
                    <option value="<?= h($o) ?>" <?= ($oda===(string)$o ? 'selected' : '') ?>>Oda: <?= h($o) ?></option>
                <?php endforeach; ?>
            </select>

            <select class="filter-select" name="durum" id="f_durum">
                <option value="">Tüm Durumlar</option>
                <option value="aktif"   <?= $durum==='aktif' ? 'selected' : '' ?>>Aktif</option>
                <option value="arizali" <?= $durum==='arizali' ? 'selected' : '' ?>>Arızalı</option>
                <option value="bakimda" <?= $durum==='bakimda' ? 'selected' : '' ?>>Bakımda</option>
            </select>

            <select class="filter-select" name="izole" id="f_izole">
                <option value="">İzolasyon: Tümü</option>
                <option value="0" <?= $izole==='0' ? 'selected' : '' ?>>Normal</option>
                <option value="1" <?= $izole==='1' ? 'selected' : '' ?>>Pozitif (İzole)</option>
            </select>

            <button type="button" class="clear-btn" onclick="window.location.href='<?= h(buildUrl([], ['q','oda','durum','izole'])) ?>'">
                <i class="fa-solid fa-broom"></i> Temizle
            </button>

            <div class="filter-meta">
                <div><strong><?= (int)$liste_sayisi ?></strong> cihaz listeleniyor</div>

                <div class="filter-badges">
                    <?php if ($q !== ''): ?><span class="badge">Ara: <?= h($q) ?></span><?php endif; ?>
                    <?php if ($oda !== ''): ?><span class="badge">Oda: <?= h($oda) ?></span><?php endif; ?>
                    <?php if ($durum !== ''): ?><span class="badge">Durum: <?= h($durum) ?></span><?php endif; ?>
                    <?php if ($izole !== ''): ?><span class="badge">İzolasyon: <?= $izole==='1' ? 'Pozitif' : 'Normal' ?></span><?php endif; ?>
                </div>
            </div>
        </form>

        <!-- Cihaz Grid -->
        <?php if(empty($cihazlar)): ?>
            <div class="empty-state">
                <i class="fa-solid fa-plug-circle-xmark"></i>
                <h3 style="margin-bottom:10px;">Cihaz Bulunamadı</h3>
                <p>Bu filtrelere uygun cihaz yok</p>
            </div>
        <?php else: ?>
            <div class="cihaz-grid">
                <?php foreach($cihazlar as $c): ?>
                    <div class="cihaz-card">
                        <div class="status-badge status-<?= h($c['durum']) ?>"></div>

                        <div class="oda-tag"><?= h($c['oda_no']) ?></div>
                        <div class="cihaz-ad"><?= h($c['marka_model']) ?></div>

                        <div class="info-grid">
                            <div class="info-item">
                                <div class="info-label">Seri No</div>
                                <div class="info-value"><?= h($c['seri_no'] ?: '-') ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Durum</div>
                                <div class="info-value" style="color: <?=
                                    $c['durum'] == 'aktif' ? 'var(--success)' :
                                    ($c['durum'] == 'arizali' ? 'var(--danger)' : 'var(--warning)')
                                ?>">
                                    <?= h(mb_strtoupper(mb_substr($c['durum'],0,1,'UTF-8'),'UTF-8') . mb_substr($c['durum'],1,null,'UTF-8')) ?>
                                </div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Son Bakım</div>
                                <div class="info-value">
                                    <?= !empty($c['son_bakim_tarihi']) ? date('d.m.Y', strtotime($c['son_bakim_tarihi'])) : '-' ?>
                                </div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">İzolasyon</div>
                                <div class="info-value" style="color: <?= ((int)$c['izolasyon_durumu'] === 1) ? 'var(--warning)' : 'var(--success)' ?>">
                                    <?= ((int)$c['izolasyon_durumu'] === 1) ? 'Pozitif' : 'Normal' ?>
                                </div>
                            </div>
                        </div>

                        <div class="action-bar">
                            <button class="btn btn-edit" type="button" onclick='editCihaz(<?= json_encode($c, JSON_UNESCAPED_UNICODE) ?>)'>
                                <i class="fa-solid fa-pen-to-square"></i> Düzenle
                            </button>
                            <a href="islem.php?islem=cihaz_sil&id=<?= (int)$c['id'] ?>"
                               class="btn btn-delete"
                               onclick="return confirm('Bu cihazı silmek istediğinize emin misiniz?')">
                                <i class="fa-solid fa-trash"></i> Sil
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

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

    <!-- Modal -->
    <div class="modal-overlay" id="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">Yeni Cihaz Ekle</h3>
            </div>

            <form action="islem.php" method="POST" class="modal-body" id="cihazForm">
                <input type="hidden" name="id" id="cihazId" value="0">

                <div class="form-group">
                    <label class="form-label">Marka / Model</label>
                    <input type="text" name="marka_model" id="cihazModel" class="form-input" required>
                </div>

                <div class="form-group">
                    <label class="form-label">Seri Numarası</label>
                    <input type="text" name="seri_no" id="cihazSeri" class="form-input">
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Oda No</label>
                        <input type="text" name="oda_no" id="cihazOda" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Durum</label>
                        <select name="durum" id="cihazDurum" class="form-input">
                            <option value="aktif">Aktif</option>
                            <option value="arizali">Arızalı</option>
                            <option value="bakimda">Bakımda</option>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">İzolasyon Durumu</label>
                    <select name="izolasyon_durumu" id="cihazIzolasyon" class="form-input">
                        <option value="0">Normal</option>
                        <option value="1">Pozitif (İzole)</option>
                    </select>
                </div>

                <button type="submit" name="cihaz_islem" class="btn-submit">
                    <i class="fa-solid fa-floppy-disk"></i> Kaydet
                </button>

                <button type="button" class="btn-cancel" onclick="closeModal()">
                    İptal
                </button>
            </form>
        </div>
    </div>
</div>

<script>
(function(){
    const f = document.getElementById('filterForm');
    if (!f) return;

    ['f_oda','f_durum','f_izole'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.addEventListener('change', () => f.submit());
    });

    // Arama input: enter basınca submit
    const search = f.querySelector('input[name="q"]');
    if (search){
        search.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') f.submit();
        });
    }
})();

function showModal() { document.getElementById('modal').style.display = 'flex'; }
function openModal() {
    showModal();
    document.getElementById('modalTitle').innerText = 'Yeni Cihaz Ekle';
    document.getElementById('cihazId').value = '0';
    document.getElementById('cihazForm').reset();
}
function closeModal() { document.getElementById('modal').style.display = 'none'; }

function editCihaz(cihaz) {
    showModal();
    document.getElementById('modalTitle').innerText = 'Cihazı Düzenle';
    document.getElementById('cihazId').value = cihaz.id || 0;

    document.getElementById('cihazForm').reset();
    document.getElementById('cihazModel').value = cihaz.marka_model || '';
    document.getElementById('cihazSeri').value  = cihaz.seri_no || '';
    document.getElementById('cihazOda').value   = cihaz.oda_no || '';
    document.getElementById('cihazDurum').value = cihaz.durum || 'aktif';
    document.getElementById('cihazIzolasyon').value = (cihaz.izolasyon_durumu == 1 ? '1' : '0');
}

document.getElementById('modal').addEventListener('click', function(e) {
    if (e.target === this) closeModal();
});

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeModal();
    if (e.key === '+' && e.ctrlKey) { e.preventDefault(); openModal(); }
});
</script>
