<?php
session_start();

$bugun = date("m-d");
$dogumGunuFurkan = "12-14";

$showBirthday = false;

if($_SESSION['username'] === 'furkan' && $bugun === $dogumGunuFurkan){
    $showBirthday = true;
}


if(!isset($_SESSION['user_id'])){
    header("Location: login.php");
    exit;
}
if(empty($_SESSION['csrf_token'])){
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>
<?php
include "db.php";

$limit = 20;

// BEKLEYEN
$page_beklemede = isset($_GET["pb"]) ? intval($_GET["pb"]) : 1;
$start_beklemede = ($page_beklemede - 1) * $limit;

// SATILAN
$page_satilan = isset($_GET["ps"]) ? intval($_GET["ps"]) : 1;
$start_satilan = ($page_satilan - 1) * $limit;


// EKLE
if(isset($_POST["ekle"])){
    $adi = $baglan->real_escape_string($_POST["item"]);
    $alis = floatval($_POST["alis"]);
    $satis = floatval($_POST["satis"]);
    $guncel_satis = floatval($_POST["guncel_satis"]);
    $durum = $baglan->real_escape_string($_POST["durum"]);
    $notlar = $baglan->real_escape_string($_POST["notlar"] ?? '');
    $link = $baglan->real_escape_string($_POST["link"] ?? '');

    $baglan->query("INSERT INTO items 
        (item_adi, alis_fiyat, satis_fiyat, guncel_satis, durum, tarih, notlar, link) 
        VALUES ('$adi','$alis','$satis','$guncel_satis','$durum', NOW(), '$notlar', '$link')");
addLog($baglan, "Item Eklendi", "Item: $adi | Alış: $alis | Satış: $satis");

    header("Location: index.php"); exit;
}


// SATILDI + TARİH
if(isset($_POST["satildi_yap"])){
    $id = intval($_POST["id"]);
    $baglan->query("
        UPDATE items SET 
            durum='Satıldı',
            satilma_tarihi = NOW()
        WHERE id=$id
    ");
addLog($baglan, "Satıldı Yapıldı", "ID: $id");

    header("Location: index.php"); exit;
}

if(isset($_POST["satildi_formdan"])){
    $id = intval($_POST["id"]);
    $satisFiyat = floatval($_POST["satis_fiyat"]);

    $baglan->query("
        UPDATE items SET
            satis_fiyat = '$satisFiyat',
            durum = 'Satıldı',
            satilma_tarihi = NOW()
        WHERE id = $id
    ");

    addLog($baglan, "Satıldı (Form)", "ID: $id | Satış: $satisFiyat");

    header("Location: index.php");
    exit;
}



// SİL (SATILDI KORUMALI + ŞİFRELİ)
if(isset($_POST["sil"])){

    $id = intval($_POST["id"]);
    $adminPass = $_POST["admin_pass"] ?? "";

    // 1️⃣ Silinmeden önce item bilgilerini al
    $old = $baglan->query("SELECT * FROM items WHERE id=$id")->fetch_assoc();

    if(!$old){
        die("❌ Kayıt bulunamadı");
    }

    // 2️⃣ SATILDI ise ŞİFRE ZORUNLU
    if($old["durum"] === "Satıldı"){
        if($adminPass !== ADMIN_ACTION_PASSWORD){
            die("❌ Yetkisiz işlem: Satılan item silinemez.");
        }
    }

    // 3️⃣ Log'a detaylı yaz
    $itemAdi = $old["item_adi"];
    $alis    = $old["alis_fiyat"];
    $satis   = $old["satis_fiyat"];
    $durum   = $old["durum"];
    $not     = $old["notlar"];

    addLog(
        $baglan,
        "Silindi",
        "Item: $itemAdi | Alış: $alis | Satış: $satis | Durum: $durum | Not: $not"
    );

    // 4️⃣ Sil
    $baglan->query("DELETE FROM items WHERE id=$id");

    header("Location: index.php");
    exit;
}





// DÜZENLE KAYDET (DETAYLI LOGLU)
if(isset($_POST["duzenle_kaydet"])){

    $id = intval($_POST["id"]);

    // 1️⃣ ESKİ VERİYİ ÇEK
    $old = $baglan->query("SELECT * FROM items WHERE id=$id")->fetch_assoc();

    $adi = $baglan->real_escape_string($_POST["item"]);
    $alis = floatval($_POST["alis"]);
    $satis = floatval($_POST["satis"]);
    $guncel_satis = floatval($_POST["guncel_satis"]);
    $durum = $baglan->real_escape_string($_POST["durum"]);
    $notlar = $baglan->real_escape_string($_POST["notlar"] ?? '');
    $link = $baglan->real_escape_string($_POST["link"] ?? '');

    // Satılma tarihi
    $satilma_tarihi = $_POST["satilma_tarihi"] ?? null;

    if ($durum == "Satıldı") {
        if ($satilma_tarihi) {
            $satilmaTarihiSQL = ", satilma_tarihi='".$baglan->real_escape_string($satilma_tarihi)."'";
        } else {
            $satilmaTarihiSQL = ", satilma_tarihi = NOW()";
        }
    } else {
        $satilmaTarihiSQL = ", satilma_tarihi = NULL";
    }

    // 2️⃣ UPDATE
    $baglan->query("UPDATE items SET 
        item_adi='$adi',
        alis_fiyat='$alis',
        satis_fiyat='$satis',
        guncel_satis='$guncel_satis',
        durum='$durum',
        notlar='$notlar',
        link='$link'
        $satilmaTarihiSQL
        WHERE id=$id
    ");

    // 3️⃣ DEĞİŞİKLİKLERİ TESPİT ET
    $degisimler = [];

    if($old["item_adi"] != $adi)
        $degisimler[] = "Item: {$old['item_adi']} → $adi";

    if($old["alis_fiyat"] != $alis)
        $degisimler[] = "Alış: {$old['alis_fiyat']} → $alis";

    if($old["satis_fiyat"] != $satis)
        $degisimler[] = "Satış: {$old['satis_fiyat']} → $satis";

    if($old["guncel_satis"] != $guncel_satis)
        $degisimler[] = "Güncel: {$old['guncel_satis']} → $guncel_satis";

    if($old["durum"] != $durum)
        $degisimler[] = "Durum: {$old['durum']} → $durum";

    if($old["notlar"] != $notlar)
        $degisimler[] = "Not: ".($old["notlar"] ?: "boş")." → ".($notlar ?: "boş");

    if($old["link"] != $link)
        $degisimler[] = "Link değişti";

    if($old["satilma_tarihi"] != $satilma_tarihi && $durum=="Satıldı")
        $degisimler[] = "Satılma Tarihi güncellendi";

    // 4️⃣ LOG YAZ
    if(count($degisimler) > 0){
addLog(
    $baglan,
    "Item Düzenlendi",
    "Item: ".$old['item_adi']." | " . implode(" | ", $degisimler)
);

    }

    header("Location: index.php");
    exit;
}



// DÜZENLEME AÇILMASI
$edit = null;
if(isset($_POST["duzenle"])){
    $id = intval($_POST["id"]);
    $edit = $baglan->query("SELECT * FROM items WHERE id=$id")->fetch_assoc();
}


// ARAMA
$arama = isset($_GET["ara"]) ? $baglan->real_escape_string($_GET["ara"]) : "";


// TARİH FİLTRESİ
$t1 = $_GET["t1"] ?? "";
$t2 = $_GET["t2"] ?? "";

$filtre = "";
if ($t1 && $t2) {
    $filtre = " AND DATE(satilma_tarihi) BETWEEN '$t1' AND '$t2' ";
}


// LİSTE
$bekleyenler = $baglan->query("
SELECT * FROM items 
WHERE TRIM(durum)='Beklemede' 
AND item_adi LIKE '%$arama%' 
 ORDER BY tarih DESC
    LIMIT $start_beklemede, $limit
");

$satilanlar = $baglan->query("
    SELECT * FROM items 
    WHERE TRIM(durum)='Satıldı' 
      AND item_adi LIKE '%$arama%' 
      $filtre
    ORDER BY satilma_tarihi DESC
    LIMIT $start_satilan, $limit
");


// TOPLAMLAR
$toplamKazan = floatval(($baglan->query("SELECT SUM(satis_fiyat - alis_fiyat) AS t FROM items WHERE TRIM(durum)='Satıldı'")->fetch_assoc())["t"]);
$beklemedePara = floatval(($baglan->query("SELECT SUM(alis_fiyat) AS t FROM items WHERE TRIM(durum)='Beklemede'")->fetch_assoc())["t"]);
$kasadakiPara = floatval(($baglan->query("SELECT SUM(satis_fiyat) AS t FROM items WHERE TRIM(durum)='Satıldı'")->fetch_assoc())["t"]);





$kasadakiParaFiltreli = 0;
$toplamKazanFiltreli = 0;

if ($t1 && $t2) {
    $kasadakiParaFiltreli = floatval(
        $baglan->query("
            SELECT SUM(satis_fiyat) AS t 
            FROM items 
            WHERE TRIM(durum)='Satıldı'
            AND DATE(satilma_tarihi) BETWEEN '$t1' AND '$t2'
        ")->fetch_assoc()['t']
    );

    $toplamKazanFiltreli = floatval(
        $baglan->query("
            SELECT SUM(satis_fiyat - alis_fiyat) AS t 
            FROM items 
            WHERE TRIM(durum)='Satıldı'
            AND DATE(satilma_tarihi) BETWEEN '$t1' AND '$t2'
        ")->fetch_assoc()['t']
    );
}
// YENİ YÜZDE HESABI (Senin istediğin mantık)
$karYuzde = 0;

if ($kasadakiPara > 0) {
    $karYuzde = ($toplamKazan / $kasadakiPara) * 100;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Item Paneli</title>

<style>


/* ================= ADMIN BAR ================= */
.admin-bar{
    display:flex;
    align-items:center;
    justify-content:space-between;
    padding:14px 20px;
    margin-bottom:20px;

    background:rgba(15,23,42,0.85);
    backdrop-filter:blur(8px);

    border-radius:14px;
    border:1px solid #1e293b;
    box-shadow:0 0 20px rgba(56,189,248,0.25);
}

.admin-left{
    color:#7dd3fc;
    font-size:15px;
}

.admin-center{
    font-size:18px;
    font-weight:bold;
    color:#38bdf8;
    text-shadow:0 0 8px rgba(56,189,248,0.6);
}

.admin-right{
    display:flex;
    gap:10px;
    align-items:center;
}

/* Ortak admin buton */
.admin-btn{
    padding:8px 14px;
    border-radius:10px;
    font-size:14px;
    font-weight:bold;
    border:none;
    cursor:pointer;
    text-decoration:none;
    transition:0.25s;
}

/* Loglar */
.log-btn{
    background:linear-gradient(135deg,#0ea5e9,#38bdf8);
    color:white;
    box-shadow:0 0 10px rgba(56,189,248,0.45);
}
.log-btn:hover{
    transform:translateY(-2px);
}

/* Çıkış */
.exit-btn{
    background:linear-gradient(135deg,#dc2626,#ef4444);
    color:white;
    box-shadow:0 0 10px rgba(239,68,68,0.45);
}
.exit-btn:hover{
    transform:translateY(-2px);
}

/* ==== GENEL TASARIM ==== */
body{
    background:#020617;
    color:#e5e7eb;
    font-family:Segoe UI,Arial;
    padding:20px;
}

h2{
    color:#38bdf8;
    margin-bottom:15px;
}

/* Genel input / button base */
input,select,button,textarea{
    padding:10px;
    border-radius:8px;
    border:1px solid #334155;
    background:#020617;
    color:#e5e7eb;
    font-size:14px;
}

button{
    cursor:pointer;
    transition:0.2s;
}
button:hover{
    opacity:0.9;
}

/* ==== ÜST KONTROL PANELİ (ARA + TARİH) ==== */
.control-panel {
    background: rgba(15, 23, 42, 0.85);
    padding: 16px;
    border-radius: 14px;
    display: flex;
    gap: 12px;
    align-items: flex-start;
    backdrop-filter: blur(6px);
    border: 1px solid #1e293b;
    box-shadow: 0 0 14px rgba(56,189,248,0.20);
    margin-bottom: 18px;
	flex-direction: column;   /* <-- BÜYÜK ÇÖZÜM BURADA */
}

.control-panel form {
    display:flex;
    gap:10px;
    flex:1;
}

.control-panel input{
    background:#020617;
    border-color:#334155;
    height:40px;
}
.control-panel input:focus{
    outline:none;
    border-color:#38bdf8;
    box-shadow:0 0 10px rgba(56,189,248,0.4);
}

.control-panel button{
    height:40px;
    padding:0 18px;
    background:linear-gradient(135deg,#0ea5e9,#38bdf8);
    border:none;
    border-radius:10px;
    font-weight:bold;
    box-shadow:0 0 10px rgba(56,189,248,0.45);
}

.clear-btn {
    padding:10px 16px;
    border-radius:10px;
    text-decoration:none;
    color:#f9fafb;
    background:linear-gradient(135deg,#dc2626,#ef4444);
    box-shadow:0 0 10px rgba(239,68,68,0.5);
    font-size:14px;
}

/* ==== ITEM FORM TASARIMI ==== */
.item-form {
    background: rgba(15, 23, 42, 0.9);
    border: 1px solid #1f2937;
    padding: 20px;
    border-radius: 14px;
    box-shadow: 0 0 16px rgba(15,23,42,0.9);
    margin-bottom: 22px;
}

.item-form-title{
    font-size:16px;
    margin-bottom:10px;
    color:#7dd3fc;
}

.item-grid {
    display: grid;
    grid-template-columns: repeat(6,1fr);
    gap: 12px;
}

.item-grid input,
.item-grid select,
.item-grid textarea {
    width: 100%;
    background:#020617;
    border:1px solid #334155;
    border-radius:10px;
    padding:9px 10px;
    color:#e5e7eb;
}

.item-grid input:focus,
.item-grid select:focus,
.item-grid textarea:focus {
    border-color:#38bdf8;
    box-shadow:0 0 10px rgba(56,189,248,0.4);
    outline:none;
}

.item-form button {
    width: 100%;
    padding: 12px;
    background: linear-gradient(135deg,#0ea5e9,#38bdf8);
    border: none;
    color: white;
    font-size: 15px;
    border-radius: 10px;
    margin-top: 10px;
    font-weight: bold;
}
.item-form button:hover{
    transform: translateY(-2px);
    box-shadow: 0 0 15px rgba(56,189,248,0.5);
}

/* ==== GENEL KUTU ==== */
.kutu{
    background:#020617;
    padding:15px;
    border-radius:12px;
    box-shadow:0 0 10px #0005;
}

/* ==== KASA KUTULARI ==== */
.kasa-wrapper{
    display:flex;
    gap:20px;
    margin-top:25px;
}

.kasa-box{
    flex:1;
    padding:18px;
    border-radius:16px;
    background:rgba(15,23,42,0.95);
    backdrop-filter:blur(6px);
    border:1px solid #1e293b;
    text-align:center;
    box-shadow:0 0 14px rgba(56,189,248,0.25);
    transition:0.25s;
}

.kasa-box:hover{
    transform:translateY(-3px);
    box-shadow:0 0 18px rgba(56,189,248,0.4);
}

.kasa-title{
    display:block;
    font-size:15px;
    color:#38bdf8;
}

.kasa-value{
    display:block;
    margin-top:6px;
    font-size:22px;
    font-weight:bold;
}

/* ========================================================= */
/* ===================== PREMIUM TABLE ===================== */
/* ========================================================= */

table{
    width:100%;
    border-collapse:collapse;
    margin-top:10px;
    overflow:hidden;
    border-radius:12px;
    background:rgba(15,23,42,0.85);
    backdrop-filter:blur(6px);
    box-shadow:0 0 18px rgba(56,189,248,0.15);
}

/* TABLO BAŞLIKLARI */
th{
    background:linear-gradient(135deg,#020617,#020617);
    padding:12px;
    color:#38bdf8;
    border-bottom:2px solid #334155;
    text-transform:uppercase;
    letter-spacing:.5px;
    font-size:12px;
}

/* TABLO HÜCRELERİ */
td{
    padding:9px;
    border-bottom:1px solid #475569;
    border-right:1px solid #334155;
    font-size:13px;
}

/* SATIR HOVER */
tr:hover{
    background:rgba(56,189,248,0.10);
    transition:0.25s;
}

/* BEKLEMEDE SATIRLAR */
tr.beklemede{
    background:linear-gradient(135deg,#7c2d12,#a16207);
    color:#fff3cd;
    font-weight:500;
}
tr.beklemede:hover{
    background:linear-gradient(135deg,#9a3412,#ca8a04);
}

/* SATILAN SATIRLAR */
tr.satildi{
    background:linear-gradient(135deg,#064e3b,#166534);
    color:#bbf7d0;
    font-weight:500;
}
tr.satildi:hover{
    background:linear-gradient(135deg,#047857,#22c55e);
}

/* NOT ALANI */
.not-cell{
    max-width:220px;
    word-break:break-word;
    text-align:left;
}

/* ====== BUTON TASARIMLARI ====== */
.islem-btn{
    margin:3px;
    padding:6px 10px;
    border-radius:8px;
    font-weight:bold;
    border:1px solid transparent;
    font-size:12px;
}

.satildi-btn{
    background:linear-gradient(135deg,#16a34a,#22c55e);
    border-color:#22c55e;
}

.duzenle-btn{
    background:linear-gradient(135deg,#0ea5e9,#38bdf8);
    border-color:#38bdf8;
}

.sil-btn{
    background:linear-gradient(135deg,#dc2626,#ef4444);
    border-color:#ef4444;
}

.islem-btn:hover{
    transform:scale(1.05);
    box-shadow:0 0 10px rgba(56,189,248,0.4);
    transition:0.2s;
}

/* ITEM LİNK */
a.item-link{
    color:#7dd3fc;
    font-weight:bold;
    text-decoration:underline;
}

/* PAGİNATİON LİNKLERİ */
.page-link{
    margin:0 5px;
    padding:6px 12px;
    background:#020617;
    color:#e5e7eb;
    border-radius:6px;
    text-decoration:none;
    border:1px solid #334155;
    font-size:13px;
}
.page-link:hover{
    background:#0f172a;
    box-shadow:0 0 10px rgba(56,189,248,0.4);
}

</style>
<script>

function acSatisFormu(id){
    let row = document.getElementById("satis-form-" + id);
    row.style.display = "table-row";
}

function kapatSatisFormu(id){
    let row = document.getElementById("satis-form-" + id);
    row.style.display = "none";
}




function adminConfirm(form){

    let satildiMi = form.closest("tr")?.classList.contains("satildi");

    if(satildiMi){
        let pass = prompt("🔐 Yönetici şifresi gir:");

        if(!pass){
            alert("İşlem iptal edildi");
            return false;
        }

        let input = document.createElement("input");
        input.type = "hidden";
        input.name = "admin_pass";
        input.value = pass;
        form.appendChild(input);
    }

    return confirm("Bu itemi silmek istediğine emin misin?");
}


function liveSearch() {
    let q = document.getElementById("searchInput").value;

    if(q.length < 1){
        document.getElementById("liveSearchBox").style.display = "none";
        return;
    }

    const xhr = new XMLHttpRequest();
    xhr.open("GET", "search.php?q=" + encodeURIComponent(q), true);

    xhr.onload = function() {
        if (this.status === 200) {
            document.getElementById("liveResults").innerHTML = this.responseText;
            document.getElementById("liveSearchBox").style.display = "block";
        }
    };

    xhr.send();
}



function backupAl(){
    if(!confirm("Veritabanı yedeği alınsın mı?")) return;

    fetch("backup.php", { method: "POST" })
    .then(res => res.json())
    .then(data => {
        if(data.status === "ok"){
            showToast("✅ " + data.message + " (" + data.file + ")");
        }else{
            showToast("❌ " + data.message, true);
        }
    })
    .catch(() => {
        showToast("❌ Yedek alınırken hata oluştu", true);
    });
}

function showToast(msg, error=false){
    let toast = document.createElement("div");
    toast.innerText = msg;
    toast.style.position = "fixed";
    toast.style.bottom = "30px";
    toast.style.right = "30px";
    toast.style.padding = "14px 20px";
    toast.style.background = error ? "#991b1b" : "#065f46";
    toast.style.color = "#fff";
    toast.style.borderRadius = "12px";
    toast.style.fontSize = "14px";
    toast.style.boxShadow = "0 0 15px rgba(0,0,0,.4)";
    toast.style.zIndex = 10000;

    toast.style.opacity = "0";
    toast.style.transition = "0.3s";

    document.body.appendChild(toast);

    setTimeout(()=> toast.style.opacity = "1", 50);
    setTimeout(()=>{
        toast.style.opacity = "0";
        setTimeout(()=> toast.remove(), 300);
    }, 3500);
}


function backupAl(){
    if(!confirm("Veritabanı yedeği alınsın mı?")) return;

    fetch("backup.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: "token=<?= $_SESSION['csrf_token'] ?>"
    })
    .then(r => r.json())
    .then(d => {
        if(d.status === "ok"){
            showToast("✅ Yedek alındı");
        }else{
            showToast("❌ " + d.message, true);
        }
    })
    .catch(() => showToast("❌ Sistem hatası", true));
}

function startConfetti(duration = 6000){

    const canvas = document.getElementById("confettiCanvas");
    const ctx = canvas.getContext("2d");

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    let pieces = [];
    let colors = ["#38bdf8", "#22c55e", "#facc15", "#ef4444", "#a855f7"];

    for(let i=0; i<180; i++){
        pieces.push({
            x: Math.random() * canvas.width,
            y: Math.random() * canvas.height - canvas.height,
            w: 6 + Math.random() * 6,
            h: 8 + Math.random() * 10,
            color: colors[Math.floor(Math.random()*colors.length)],
            speed: 2 + Math.random() * 4,
            rotate: Math.random() * 360
        });
    }

    let start = Date.now();

    function draw(){
        ctx.clearRect(0,0,canvas.width,canvas.height);

        pieces.forEach(p=>{
            ctx.save();
            ctx.translate(p.x, p.y);
            ctx.rotate(p.rotate * Math.PI / 180);
            ctx.fillStyle = p.color;
            ctx.fillRect(-p.w/2, -p.h/2, p.w, p.h);
            ctx.restore();

            p.y += p.speed;
            p.rotate += 5;

            if(p.y > canvas.height){
                p.y = -20;
                p.x = Math.random() * canvas.width;
            }
        });

        if(Date.now() - start < duration){
            requestAnimationFrame(draw);
        }else{
            ctx.clearRect(0,0,canvas.width,canvas.height);
        }
    }

    draw();
}

document.addEventListener("DOMContentLoaded", function () {

    if (window.isBirthday) {
        openBirthdayModal();   // 🔥 MODAL AÇILIR
    }

});


function openBirthdayModal(){
    document.getElementById("birthdayModal").style.display = "flex";
    startConfetti(5500); // 5.5 saniye konfeti
}

function closeBirthdayModal(){
    document.getElementById("birthdayModal").style.display = "none";
}

</script>
<?php if($showBirthday): ?>
<script>
    window.isBirthday = true;
</script>
<?php endif; ?>


</head>

<body>

<!-- ADMİN PANELİ (Giriş yapan kullanıcı bilgisi + Çıkış) -->
<div class="admin-bar">

    <div class="admin-left">
        👤 Hoşgeldin, <b><?= htmlspecialchars($_SESSION['username']) ?></b>
    </div>

    <div class="admin-center">
        🗡 Item Alım - Satım Paneli
    </div>

    <div class="admin-right">
        <?php if($_SESSION['username'] === 'admin'){ ?>
            <button onclick="backupAl()" class="admin-btn log-btn">💾 Yedek Al</button>


        <?php } ?>



        <a href="loglar.php" class="admin-btn log-btn">📜 Loglar</a>
	<a href="item.php" class="admin-btn log-btn">🗡 İtem Fiyatlandırma</a>

        <form action="logout.php" method="POST" style="margin:0;">
            <button class="admin-btn exit-btn">Çıkış</button>
        </form>
    </div>

</div>





<!-- ÜST KONTROL PANELİ -->
<div class="control-panel">

    <!-- 🔵 1) TARİH FİLTRESİ ÜSTTE -->
    <form method="GET" style="display:flex; gap:10px;">
        <input type="date" name="t1" value="<?= $t1 ?>">
        <input type="date" name="t2" value="<?= $t2 ?>">
        <button type="submit">Ara / Filtrele</button>
    </form>

    <!-- 🔵 2) ARAMA INPUTU ALTA -->
    <input id="searchInput"
           type="text"
           placeholder="Item ara..."
           onkeyup="liveSearch()"
           style="width:300px;">

    <!-- 🔵 3) ARAMA SONUÇ KUTUSU EN ALTTA -->
    <div id="liveSearchBox" style="display:none; width:100%; margin-top:12px;">
        <div class="kutu">
            <h3>🔍 Arama Sonuçları</h3>
            <div id="liveResults"></div>
        </div>
    </div>

    <a href="index.php" class="clear-btn">Temizle</a>

</div>


<!-- ITEM EKLE / DÜZENLE FORMU -->
<div class="item-form">
    <div class="item-form-title">
        <?php if($edit){ ?>
            ✏️ Item Düzenle (#<?= $edit['id'] ?>)
        <?php } else { ?>
            ➕ Yeni Item Ekle
        <?php } ?>
    </div>

    <form method="POST">
        <div class="item-grid">

            <input name="item" value="<?= htmlspecialchars($edit['item_adi'] ?? '') ?>" placeholder="Item adı" required>
            <input name="alis" type="number" step="0.01" value="<?= @$edit['alis_fiyat'] ?>" placeholder="Alış">
            <input name="satis" type="number" step="0.01" value="<?= @$edit['satis_fiyat'] ?>" placeholder="Satış">
            <input name="guncel_satis" type="number" step="0.01" value="<?= @$edit['guncel_satis'] ?>" placeholder="Güncel">

<?php if($edit && $edit['durum']=="Satıldı"){ ?>

    <input type="datetime-local"
           name="satilma_tarihi"
           value="<?= ($edit['satilma_tarihi'] ? date('Y-m-d\TH:i', strtotime($edit['satilma_tarihi'])) : '') ?>"
           style="background:#1e293b; color:white; border:1px solid #334155; padding:10px; border-radius:8px;">

<?php } else { ?>
    <span style="visibility:hidden;">x</span>
<?php } ?>


            <select name="durum">
                <option <?= (@$edit['durum']=="Beklemede"?"selected":"") ?>>Beklemede</option>
                <option <?= (@$edit['durum']=="Satıldı"?"selected":"") ?>>Satıldı</option>
            </select>

            <input name="link" type="text" 
                   value="<?= htmlspecialchars($edit['link'] ?? '') ?>" 
                   placeholder="Item linki (isteğe bağlı)" 
                   style="grid-column:span 6;">

            <textarea name="notlar" placeholder="Notlar" style="grid-column:span 6; height:60px;"><?= htmlspecialchars($edit['notlar'] ?? '') ?></textarea>
        </div>

        <?php if($edit){ ?>
            <input type="hidden" name="id" value="<?= $edit['id'] ?>">
            <button name="duzenle_kaydet">Güncelle</button>
        <?php } else { ?>
            <button name="ekle">Kaydet</button>
        <?php } ?>
    </form>
</div>

<?php if($t1 && $t2){ ?>
<div class="kasa-wrapper" style="margin-top:0;">
    <div class="kasa-box" style="background:#0c4a6e;">
        <span class="kasa-title">Filtreli Kasada (<?= htmlspecialchars($t1) ?> → <?= htmlspecialchars($t2) ?>)</span>
        <span class="kasa-value"><?= number_format($kasadakiParaFiltreli,2,',','.') ?> TL</span>
    </div>

    <div class="kasa-box" style="background:#164e63;">
        <span class="kasa-title">Filtreli Kazanç (<?= htmlspecialchars($t1) ?> → <?= htmlspecialchars($t2) ?>)</span>
        <span class="kasa-value"><?= number_format($toplamKazanFiltreli,2,',','.') ?> TL</span>
    </div>
</div>
<?php } ?>

<br>

<div style="display:flex; gap:20px;">

<!-- BEKLEYEN -->
<div class="kutu" style="width:50%;">
<h3>⏳ Beklemede</h3>
<table>
<tr>
    <th>Eklenme</th><th>Item</th><th>Alış</th><th>Güncel</th><th>Not</th><th>İşlem</th>
</tr>

<?php while($r=$bekleyenler->fetch_assoc()){ ?>
<tr class="beklemede">
<td><?= date("d/m/Y H:i", strtotime($r["tarih"])) ?></td>

<td>
<?php if(!empty($r["link"])){ ?>
    <a href="<?= htmlspecialchars($r["link"]) ?>" target="_blank" class="item-link">
        <?= htmlspecialchars($r["item_adi"]) ?>
    </a>
<?php } else { ?>
    <?= htmlspecialchars($r["item_adi"]) ?>
<?php } ?>
</td>

<td><?= number_format($r["alis_fiyat"],2,',','.') ?></td>
<td><?= number_format($r["guncel_satis"],2,',','.') ?></td>
<td class="not-cell"><?= nl2br(htmlspecialchars($r["notlar"])) ?></td>
<td>
<button class="islem-btn satildi-btn"
        onclick="acSatisFormu(<?= $r['id'] ?>)">
    ✔
</button>

    <form method="POST" style="display:inline;">
        <input type="hidden" name="id" value="<?= $r["id"] ?>">
        <button class="islem-btn duzenle-btn" name="duzenle">✏️</button>
    </form>
    <form method="POST" style="display:inline;">
        <input type="hidden" name="id" value="<?= $r["id"] ?>">
        <button class="islem-btn sil-btn" name="sil"
                onclick="return confirm('Bu itemi silmek istediğine emin misin?');">🗑</button>
    </form>
</td>
</tr>
<tr id="satis-form-<?= $r['id'] ?>" style="display:none; background:#020617;">
<td colspan="6">
    <form method="POST" style="display:flex; gap:10px; align-items:center;">
        <input type="hidden" name="id" value="<?= $r['id'] ?>">

        <input type="number"
               step="0.01"
               name="satis_fiyat"
               placeholder="Satış fiyatı"
               required
               style="flex:1;">

        <button class="islem-btn satildi-btn" name="satildi_formdan">
            Satıldı Olarak Kaydet
        </button>

        <button type="button"
                class="islem-btn sil-btn"
                onclick="kapatSatisFormu(<?= $r['id'] ?>)">
            İptal
        </button>
    </form>
</td>
</tr>

<?php } ?>
</table>

<?php 
$total_beklemede = $baglan->query("
    SELECT COUNT(*) AS t FROM items 
    WHERE TRIM(durum)='Beklemede' 
    AND item_adi LIKE '%$arama%'
")->fetch_assoc()['t'];

$pages_beklemede = ceil($total_beklemede / $limit);
?>

<div style="margin-top:10px; text-align:center;">
<?php for($i=1; $i <= $pages_beklemede; $i++): ?>
<a href="?pb=<?= $i ?>&ara=<?= urlencode($arama) ?>&t1=<?= htmlspecialchars($t1) ?>&t2=<?= htmlspecialchars($t2) ?>" 
   class="page-link"><?= $i ?></a>
<?php endfor; ?>
</div>

</div>

<!-- SATILAN -->
<div class="kutu" style="width:50%;">
<h3>✅ Satılanlar</h3>
<table>
<tr>
    <th>Satış Tarih</th><th>Item</th><th>Alış</th><th>Satış</th><th>Not</th><th>İşlem</th>
</tr>

<?php while($r=$satilanlar->fetch_assoc()){ ?>
<tr class="satildi">
<td><?= $r["satilma_tarihi"] ? date("d/m/Y H:i", strtotime($r["satilma_tarihi"])) : "-" ?></td>

<td>
<?php if(!empty($r["link"])){ ?>
    <a href="<?= htmlspecialchars($r["link"]) ?>" target="_blank" class="item-link">
        <?= htmlspecialchars($r["item_adi"]) ?>
    </a>
<?php } else { ?>
    <?= htmlspecialchars($r["item_adi"]) ?>
<?php } ?>
</td>

<td><?= number_format($r["alis_fiyat"],2,',','.') ?></td>
<td><?= number_format($r["satis_fiyat"],2,',','.') ?></td>
<td class="not-cell"><?= nl2br(htmlspecialchars($r["notlar"])) ?></td>
<td>
    <form method="POST" style="display:inline;">
        <input type="hidden" name="id" value="<?= $r["id"] ?>">
        <button class="islem-btn duzenle-btn" name="duzenle">✏️</button>
    </form>
<form method="POST" style="display:inline;" onsubmit="return adminConfirm(this);">
    <input type="hidden" name="id" value="<?= $r["id"] ?>">
    <button class="islem-btn sil-btn" name="sil">🗑</button>
</form>

</form>

</td>
</tr>
<?php } ?>
</table>

<?php 
$total_satilan = $baglan->query("
    SELECT COUNT(*) AS t FROM items 
    WHERE TRIM(durum)='Satıldı'
    AND item_adi LIKE '%$arama%'
    $filtre
")->fetch_assoc()['t'];

$pages_satilan = ceil($total_satilan / $limit);
?>

<div style="margin-top:10px; text-align:center;">
<?php for($i=1; $i <= $pages_satilan; $i++): ?>
<a href="?ps=<?= $i ?>&ara=<?= urlencode($arama) ?>&t1=<?= htmlspecialchars($t1) ?>&t2=<?= htmlspecialchars($t2) ?>" 
   class="page-link"><?= $i ?></a>
<?php endfor; ?>
</div>

</div>

</div>

<br>

<div class="kasa-wrapper">
    <div class="kasa-box">
        <span class="kasa-title">Stoktaki İtemlerin Maliyeti</span>
        <span class="kasa-value"><?= number_format($beklemedePara,2,',','.') ?> TL</span>
    </div>

    <div class="kasa-box">
        <span class="kasa-title">Satılan İtemlerin Totali</span>
        <span class="kasa-value"><?= number_format($kasadakiPara,2,',','.') ?> TL</span>
    </div>

    <div class="kasa-box">
        <span class="kasa-title">Toplam Kazanç</span>
 <span class="kasa-value">
    <?= number_format($toplamKazan,2,',','.') ?> TL
    <small style="color:#7dd3fc;">(<?= number_format($karYuzde,2,',','.') ?>%)</small>
</span>

    </div>
</div>
<canvas id="confettiCanvas"
        style="position:fixed; inset:0; pointer-events:none; z-index:9999;"></canvas>
<div id="birthdayModal" style="
    position:fixed;
    inset:0;
    background:rgba(2,6,23,0.75);
    backdrop-filter:blur(6px);
    display:none;
    align-items:center;
    justify-content:center;
    z-index:10001;
">
    <div style="
        background:linear-gradient(135deg,#020617,#0f172a);
        border:2px solid #38bdf8;
        border-radius:20px;
        padding:40px 50px;
        text-align:center;
        box-shadow:0 0 40px rgba(56,189,248,0.6);
        animation:popIn .6s ease-out;
        max-width:420px;
    ">
        <div style="font-size:42px;">🎉🎂🎉</div>
        <h1 style="margin:15px 0; color:#38bdf8;">
            Doğum Günün Kutlu Olsun!
        </h1>
        <h2 style="color:#e5e7eb; margin-bottom:10px;">
            Furkan
        </h2>
        <p style="color:#94a3b8; font-size:15px;">
            Bol kazançlı, sağlıklı bir yıl olsun 🚀
        </p>

        <button onclick="closeBirthdayModal()" style="
            margin-top:25px;
            padding:12px 28px;
            font-size:15px;
            border-radius:12px;
            border:none;
            cursor:pointer;
            background:linear-gradient(135deg,#22c55e,#16a34a);
            color:white;
            box-shadow:0 0 15px rgba(34,197,94,0.6);
        ">
            🎁 Teşekkürler
        </button>
    </div>
</div>

<style>
@keyframes popIn{
    from{ transform:scale(.6); opacity:0 }
    to{ transform:scale(1); opacity:1 }
}
</style>


</body>
</html>
