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

// Set batas upload maksimal 200KB
ini_set('post_max_size', '210K'); // Sedikit lebih besar dari 200KB untuk buffer
ini_set('upload_max_filesize', '200K');

// 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') {
    // Validasi field required
    $required = ['kode_barang', 'nama_barang', 'jumlah', 'kondisi', 'id_lokasi', 'id_jenis'];
    foreach ($required as $field) {
        if (empty($_POST[$field])) {
            $_SESSION['error'] = "Field " . ucfirst(str_replace('_', ' ', $field)) . " harus diisi";
            header("Location: tambah.php");
            exit();
        }
    }

    // Collect all form data dengan null coalescing operator
    $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' => (int)($_POST['jumlah'] ?? 0),
        'tahun_pembelian' => !empty($_POST['tahun_pembelian']) ? (int)$_POST['tahun_pembelian'] : null,
        'kondisi' => $_POST['kondisi'] ?? 'Baik',
        'keterangan' => $_POST['keterangan'] ?? '',
        'id_lokasi' => (int)($_POST['id_lokasi'] ?? 0),
        'id_jenis' => (int)($_POST['id_jenis'] ?? 0),
        'id_asal' => !empty($_POST['id_asal']) ? (int)$_POST['id_asal'] : null
    ];

    // Handle file upload
    $foto = null;
    if (isset($_FILES['foto']) && $_FILES['foto']['error'] !== UPLOAD_ERR_NO_FILE) {
        $file = $_FILES['foto'];
        
        // Validasi ukuran file (max 200KB)
        if ($file['size'] > 200 * 1024) {
            $_SESSION['error'] = "Ukuran foto maksimal 200KB";
            header("Location: tambah.php");
            exit();
        }
        
        // Validasi tipe file (hanya gambar)
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        if (!in_array($file['type'], $allowed_types)) {
            $_SESSION['error'] = "Hanya file JPG, PNG, atau GIF yang diperbolehkan";
            header("Location: tambah.php");
            exit();
        }
        
        if ($file['error'] === UPLOAD_ERR_OK) {
            $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
    $check = $conn->prepare("SELECT id_barang FROM pdta_inventaris_barang WHERE kode_barang = ?");
    $check->bind_param("s", $data['kode_barang']);
    $check->execute();
    $check->store_result();
    
    if ($check->num_rows > 0) {
        $_SESSION['error'] = "Kode barang sudah digunakan";
        header("Location: tambah.php");
        exit();
    }

    // Prepare SQL query
    $columns = implode(', ', array_keys($data));
    $placeholders = implode(', ', array_fill(0, count($data), '?'));
    
    // Generate parameter types (s = string, i = integer)
    $types = '';
    foreach ($data as $value) {
        $types .= is_int($value) ? 'i' : 's';
    }
    
    $stmt = $conn->prepare("INSERT INTO pdta_inventaris_barang ($columns) VALUES ($placeholders)");
    $stmt->bind_param($types, ...array_values($data));
    
    if ($stmt->execute()) {
        $_SESSION['success'] = "Barang berhasil ditambahkan!";
        header("Location: index.php");
        exit();
    } else {
        // Delete uploaded file if there was an error
        if (isset($foto)) {
            unlink('../../uploads/' . $foto);
        }
        $_SESSION['error'] = "Gagal menambahkan barang: " . $conn->error;
        header("Location: tambah.php");
        exit();
    }
}
?>

<?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-plus-circle"></i> Tambah 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" 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" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="deskripsi" class="form-label">Deskripsi</label>
                            <textarea class="form-control" id="deskripsi" name="deskripsi" rows="2"></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">
                                </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">
                                </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">
                                </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">
                                </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" 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" 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">Baik</option>
                                <option value="Rusak Ringan">Rusak Ringan</option>
                                <option value="Rusak Berat">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"></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/*">
                        </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'] ?>"><?= 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'] ?>"><?= 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'] ?>"><?= 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
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="../../assets/js/jquery.min.js"></script>
<script src="../../assets/js/bootstrap.bundle.min.js"></script>

<?php include '../../includes/footer.php'; ?>