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



// Tangkap ID barang yang akan diedit
$id_barang = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Ambil data barang dari database beserta relasinya
$query = "SELECT b.*, l.nama_lokasi, j.nama_jenis, a.sumber_asal 
          FROM pdta_inventaris_barang b
          LEFT JOIN pdta_lokasi l ON b.id_lokasi = l.id_lokasi
          LEFT JOIN pdta_jenis_barang j ON b.id_jenis = j.id_jenis
          LEFT JOIN pdta_asal_usul a ON b.id_asal = a.id_asal
          WHERE b.id_barang = '$id_barang'";
$result = mysqli_query($conn, $query);
$barang = mysqli_fetch_assoc($result);

// Jika data tidak ditemukan, redirect ke halaman index
// if (!$barang) {
//     set_flash_message('error', 'Data barang tidak ditemukan');
//     header('Location: index.php');
//     exit();
// }

// Get options for dropdowns
$lokasi_options = [];
$jenis_options = [];
$asal_options = [];

$query_lokasi = "SELECT id_lokasi, nama_lokasi FROM pdta_lokasi ORDER BY nama_lokasi";
$result_lokasi = mysqli_query($conn, $query_lokasi);
while ($row = mysqli_fetch_assoc($result_lokasi)) {
    $lokasi_options[$row['id_lokasi']] = $row['nama_lokasi'];
}

$query_jenis = "SELECT id_jenis, nama_jenis FROM pdta_jenis_barang ORDER BY nama_jenis";
$result_jenis = mysqli_query($conn, $query_jenis);
while ($row = mysqli_fetch_assoc($result_jenis)) {
    $jenis_options[$row['id_jenis']] = $row['nama_jenis'];
}

$query_asal = "SELECT id_asal, sumber_asal FROM pdta_asal_usul ORDER BY sumber_asal";
$result_asal = mysqli_query($conn, $query_asal);
while ($row = mysqli_fetch_assoc($result_asal)) {
    $asal_options[$row['id_asal']] = $row['sumber_asal'];
}

