<?php
require_once '../../config/database.php';
require_once '../../includes/auth.php';

$id_barang = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Get inventory item data
$stmt = $conn->prepare("SELECT * FROM pdta_inventaris_barang WHERE id_barang = ?");
$stmt->bind_param("i", $id_barang);
$stmt->execute();
$result = $stmt->get_result();
$barang = $result->fetch_assoc();

if (!$barang) {
    $_SESSION['error'] = "Data barang tidak ditemukan";
    header("Location: index.php");
    exit();
}

// Get data for dropdowns
$lokasi = $conn->query("SELECT * FROM pdta_lokasi ORDER BY nama_lokasi");
$jenis = $conn->query("SELECT * FROM pdta_jenis_barang ORDER BY nama_jenis");
$asal = $conn->query("SELECT * FROM pdta_asal_usul ORDER BY sumber_asal");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect all form data
    $data = [
        'kode_barang' => $_POST['kode_barang'],
        'nama_barang' => $_POST['nama_barang'],
        'deskripsi' => $_POST['deskripsi'],
        'merk' => $_POST['merk'],
        'type' => $_POST['type'],
        'ukuran' => $_POST['ukuran'],
        'bahan' => $_POST['bahan'],
        'jumlah' => $_POST['jumlah'],
        'tahun_pembelian' => $_POST['tahun_pembelian'],
        'kondisi' => $_POST['kondisi'],
        'keterangan' => $_POST['keterangan'],
        'id_lokasi' => $_POST['id_lokasi'],
        'id_jenis' => $_POST['id_jenis'],
        'id_asal' => $_POST['id_asal']
    ];
    
    // Handle file upload
    if (isset($_FILES['foto']) && $_FILES['foto']['error'] !== UPLOAD_ERR_NO_FILE) {
        $file = $_FILES['foto'];
        
        // Check file size (max 200KB)
        if ($file['size'] > 200 * 1024) {
            $_SESSION['error'] = "Ukuran foto maksimal 200KB";
            header("Location: edit.php?id=" . $id_barang);
            exit();
        }
        
        if ($file['error'] === UPLOAD_ERR_OK) {
            // Delete old photo if exists
            if ($foto && file_exists('../../uploads/' . $foto)) {
                unlink('../../uploads/' . $foto);
            }
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            $foto = uniqid() . '.' . $ext;
            move_uploaded_file($file['tmp_name'], '../../uploads/' . $foto);
            $data['foto'] = $foto;
        }
    }
    
    // Check if item code already exists (excluding current item)
    $check = $conn->prepare("SELECT id_barang FROM pdta_inventaris_barang WHERE kode_barang = ? AND id_barang != ?");
    $check->bind_param("si", $data['kode_barang'], $id_barang);
    $check->execute();
    $check->store_result();
    
    if ($check->num_rows > 0) {
        $_SESSION['error'] = "Kode barang sudah digunakan";
    } else {
        // Prepare SQL query
        $setClause = implode(' = ?, ', array_keys($data)) . ' = ?';
        $types = str_repeat('s', count($data)) . 'i';
        $values = array_values($data);
        $values[] = $id_barang;
        
        $stmt = $conn->prepare("UPDATE pdta_inventaris_barang SET $setClause WHERE id_barang = ?");
        $stmt->bind_param($types, ...$values);
        
        if ($stmt->execute()) {
            $_SESSION['success'] = "Data barang berhasil diperbarui!";
            header("Location: index.php");
            exit();
        } else {
            $_SESSION['error'] = "Gagal memperbarui data barang: " . $conn->error;
            // Delete uploaded file if there was an error
            if (isset($file)) {
                unlink('../../uploads/' . $foto);
            }
        }
    }
}
?>

<?php include '../../includes/header.php'; ?>
<?php include '../../includes/navbar.php'; ?>

