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

// Variabel untuk menampung pesan alert
$showAlert = false;
$alertType = '';
$alertTitle = '';
$alertText = '';

// Initialize all form fields with empty values
$formInput = [
    'kode_barang' => '',
    'nama_barang' => '',
    'deskripsi' => '',
    'merk' => '',
    'type' => '',
    'ukuran' => '',
    'bahan' => '',
    'jumlah' => 1,
    'tahun_pembelian' => date('Y'),
    'kondisi' => 'Baik',
    'keterangan' => '',
    'id_lokasi' => '',
    'id_jenis' => '',
    'id_asal' => '',
    'foto' => ''
];

// 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'];
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and store all form inputs
    $formInput['kode_barang'] = mysqli_real_escape_string($conn, $_POST['kode_barang'] ?? '');
    $formInput['nama_barang'] = mysqli_real_escape_string($conn, $_POST['nama_barang'] ?? '');
    $formInput['deskripsi'] = mysqli_real_escape_string($conn, $_POST['deskripsi'] ?? '');
    $formInput['merk'] = mysqli_real_escape_string($conn, $_POST['merk'] ?? '');
    $formInput['type'] = mysqli_real_escape_string($conn, $_POST['type'] ?? '');
    $formInput['ukuran'] = mysqli_real_escape_string($conn, $_POST['ukuran'] ?? '');
    $formInput['bahan'] = mysqli_real_escape_string($conn, $_POST['bahan'] ?? '');
    $formInput['jumlah'] = intval($_POST['jumlah'] ?? 1);
    $formInput['tahun_pembelian'] = intval($_POST['tahun_pembelian'] ?? date('Y'));
    $formInput['kondisi'] = mysqli_real_escape_string($conn, $_POST['kondisi'] ?? 'Baik');
    $formInput['keterangan'] = mysqli_real_escape_string($conn, $_POST['keterangan'] ?? '');
    $formInput['id_lokasi'] = intval($_POST['id_lokasi'] ?? 0);
    $formInput['id_jenis'] = intval($_POST['id_jenis'] ?? 0);
    $formInput['id_asal'] = !empty($_POST['id_asal']) ? intval($_POST['id_asal']) : NULL;

    // Cek apakah kode barang sudah ada
    $check_query = "SELECT id_barang FROM pdta_inventaris_barang WHERE kode_barang = '{$formInput['kode_barang']}' LIMIT 1";
    $check_result = mysqli_query($conn, $check_query);
    
    if (mysqli_num_rows($check_result) > 0) {
        $showAlert = true;
        $alertType = 'error';
        $alertTitle = 'Gagal';
        $alertText = 'Kode barang sudah ada dalam database';
    } else {
        // Upload foto
        $foto = '';
        if (isset($_FILES['foto']) && $_FILES['foto']['error'] == 0) {
            $allowed = ['jpg', 'jpeg', 'png'];
            $filename = $_FILES['foto']['name'];
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            
            if ($_FILES['foto']['size'] > 200000) {
                $showAlert = true;
                $alertType = 'error';
                $alertTitle = 'Gagal Upload';
                $alertText = 'Ukuran file terlalu besar. Maksimal 200KB';
            }
            elseif (!in_array(strtolower($ext), $allowed)) {
                $showAlert = true;
                $alertType = 'error';
                $alertTitle = 'Gagal Upload';
                $alertText = 'Format file tidak didukung. Gunakan JPG, JPEG, atau PNG';
            } else {
                // Generate filename
                $nama_singkat = '';
                if (!empty($formInput['nama_barang'])) {
                    $words = explode(' ', $formInput['nama_barang']);
                    foreach ($words as $word) {
                        if (!empty($word)) {
                            $nama_singkat .= strtolower(substr($word, 0, 1));
                        }
                    }
                }

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

                $new_filename = strtolower($kode_barang) . '_' . $nama_singkat . '.' . $ext;
                $upload_dir = '../../uploads/gambar/';
                
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }

                $upload_path = $upload_dir . $new_filename;

                if (move_uploaded_file($_FILES['foto']['tmp_name'], $upload_path)) {
                    $foto = $new_filename;
                } else {
                    $showAlert = true;
                    $alertType = 'error';
                    $alertTitle = 'Gagal Upload';
                    $alertText = 'Gagal menyimpan file gambar';
                }
            }
        } else {
            $showAlert = true;
            $alertType = 'error';
            $alertTitle = 'Peringatan';
            $alertText = 'Harap pilih file gambar';
        }

        // Jika tidak ada error, lanjutkan proses insert
        if (!$showAlert) {
            $query = "INSERT INTO pdta_inventaris_barang (
                kode_barang, nama_barang, deskripsi, merk, type, ukuran, bahan, jumlah, 
                tahun_pembelian, kondisi, keterangan, foto, id_lokasi, id_jenis, id_asal
            ) VALUES (
                '{$formInput['kode_barang']}', 
                '{$formInput['nama_barang']}', 
                '{$formInput['deskripsi']}', 
                '{$formInput['merk']}', 
                '{$formInput['type']}', 
                '{$formInput['ukuran']}', 
                '{$formInput['bahan']}', 
                {$formInput['jumlah']}, 
                {$formInput['tahun_pembelian']}, 
                '{$formInput['kondisi']}', 
                '{$formInput['keterangan']}', 
                '{$foto}', 
                {$formInput['id_lokasi']}, 
                {$formInput['id_jenis']}, 
                " . ($formInput['id_asal'] ? $formInput['id_asal'] : 'NULL') . "
            )";

            if (mysqli_query($conn, $query)) {
                $showAlert = true;
                $alertType = 'success';
                $alertTitle = 'Berhasil';
                $alertText = 'Data inventaris berhasil ditambahkan';
            } else {
                $showAlert = true;
                $alertType = 'error';
                $alertTitle = 'Gagal';
                $alertText = 'Terjadi kesalahan: ' . mysqli_error($conn);
                
                // Hapus file yang sudah diupload jika query gagal
                if (!empty($foto) && file_exists('../../uploads/gambar/' . $foto)) {
                    unlink('../../uploads/gambar/' . $foto);
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tambah 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>
        textarea::placeholder {
            font-style: italic;
            font-size: 0.875rem;
            color: #6c757d;
        }
        .input-keterangan::placeholder {
            font-style: italic;
            font-size: 0.875rem;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <?php if ($showAlert): ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                icon: '<?= $alertType ?>',
                title: '<?= $alertTitle ?>',
                text: '<?= $alertText ?>',
                showConfirmButton: false,
                timer: 1500
            }).then(() => {
                <?php if ($alertType == 'success'): ?>
                    window.location.href = 'index.php';
                <?php endif; ?>
            });
        });
    </script>
    <?php endif; ?>

    <div class="container mt-4">
        <div class="card">
            <div class="card-header text-white" style="background-color: #068496;">
                <h4><i class="bi bi-plus-circle"></i> Tambah Barang Inventaris</h4>
            </div>
            <div class="card-body">
                <form method="POST" action="" enctype="multipart/form-data" id="formBarang">
                    <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 ?>" <?= $formInput['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 ?>" <?= $formInput['id_jenis'] == $id ? 'selected' : '' ?>><?= htmlspecialchars($nama) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="kode_barang">Kode Barang <span class="text-danger">*</span></label>
                                <input type="text" class="form-control input-keterangan" id="kode_barang" name="kode_barang" placeholder="Isi dengan Kode Barang" value="<?= htmlspecialchars($formInput['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 input-keterangan" id="nama_barang" name="nama_barang" placeholder="Isi dengan nama barang" value="<?= htmlspecialchars($formInput['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($formInput['deskripsi']) ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="merk" class="form-label">Merk</label>
                                <input type="text" class="form-control input-keterangan" id="merk" name="merk" placeholder="Isi dengan merk barang" value="<?= htmlspecialchars($formInput['merk']) ?>">
                            </div>
                            <div class="mb-3">
                                <label for="type" class="form-label">Type</label>
                                <input type="text" class="form-control input-keterangan" id="type" name="type" placeholder="Isi dengan type barang" value="<?= htmlspecialchars($formInput['type']) ?>">
                            </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 input-keterangan" id="ukuran" name="ukuran" placeholder="Contoh: Kecil, Sedang, Besar" value="<?= htmlspecialchars($formInput['ukuran']) ?>">
                            </div>
                            <div class="mb-3">
                                <label for="bahan" class="form-label">Bahan</label>
                                <input type="text" class="form-control input-keterangan" id="bahan" name="bahan" placeholder="Contoh: Plastik, Kayu, Besi" value="<?= htmlspecialchars($formInput['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" min="1" value="<?= htmlspecialchars($formInput['jumlah']) ?>" 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" min="2000" max="<?= date('Y') ?>" value="<?= htmlspecialchars($formInput['tahun_pembelian']) ?>" required>
                            </div>
                            <div class="mb-3">
                                <label for="id_asal" class="form-label">Asal Perolehan<span class="text-danger">*</span></label>
                                <select class="form-select" id="id_asal" name="id_asal" required>
                                    <option value="">Pilih Asal Usul</option>
                                    <?php foreach ($asal_options as $id => $nama): ?>
                                        <option value="<?= $id ?>" <?= $formInput['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" <?= $formInput['kondisi'] == 'Baik' ? 'selected' : '' ?>>Baik</option>
                                    <option value="Rusak Ringan" <?= $formInput['kondisi'] == 'Rusak Ringan' ? 'selected' : '' ?>>Rusak Ringan</option>
                                    <option value="Rusak Berat" <?= $formInput['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($formInput['keterangan']) ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="foto" class="form-label">Foto Barang (max 200KB) <span class="text-danger">*</span></label>
                                <input type="file" class="form-control" id="foto" name="foto" accept=".jpg,.jpeg,.png" required>
                                <small class="text-muted">Pastikan ukuran file tidak lebih dari 200KB</small>
                            </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
                        </button>
                    </div>
                </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 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 = '';
                }
            }
        });
    </script>
</body>
</html>