<?php
session_start();

include 'db.php';

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

$nama_brg = trim($_POST['nama_brg'] ?? '');
$harga    = (int)($_POST['rego'] ?? 0);
$stok     = (int)($_POST['sisa'] ?? 0);
$diskon   = (int)($_POST['diskon'] ?? 0);
$message  = "";

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

    $target_dir = "gambar/";
    if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);

    // 🔧 Bersihkan nama file gambar
    $raw_name   = basename($_FILES["gbr_brg"]["name"]);
    $nama_bersih = preg_replace("/[^A-Za-z0-9_\-\.]/", "_", $raw_name); // hanya huruf, angka, _, -, .
    $nama_bersih = strtolower(str_replace(" ", "_", $nama_bersih));     // huruf kecil & ganti spasi jadi _
    $target_file = $target_dir . $nama_bersih;
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    $uploadOk = 1;

    if (isset($_FILES["gbr_brg"]["tmp_name"]) && $_FILES["gbr_brg"]["tmp_name"] != "") {
        $check = getimagesize($_FILES["gbr_brg"]["tmp_name"]);
        if ($check === false) {
            $message .= "❌ File bukan gambar.<br>";
            $uploadOk = 0;
        }

        if (file_exists($target_file)) {
            $message .= "⚠️ File dengan nama ini sudah ada. Ganti nama file atau pilih file lain.<br>";
            $uploadOk = 0;
        }

        if ($_FILES["gbr_brg"]["size"] > 5 * 1024 * 1024) {
            $message .= "⚠️ Ukuran file terlalu besar (maks 5MB).<br>";
            $uploadOk = 0;
        }

        if (!in_array($imageFileType, ["jpg", "jpeg", "png", "gif"])) {
            $message .= "⚠️ Hanya JPG, JPEG, PNG & GIF yang diizinkan.<br>";
            $uploadOk = 0;
        }

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

            // 🔍 Cek duplikasi nama barang
            $cek = $conn->prepare("SELECT COUNT(*) FROM barang WHERE LOWER(Nama_barang) = LOWER(?)");
            $cek->bind_param("s", $nama_brg);
            $cek->execute();
            $cek->bind_result($jumlah);
            $cek->fetch();
            $cek->close();

            if ($jumlah > 0) {
                $message .= "<span class='error'>⚠️ Barang dengan nama <b>$nama_brg</b> sudah ada. Gunakan nama lain.</span><br>";
                $conn->close();
            } else {
                // 🚀 Upload gambar
                if (move_uploaded_file($_FILES["gbr_brg"]["tmp_name"], $target_file)) {
                    $stmt = $conn->prepare("INSERT INTO barang (Nama_barang, Harga, Stok, Diskon, Gbr_brg)
                                            VALUES (?, ?, ?, ?, ?)");
                    $stmt->bind_param("siiis", $nama_brg, $harga, $stok, $diskon, $nama_bersih);

                    if ($stmt->execute()) {
                        $message .= "<span class='success'>✅ Data barang <b>$nama_brg</b> berhasil disimpan dengan gambar <b>$nama_bersih</b>.</span><br>";
                    } else {
                        $message .= "<span class='error'>❌ Gagal menyimpan data: {$stmt->error}</span><br>";
                    }

                    $stmt->close();
                    $conn->close();
                } else {
                    $message .= "<span class='error'>❌ Terjadi kesalahan saat mengupload file.</span><br>";
                }
            }
        }
    } else {
        $message .= "⚠️ Tidak ada file diupload.<br>";
    }
}
?>

<html>
<head>
    <title>Tambah Data Barang</title>
    <style>
        body {
            font-family: Verdana;
            background-color: #f2f2f2;
        }
        .container {
            width: 600px;
            margin: 40px auto;
            background: white;
            padding: 30px 40px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        h1 {
            text-align: center;
            color: #004aad;
        }
        table {
            width: 100%;
            font-size: 14px;
        }
        td {
            padding: 8px;
        }
        input[type=text],
        input[type=number],
        input[type=file] {
            width: 95%;
            padding: 8px;
            border: 1px solid #aaa;
            border-radius: 6px;
        }
        button {
            background-color: #004aad;
            color: white;
            padding: 10px 25px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
        }
        button:hover {
            background-color: #00337a;
        }
        .message {
            text-align: center;
            margin-bottom: 15px;
        }
        .success {
            color: green;
            font-weight: bold;
        }
        .error {
            color: red;
            font-weight: bold;
        }
        #preview {
            display: none;
            margin-top: 10px;
            max-width: 200px;
            border: 1px solid #aaa;
            border-radius: 8px;
        }
        .back-link {
            text-align: center;
            margin-top: 20px;
        }
        .back-link a {
            color: #004aad;
            text-decoration: none;
        }
        .back-link a:hover {
            text-decoration: underline;
        }
    </style>

    <script>
        function previewImage(event) {
            const file = event.target.files[0];
            const preview = document.getElementById('preview');
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                };
                reader.readAsDataURL(file);
            } else {
                preview.src = "";
                preview.style.display = 'none';
            }
        }
    </script>
</head>

<body>
<div class="container">
    <h1>Tambah Data Barang</h1>

    <?php if (!empty($message)) echo "<div class='message'>$message</div>"; ?>

    <form method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>Nama Barang</td>
                <td><input type="text" name="nama_brg" required></td>
            </tr>
            <tr>
                <td>Harga Barang</td>
                <td><input type="number" name="rego" min="0" required></td>
            </tr>
            <tr>
                <td>Stok</td>
                <td><input type="number" name="sisa" min="0" required></td>
            </tr>
            <tr>
                <td>Diskon (%)</td>
                <td><input type="number" name="diskon" min="0" max="100" required></td>
            </tr>
            <tr>
                <td>Foto Barang</td>
                <td>
                    <input type="file" name="gbr_brg" accept="image/*" onchange="previewImage(event)" required>
                    <br><img id="preview">
                </td>
            </tr>
        </table>
        <div style="text-align:center;margin-top:20px;">
            <button type="submit" onclick="this.disabled=true; this.form.submit();">💾 Simpan Barang</button>
        </div>
    </form>

    <div class="back-link">
        <a href="admin_dashboard.php">← Kembali ke Dashboard</a>
    </div>
</div>
</body>
</html>