<div class="container mt-4">
    <div class="card shadow">
        <div class="card-header bg-primary text-white">
            <h4 class="mb-0"><i class="bi bi-pencil-square"></i> Edit Barang Inventaris</h4>
        </div>
        <div class="card-body">
            <form method="POST" enctype="multipart/form-data">
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="kode_barang" class="form-label">Kode Barang <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="kode_barang" name="kode_barang" 
                                   value="<?= htmlspecialchars($barang['kode_barang']) ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="nama_barang" class="form-label">Nama Barang <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="nama_barang" name="nama_barang" 
                                   value="<?= htmlspecialchars($barang['nama_barang']) ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="deskripsi" class="form-label">Deskripsi</label>
                            <textarea class="form-control" id="deskripsi" name="deskripsi" rows="2"><?= htmlspecialchars($barang['deskripsi']) ?></textarea>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="merk" class="form-label">Merk</label>
                                    <input type="text" class="form-control" id="merk" name="merk" 
                                           value="<?= htmlspecialchars($barang['merk']) ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="type" class="form-label">Type</label>
                                    <input type="text" class="form-control" id="type" name="type" 
                                           value="<?= htmlspecialchars($barang['type']) ?>">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="ukuran" class="form-label">Ukuran</label>
                                    <input type="text" class="form-control" id="ukuran" name="ukuran" 
                                           value="<?= htmlspecialchars($barang['ukuran']) ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="bahan" class="form-label">Bahan</label>
                                    <input type="text" class="form-control" id="bahan" name="bahan" 
                                           value="<?= htmlspecialchars($barang['bahan']) ?>">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="jumlah" class="form-label">Jumlah <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="jumlah" name="jumlah" 
                                           value="<?= htmlspecialchars($barang['jumlah']) ?>" min="1" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="tahun_pembelian" class="form-label">Tahun Pembelian</label>
                                    <input type="number" class="form-control" id="tahun_pembelian" name="tahun_pembelian" 
                                           value="<?= htmlspecialchars($barang['tahun_pembelian']) ?>" min="1900" max="<?= date('Y') ?>">
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="kondisi" class="form-label">Kondisi <span class="text-danger">*</span></label>
                            <select class="form-select" id="kondisi" name="kondisi" required>
                                <option value="Baik" <?= $barang['kondisi'] == 'Baik' ? 'selected' : '' ?>>Baik</option>
                                <option value="Rusak Ringan" <?= $barang['kondisi'] == 'Rusak Ringan' ? 'selected' : '' ?>>Rusak Ringan</option>
                                <option value="Rusak Berat" <?= $barang['kondisi'] == 'Rusak Berat' ? 'selected' : '' ?>>Rusak Berat</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="keterangan" class="form-label">Keterangan</label>
                            <textarea class="form-control" id="keterangan" name="keterangan" rows="2"><?= htmlspecialchars($barang['keterangan']) ?></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="foto" class="form-label">Foto Barang</label>
                            <input type="file" class="form-control" id="foto" name="foto" accept="image/*">
                            <small class="text-muted">Maksimal ukuran file: 200KB (Format: JPG, PNG)</small>
                            <?php if ($barang['foto']) : ?>
                                <div class="mt-2">
                                    <img src="../../uploads/<?= $barang['foto'] ?>" alt="Foto Barang" style="max-height: 100px;">
                                    <div class="form-check mt-2">
                                        <input class="form-check-input" type="checkbox" id="hapus_foto" name="hapus_foto">
                                        <label class="form-check-label" for="hapus_foto">Hapus foto</label>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="id_lokasi" class="form-label">Lokasi <span class="text-danger">*</span></label>
                            <select class="form-select" id="id_lokasi" name="id_lokasi" required>
                                <option value="">Pilih Lokasi</option>
                                <?php while ($row = $lokasi->fetch_assoc()) : ?>
                                    <option value="<?= $row['id_lokasi'] ?>" <?= $barang['id_lokasi'] == $row['id_lokasi'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($row['nama_lokasi']) ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="id_jenis" class="form-label">Jenis Barang <span class="text-danger">*</span></label>
                            <select class="form-select" id="id_jenis" name="id_jenis" required>
                                <option value="">Pilih Jenis</option>
                                <?php while ($row = $jenis->fetch_assoc()) : ?>
                                    <option value="<?= $row['id_jenis'] ?>" <?= $barang['id_jenis'] == $row['id_jenis'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($row['nama_jenis']) ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="id_asal" class="form-label">Asal Usul</label>
                            <select class="form-select" id="id_asal" name="id_asal">
                                <option value="">Pilih Asal Usul</option>
                                <?php while ($row = $asal->fetch_assoc()) : ?>
                                    <option value="<?= $row['id_asal'] ?>" <?= $barang['id_asal'] == $row['id_asal'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($row['sumber_asal']) ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="d-flex justify-content-between mt-4">
                    <a href="index.php" class="btn btn-secondary">
                        <i class="bi bi-arrow-left"></i> Kembali
                    </a>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save"></i> Simpan Perubahan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="../../assets/js/jquery.min.js"></script>
<script src="../../assets/js/bootstrap.bundle.min.js"></script>
<script>
$(document).ready(function() {
    $('form').submit(function(e) {
        const fotoInput = $('#foto')[0];
        if (fotoInput.files.length > 0) {
            const fileSize = fotoInput.files[0].size; // in bytes
            const maxSize = 200 * 1024; // 200KB
            
            if (fileSize > maxSize) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Ukuran foto maksimal 200KB'
                });
                e.preventDefault();
                return false;
            }
        }
    });
});
</script>
<?php include '../../includes/footer.php'; ?>