<?php
session_start();

include 'db.php';

if ($_SESSION['username'] !== "admin@admin.com") {
    header("Location: login.php");
    exit;
}

$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

$namabrg = trim($_POST['nama_brg'] ?? '');
$aksi    = $_POST['aksi'] ?? '';
$data_barang = null;

// ===================================================
// MODE 1 — CARI DATA (tidak case sensitive & sebagian kata)
// ===================================================
if ($aksi === 'cari' && !empty($namabrg)) {
    $keyword = "%" . strtolower($namabrg) . "%"; // gunakan LIKE + lower()

    $stmt = $conn->prepare("
        SELECT no_id, Nama_barang, Harga, Stok, Diskon, Gbr_brg 
        FROM barang 
        WHERE LOWER(Nama_barang) LIKE ?
        LIMIT 10
    ");
    $stmt->bind_param("s", $keyword);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        echo "<center><b>Ditemukan {$result->num_rows} barang cocok dengan kata '<u>" . htmlspecialchars($namabrg) . "</u>'</b></center><br>";
        echo "<center><table border=1 cellpadding=5 cellspacing=0>";
        echo "<tr bgcolor='#efefef'><th>No ID</th><th>Nama Barang</th><th>Harga</th><th>Stok</th><th>Diskon</th><th>Gambar</th><th>Aksi</th></tr>";
        while ($row = $result->fetch_assoc()) {
            echo "<tr>";
            echo "<td>{$row['no_id']}</td>";
            echo "<td>{$row['Nama_barang']}</td>";
            echo "<td>{$row['Harga']}</td>";
            echo "<td>{$row['Stok']}</td>";
            echo "<td>{$row['Diskon']}%</td>";
            echo "<td><img src='gambar/{$row['Gbr_brg']}' width='60'></td>";
            echo "<td>
                    <form method='post'>
                        <input type='hidden' name='nama_brg' value='" . htmlspecialchars($row['Nama_barang']) . "'>
                        <button type='submit' name='aksi' value='pilih'>Pilih</button>
                    </form>
                  </td>";
            echo "</tr>";
        }
        echo "</table></center><br>";
    } else {
        echo "<center><font color=red><b>⚠️ Tidak ada barang mengandung kata '<u>" . htmlspecialchars($namabrg) . "</u>'</b></font></center>";
    }
    $stmt->close();
}

// ===================================================
// MODE 2 — PILIH DATA (setelah klik tombol pilih di hasil pencarian)
// ===================================================
if ($aksi === 'pilih' && !empty($namabrg)) {
    $stmt = $conn->prepare("SELECT no_id, Nama_barang, Harga, Stok, Diskon, Gbr_brg FROM barang WHERE Nama_barang = ?");
    $stmt->bind_param("s", $namabrg);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        $data_barang = $row;
    }
    $stmt->close();
}

