<?php
session_start();
include 'db.php';

if (!isset($_SESSION['username'])) {
   header("Location: index.php");
   exit;
}

$nama_onderdil = $harga_beli = $harga_jual = $stok_onderdil = "";
$hasil_cari = [];
$pesan = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // ====== PENCARIAN MIRIP NAMA ======
    if (isset($_POST['cari'])) {
        $cari = "%" . trim($_POST['sp']) . "%";
        $stmt = $conn->prepare("SELECT Nama_onderdil, Harga_beli, Harga_jual, Stok FROM onderdil WHERE Nama_onderdil LIKE ?");
        $stmt->bind_param("s", $cari);
        $stmt->execute();
        $result = $stmt->get_result();
        $hasil_cari = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
    }

    // ====== EDIT DATA (MUNCULKAN FORM) ======
    if (isset($_POST['edit'])) {
        $nama_edit = trim($_POST['nama_edit']);
        $stmt = $conn->prepare("SELECT Nama_onderdil, Harga_beli, Harga_jual, Stok FROM onderdil WHERE Nama_onderdil=?");
        $stmt->bind_param("s", $nama_edit);
        $stmt->execute();
        $stmt->bind_result($nama_onderdil, $harga_beli, $harga_jual, $stok_onderdil);
        $stmt->fetch();
        $stmt->close();
    }

    // ====== UPDATE DATA ======
    if (isset($_POST['update'])) {
        $nama_lama = trim($_POST['nama_lama']);
        $nama = trim($_POST['nama']);
        $beli = (int) $_POST['beli'];
        $jual = (int) $_POST['jual'];
        $stok = (int) $_POST['stok'];

        $stmt = $conn->prepare("UPDATE onderdil 
            SET Nama_onderdil=?, Harga_beli=?, Harga_jual=?, Stok=? 
            WHERE Nama_onderdil=?");
        $stmt->bind_param("siiis", $nama, $beli, $jual, $stok, $nama_lama);

        if ($stmt->execute()) {
            $pesan = "<div class='msg success'>✅ Data berhasil diperbarui!</div>";
        } else {
            $pesan = "<div class='msg error'>❌ Gagal memperbarui data!</div>";
        }
        $stmt->close();
    }

    // ====== HAPUS DATA ======
    if (isset($_POST['hapus'])) {
        $hapus = trim($_POST['nama_hapus']);
        $stmt = $conn->prepare("DELETE FROM onderdil WHERE Nama_onderdil=?");
        $stmt->bind_param("s", $hapus);
        if ($stmt->execute()) {
            $pesan = "<div class='msg success'>🗑️ Data '$hapus' telah dihapus!</div>";
        } else {
            $pesan = "<div class='msg error'>❌ Gagal menghapus data!</div>";
        }
        $stmt->close();
    }
}

$conn->close();
?>

<html>
<head>
<title>Manajemen Spare Part</title>
<style>
body {
    font-family: Verdana, sans-serif;
    background: linear-gradient(135deg, #f3f3f3, #dfe9f3);
    margin: 0;
    padding: 0;
}
.container {
    width: 90%;
    max-width: 800px;
    margin: 50px auto;
    background: white;
    padding: 30px;
    border-radius: 15px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    text-align: center;
}
h2 { color: #0077aa; margin-bottom: 20px; }
input[type=text], input[type=number] {
    width: 80%;
    padding: 10px;
    margin: 8px 0;
    border: 1px solid #ccc;
    border-radius: 8px;
    font-size: 14px;
}
input[type=submit], button {
    background: #0077aa;
    color: white;
    border: none;
    padding: 8px 15px;
    border-radius: 6px;
    font-size: 14px;
    cursor: pointer;
}
input[type=submit]:hover, button:hover {
    background: #005f88;
}
table {
    border-collapse: collapse;
    width: 100%;
    margin-top: 20px;
}
th, td {
    border: 1px solid #ccc;
    padding: 8px;
}
th { background: #0077aa; color: white; }
.msg { margin: 10px 0; padding: 10px; border-radius: 6px; font-weight: bold; }
.msg.success { background: #d9f9d9; color: #007700; }
.msg.error { background: #ffd6d6; color: #cc0000; }
a { text-decoration: none; color: #0077aa; }
</style>
<script>
function konfirmasiHapus(nama) {
    return confirm("Yakin ingin menghapus spare part '" + nama + "' ?");
}
</script>
</head>

<body>
<div class="container">
    <h2>⚙️ Manajemen Spare Part</h2>
    <?php if ($pesan) echo $pesan; ?>

    <form method="post">
        <b>Cari Nama Spare Part:</b><br>
        <input type="text" name="sp" placeholder="contoh: Kampas" required>
        <input type="submit" name="cari" value="Cari">
    </form>

    <?php if (count($hasil_cari) > 0): ?>
    <table>
        <tr>
            <th>Nama</th>
            <th>Harga Beli</th>
            <th>Harga Jual</th>
            <th>Stok</th>
            <th>Aksi</th>
        </tr>
        <?php foreach ($hasil_cari as $r): ?>
        <tr>
            <td><?= htmlspecialchars($r['Nama_onderdil']) ?></td>
            <td align="right"><?= number_format($r['Harga_beli']) ?></td>
            <td align="right"><?= number_format($r['Harga_jual']) ?></td>
            <td align="center"><?= htmlspecialchars($r['Stok']) ?></td>
            <td>
                <form method="post" style="display:inline;">
                    <input type="hidden" name="nama_edit" value="<?= htmlspecialchars($r['Nama_onderdil']) ?>">
                    <input type="submit" name="edit" value="Edit">
                </form>
                <form method="post" style="display:inline;" onsubmit="return konfirmasiHapus('<?= htmlspecialchars($r['Nama_onderdil']) ?>');">
                    <input type="hidden" name="nama_hapus" value="<?= htmlspecialchars($r['Nama_onderdil']) ?>">
                    <input type="submit" name="hapus" value="Hapus">
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
    <?php elseif (isset($_POST['cari'])): ?>
        <p><i>Tidak ada hasil untuk pencarian tersebut.</i></p>
    <?php endif; ?>

    <?php if (!empty($nama_onderdil)): ?>
    <hr><h3>Edit Data</h3>
    <form method="post">
        <input type="hidden" name="nama_lama" value="<?= htmlspecialchars($nama_onderdil) ?>">
        <input type="text" name="nama" value="<?= htmlspecialchars($nama_onderdil) ?>" required><br>
        <input type="number" name="beli" value="<?= htmlspecialchars($harga_beli) ?>" required><br>
        <input type="number" name="jual" value="<?= htmlspecialchars($harga_jual) ?>" required><br>
        <input type="number" name="stok" value="<?= htmlspecialchars($stok_onderdil) ?>" required><br>
        <input type="submit" name="update" value="💾 Simpan Perubahan">
    </form>
    <?php endif; ?>

    <br><a href="dashboard.php">⬅️ Kembali ke Dashboard</a>
</div>
</body>
</html>
