<?php
session_start();
if(!isset($_SESSION['admin'])){
    header("Location: /frozenfood/");
    exit;
}
include 'koneksi.php';

$id = $_GET['id'];
$data = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM produk WHERE id='$id'"));

if(isset($_POST['update'])){
    $nama = $_POST['nama_produk'];
    $harga = $_POST['harga'];
    $stok = $_POST['stok'];
    $deskripsi = $_POST['deskripsi'];

    $gambar = $data['gambar'];

    if($_FILES['gambar']['name'] != ""){
        $gambar = $_FILES['gambar']['name'];
        $tmp = $_FILES['gambar']['tmp_name'];
        move_uploaded_file($tmp, "images/".$gambar);
    }

    mysqli_query($conn, "UPDATE produk SET
        nama_produk='$nama',
        harga='$harga',
        stok='$stok',
        deskripsi='$deskripsi',
        gambar='$gambar'
        WHERE id='$id'
    ");

    echo "<script>alert('Produk berhasil diupdate'); window.location='admin.php';</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Edit Produk</title>
    <style>
        body{
            font-family: Arial;
            background: #f4f6f9;
        }
        .box{
            width: 500px;
            margin: 40px auto;
            background: white;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        input, textarea{
            width: 100%;
            padding: 12px;
            margin: 10px 0;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-sizing: border-box;
        }
        textarea{
            resize: none;
        }
        .btn{
            padding: 12px 18px;
            border: none;
            border-radius: 8px;
            color: white;
            font-weight: bold;
            cursor: pointer;
        }
        .save{background:#28a745;}
        .back{
            background:#007bff;
            text-decoration:none;
            display:inline-block;
        }
    </style>
</head>
<body>

<div class="box">
    <h2>Edit Produk</h2>
    <form method="POST" enctype="multipart/form-data">
        <label>Nama Produk</label>
        <input type="text" name="nama_produk" value="<?= $data['nama_produk'] ?>" required>

        <label>Harga</label>
        <input type="number" name="harga" value="<?= $data['harga'] ?>" required>

        <label>Stok</label>
        <input type="number" name="stok" value="<?= $data['stok'] ?>" required>

        <label>Deskripsi</label>
        <textarea name="deskripsi" rows="4" required><?= $data['deskripsi'] ?></textarea>

        <label>Gambar Baru (opsional)</label>
        <input type="file" name="gambar">

        <a href="admin.php" class="btn back">Kembali</a>
        <button type="submit" name="update" class="btn save">Update</button>
    </form>
</div>

</body>
</html>