// ===================================================
// MODE 3 — UPDATE DATA (tetap seperti sebelumnya)
// ===================================================
if ($aksi === 'update') {
    $no_id     = (int) ($_POST['no_id'] ?? 0);
    $nama_baru = trim($_POST['namaku'] ?? '');
    $harga     = (int) ($_POST['rego'] ?? 0);
    $stok      = (int) ($_POST['sisa'] ?? 0);
    $diskon    = (int) ($_POST['diskon'] ?? 0);

    $target_dir  = "gambar/";
    $nama_file   = basename($_FILES["gambar_brg"]["name"] ?? '');
    $target_file = $target_dir . $nama_file;
    $uploadOk    = 1;
    $gambar_baru = '';

    if (!empty($_FILES["gambar_brg"]["tmp_name"])) {
        $check = getimagesize($_FILES["gambar_brg"]["tmp_name"]);
        if ($check === false) {
            echo "❌ File bukan gambar.<br>";
            $uploadOk = 0;
        }

        if ($_FILES["gambar_brg"]["size"] > 5000000) {
            echo "❌ Ukuran file terlalu besar (max 5MB).<br>";
            $uploadOk = 0;
        }

        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        if (!in_array($imageFileType, ["jpg", "jpeg", "png", "gif"])) {
            echo "❌ Hanya file JPG, JPEG, PNG & GIF diizinkan.<br>";
            $uploadOk = 0;
        }

        if ($uploadOk == 1) {
            $unique_name = uniqid("img_", true) . "." . $imageFileType;
            $final_path = $target_dir . $unique_name;
            if (move_uploaded_file($_FILES["gambar_brg"]["tmp_name"], $final_path)) {
                $gambar_baru = $unique_name;
            } else {
                echo "❌ Gagal upload file.<br>";
                $uploadOk = 0;
            }
        }
    }

    if (empty($gambar_baru)) {
        $res = $conn->prepare("SELECT Gbr_brg FROM barang WHERE no_id = ?");
        $res->bind_param("i", $no_id);
        $res->execute();
        $res->bind_result($gambar_lama);
        $res->fetch();
        $gambar_baru = $gambar_lama ?? '';
        $res->close();
    }

    if ($no_id > 0 && $nama_baru !== '') {
        $stmt = $conn->prepare("UPDATE barang SET Nama_barang=?, Harga=?, Stok=?, Diskon=?, Gbr_brg=? WHERE no_id=?");
        $stmt->bind_param("siiisi", $nama_baru, $harga, $stok, $diskon, $gambar_baru, $no_id);
        if ($stmt->execute()) {
            echo "<center><font color=green><b>✅ Data berhasil diupdate!</b></font></center>";
        } else {
            echo "<center><font color=red><b>❌ Error: {$stmt->error}</b></font></center>";
        }
        $stmt->close();
    }
}

$conn->close();
?>

<!-- =================================================== -->
<!-- FORM HTML -->
<!-- =================================================== -->
<html>
<head>
    <title>Update Data Barang</title>
    <meta charset="UTF-8">
</head>
<body>
<center>
    <h2>🔍 Cari Barang</h2>
    <form method="post">
        Nama Barang (bebas huruf besar kecil): 
        <input type="text" name="nama_brg" placeholder="Ketik sebagian nama..." required>
        <button type="submit" name="aksi" value="cari">Cari</button>
    </form>
</center>

<?php if (!empty($data_barang)): ?>
<hr>
<center>
    <h2>✏️ Form Update Barang</h2>
    <form enctype="multipart/form-data" method="post">
        <input type="hidden" name="no_id" value="<?= htmlspecialchars($data_barang['no_id']); ?>">
        <table border="0" cellpadding="5">
            <tr><td>No ID</td><td><b><?= htmlspecialchars($data_barang['no_id']); ?></b></td></tr>
            <tr><td>Nama Barang</td><td><input type="text" name="namaku" value="<?= htmlspecialchars($data_barang['Nama_barang']); ?>"></td></tr>
            <tr><td>Harga</td><td><input type="number" name="rego" value="<?= htmlspecialchars($data_barang['Harga']); ?>"></td></tr>
            <tr><td>Stok</td><td><input type="number" name="sisa" value="<?= htmlspecialchars($data_barang['Stok']); ?>"></td></tr>
            <tr><td>Diskon (%)</td><td><input type="number" name="diskon" value="<?= htmlspecialchars($data_barang['Diskon']); ?>"></td></tr>
            <tr><td>Gambar</td>
                <td>
                    <?php if (!empty($data_barang['Gbr_brg'])): ?>
                        <img src="gambar/<?= htmlspecialchars($data_barang['Gbr_brg']); ?>" width="100"><br>
                    <?php endif; ?>
                    <input type="file" name="gambar_brg" accept="image/*">
                </td>
            </tr>
            <tr><td colspan="2" align="center"><button type="submit" name="aksi" value="update">💾 Simpan Perubahan</button></td></tr>
        </table>
    </form>
</center>
<?php endif; ?>
<br><br>
<center><a href="admin_dashboard.php">⬅️ Kembali ke Dashboard</a></center>
</body>
</html>