// Proses form jika ada data yang dikirim
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Ambil data dari form
    $kode_barang = mysqli_real_escape_string($conn, $_POST['kode_barang']);
    $nama_barang = mysqli_real_escape_string($conn, $_POST['nama_barang']);
    $deskripsi = mysqli_real_escape_string($conn, $_POST['deskripsi']);
    $merk = mysqli_real_escape_string($conn, $_POST['merk']);
    $type = mysqli_real_escape_string($conn, $_POST['type']);
    $ukuran = mysqli_real_escape_string($conn, $_POST['ukuran']);
    $bahan = mysqli_real_escape_string($conn, $_POST['bahan']);
    $jumlah = intval($_POST['jumlah']);
    $tahun_pembelian = intval($_POST['tahun_pembelian']);
    $kondisi = mysqli_real_escape_string($conn, $_POST['kondisi']);
    $keterangan = mysqli_real_escape_string($conn, $_POST['keterangan']);
    $id_lokasi = intval($_POST['id_lokasi']);
    $id_jenis = intval($_POST['id_jenis']);
    $id_asal = !empty($_POST['id_asal']) ? intval($_POST['id_asal']) : NULL;
    
    // Handle upload gambar
    $foto = $barang['foto']; // Default ke foto lama
    
    if (!empty($_FILES['foto']['name'])) {
        $target_dir = "../../uploads/gambar/";
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0777, true);
        }
        
        $allowed = ['jpg', 'jpeg', 'png'];
        $filename = $_FILES['foto']['name'];
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        
        // Validasi file
        if ($_FILES['foto']['size'] > 200000) {
            set_flash_message('error', 'Ukuran file terlalu besar. Maksimal 200KB');
            header("Location: edit.php?id=$id_barang");
            exit();
        }
        
        if (!in_array(strtolower($ext), $allowed)) {
            set_flash_message('error', 'Format file tidak didukung. Gunakan JPG, JPEG, atau PNG');
            header("Location: edit.php?id=$id_barang");
            exit();
        }
        
        // Generate nama file baru
        $nama_singkat = '';
        if (!empty($nama_barang)) {
            $words = explode(' ', $nama_barang);
            foreach ($words as $word) {
                if (!empty($word)) {
                    $nama_singkat .= strtolower(substr($word, 0, 1));
                }
            }
        }

        $kode_barang_clean = preg_replace('/[^a-zA-Z0-9_-]/', '', $kode_barang);
        $nama_singkat = preg_replace('/[^a-zA-Z0-9]/', '', $nama_singkat);

        $new_filename = strtolower($kode_barang_clean) . '_' . $nama_singkat . '.' . $ext;
        $target_file = $target_dir . $new_filename;
        
        // Hapus foto lama jika ada
        if (!empty($barang['foto']) && file_exists($target_dir . $barang['foto'])) {
            unlink($target_dir . $barang['foto']);
        }
        
        // Upload file baru
        if (move_uploaded_file($_FILES['foto']['tmp_name'], $target_file)) {
            $foto = $new_filename;
        } else {
            set_flash_message('error', 'Gagal mengupload file gambar');
            header("Location: edit.php?id=$id_barang");
            exit();
        }
    }
    
    // Update data di database
    $query = "UPDATE pdta_inventaris_barang SET 
                kode_barang = '$kode_barang',
                nama_barang = '$nama_barang',
                deskripsi = '$deskripsi',
                merk = '$merk',
                type = '$type',
                ukuran = '$ukuran',
                bahan = '$bahan',
                jumlah = $jumlah,
                tahun_pembelian = $tahun_pembelian,
                kondisi = '$kondisi',
                keterangan = '$keterangan',
                foto = '$foto',
                id_lokasi = $id_lokasi,
                id_jenis = $id_jenis,
                id_asal = " . ($id_asal ? $id_asal : 'NULL') . "
              WHERE id_barang = $id_barang";
    
    if (mysqli_query($conn, $query)) {
        $_SESSION['success'] = "Data Barang berhasil diperbarui!";
        header('Location: index.php');
        exit();
    } else {
        $_SESSION['error'] = "Gagal memperbarui data barang: " . $conn->error;
        header("Location: edit.php?id=$id_barang");
        exit();
    }
    // if (mysqli_query($conn, $query)) {
    //     $_SESSION['alert'] = [
    //         'type' => 'success',
    //         'message' => 'Data barang berhasil diperbarui'
    //     ];
    //     header('Location: index.php');
    //     exit();
    // } else {
    //     $_SESSION['alert'] = [
    //         'type' => 'error',
    //         'message' => 'Gagal memperbarui data barang: ' . mysqli_error($conn)
    //     ];
    // }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Inventaris - DIPAN (DIGITAL PANDAI)</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/css/style.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        .img-preview {
            max-width: 200px;
            max-height: 200px;
            margin-top: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 5px;
        }
        textarea::placeholder {
            font-style: italic;
            font-size: 0.875rem;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <div class="card shadow">
            <div class="card-header text-white" style="background-color: #068496;">
                <h4><i class="bi bi-pencil-square"></i> Edit Data Inventaris</h4>
            </div>
            <div class="card-body">
                <?php display_flash_message(); ?>
                
                <form method="POST" action="" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-md-6">
                             <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 foreach ($lokasi_options as $id => $nama): ?>
                                        <option value="<?= $id ?>" <?= $barang['id_lokasi'] == $id ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($nama) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                             <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 Barang</option>
                                    <?php foreach ($jenis_options as $id => $nama): ?>
                                        <option value="<?= $id ?>" <?= $barang['id_jenis'] == $id ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($nama) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <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="6"
                                          placeholder="Isi dengan deskripsi barang"><?= htmlspecialchars($barang['deskripsi']) ?></textarea>
                            </div>
                            
                            <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 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 class="col-md-4">
                            <?php if (!empty($barang['foto'])) : ?>
                                    <div class="mt-2">
                                        <p>Foto Saat Ini:</p>
                                        <img src="../../uploads/gambar/<?= htmlspecialchars($barang['foto']) ?>" 
                                            alt="Foto Barang" class="img-preview" id="current-photo-preview" 
                                            onerror="this.src='../../assets/img/no-image.png'">
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <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 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 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 class="mb-3">
                                <label for="tahun_pembelian" class="form-label">Tahun Pembelian <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="tahun_pembelian" name="tahun_pembelian" 
                                       value="<?= htmlspecialchars($barang['tahun_pembelian']) ?>" min="2000" max="<?= date('Y') ?>" required>
                            </div>
                             <div class="mb-3">
                                <label for="id_asal" class="form-label">Asal Perolehan</label>
                                <select class="form-select" id="id_asal" name="id_asal">
                                    <option value="">Pilih Asal Usul</option>
                                    <?php foreach ($asal_options as $id => $nama): ?>
                                        <option value="<?= $id ?>" <?= $barang['id_asal'] == $id ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($nama) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </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"
                                          placeholder="Bisa diisi tempat / letak barang, peruntukan, atau saat ini dipinjam siapa, dll"><?= htmlspecialchars($barang['keterangan']) ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="foto" class="form-label">Foto Barang (max 200KB)</label>
                                <input type="file" class="form-control" id="foto" name="foto" accept=".jpg,.jpeg,.png">
                                <small class="text-muted">Biarkan kosong jika tidak ingin mengubah foto</small>
                                
                                <div class="mt-2">
                                    <p>Pratinjau Foto Baru:</p>
                                    <img src="#" alt="Pratinjau Foto" class="img-preview" id="photo-preview" style="display: none;">
                                </div>
                            </div>
                        </div>
                        
                        
                    </div>
                    
                    <div class="row">
                        
                        
                        <div class="col-md-4">
                           
                        </div>
                        
                        <div class="col-md-4">
                           
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12">
                            
                        </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="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Preview gambar sebelum upload
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                
                reader.onload = function(e) {
                    $('#photo-preview').attr('src', e.target.result);
                    $('#photo-preview').show();
                }
                
                reader.readAsDataURL(input.files[0]);
            }
        }
        
        $("#foto").change(function() {
            readURL(this);
        });
        
        // Validasi ukuran file sebelum upload
        document.getElementById('foto').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const fileSize = file.size / 1024; // dalam KB
                if (fileSize > 200) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Ukuran File Terlalu Besar',
                        text: 'Maksimal ukuran file 200KB',
                        showConfirmButton: false,
                        timer: 1500
                    });
                    e.target.value = '';
                    $('#photo-preview').hide();
                }
            }
        });
        
    </script>
</body>
</html>