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

// Set batas upload
ini_set('post_max_size', '210K');
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 (sesuaikan dengan form baru)
    $required = [
        'id_lokasi', 'id_jenis', 'kode_barang', 'nama_barang', 
        'jumlah', 'tahun_pembelian', 'kondisi', 'id_asal'
    ];
    
    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
    $data = [
        'kode_barang' => $_POST['kode_barang'],
        'nama_barang' => $_POST['nama_barang'],
        'deskripsi' => $_POST['deskripsi'] ?? null,
        'merk' => $_POST['merk'] ?? null,
        'type' => $_POST['type'] ?? null,
        'ukuran' => $_POST['ukuran'] ?? null,
        'bahan' => $_POST['bahan'] ?? null,
        'jumlah' => (int)$_POST['jumlah'],
        'tahun_pembelian' => (int)$_POST['tahun_pembelian'],
        'kondisi' => $_POST['kondisi'],
        'keterangan' => $_POST['keterangan'] ?? null,
        'id_lokasi' => (int)$_POST['id_lokasi'],
        'id_jenis' => (int)$_POST['id_jenis'],
        'id_asal' => (int)$_POST['id_asal']
    ];

    // Handle file upload
    $foto = null;
    if (isset($_FILES['foto']) && $_FILES['foto']['error'] !== UPLOAD_ERR_NO_FILE) {
        $file = $_FILES['foto'];
        
        // Validasi ukuran file
        if ($file['size'] > 200 * 1024) {
            $fileSizeKB = round($file['size'] / 1024, 2);
            $_SESSION['error'] = "Ukuran foto ($fileSizeKB KB) melebihi batas maksimal 200KB";
            header("Location: tambah.php");
            exit();
        }
        
        // Validasi tipe file
        $allowed = ['image/jpeg', 'image/png', 'image/gif'];
        $mime = mime_content_type($file['tmp_name']);
        
        if (!in_array($mime, $allowed)) {
            $_SESSION['error'] = "Hanya file JPG, PNG, atau GIF yang diperbolehkan";
            header("Location: tambah.php");
            exit();
        }
        
        // Generate nama unik
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $foto = uniqid().'.'.$ext;
        
        if (!move_uploaded_file($file['tmp_name'], '../../uploads/'.$foto)) {
            $_SESSION['error'] = "Gagal menyimpan file foto";
            header("Location: tambah.php");
            exit();
        }
        
        $data['foto'] = $foto;
    } else {
        $_SESSION['error'] = "Foto barang harus diupload";
        header("Location: tambah.php");
        exit();
    }

    // Check duplicate kode barang
    $check = $conn->prepare("SELECT id_barang FROM pdta_inventaris_barang WHERE kode_barang = ?");
    $check->bind_param("s", $data['kode_barang']);
    $check->execute();
    
    if ($check->get_result()->num_rows > 0) {
        if (isset($foto)) unlink('../../uploads/'.$foto);
        $_SESSION['error'] = "Kode barang sudah digunakan";
        header("Location: tambah.php");
        exit();
    }

    // Prepare and execute query
    $columns = implode(',', array_keys($data));
    $placeholders = implode(',', array_fill(0, count($data), '?'));
    $types = str_repeat('s', count($data));
    
    $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 {
        if (isset($foto)) unlink('../../uploads/'.$foto);
        $_SESSION['error'] = "Gagal menyimpan: ".$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">
            <?php if (isset($_SESSION['error'])): ?>
                <div class="alert alert-danger"><?= $_SESSION['error']; unset($_SESSION['error']); ?></div>
            <?php endif; ?>
            
            <form method="POST" enctype="multipart/form-data" id="formBarang">
                <div class="row">
                    <div class="col-md-6">
                        <!-- Lokasi -->
                        <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>
                        
                        <!-- Jenis Barang -->
                        <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>
                        
                        <!-- Kode Barang -->
                        <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>
                        
                        <!-- Nama Barang -->
                        <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>
                        
                        <!-- Deskripsi -->
                        <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>
                    
                    <div class="col-md-6">
                        <!-- Merk -->
                        <div class="mb-3">
                            <label for="merk" class="form-label">Merk</label>
                            <input type="text" class="form-control" id="merk" name="merk">
                        </div>
                        
                        <!-- Type -->
                        <div class="mb-3">
                            <label for="type" class="form-label">Type</label>
                            <input type="text" class="form-control" id="type" name="type">
                        </div>
                        
                        <!-- Ukuran -->
                        <div class="mb-3">
                            <label for="ukuran" class="form-label">Ukuran</label>
                            <input type="text" class="form-control" id="ukuran" name="ukuran">
                        </div>
                        
                        <!-- Bahan -->
                        <div class="mb-3">
                            <label for="bahan" class="form-label">Bahan</label>
                            <input type="text" class="form-control" id="bahan" name="bahan">
                        </div>
                        
                        <!-- Jumlah -->
                        <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>
                        
                        <!-- Tahun Pembelian -->
                        <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="1900" max="<?= date('Y') ?>" required>
                        </div>
                        
                        <!-- Asal Usul -->
                        <div class="mb-3">
                            <label for="id_asal" class="form-label">Asal Usul <span class="text-danger">*</span></label>
                            <select class="form-select" id="id_asal" name="id_asal" required>
                                <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>
                        
                        <!-- Kondisi -->
                        <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>
                        
                        <!-- Keterangan -->
                        <div class="mb-3">
                            <label for="keterangan" class="form-label">Keterangan</label>
                            <textarea class="form-control" id="keterangan" name="keterangan" rows="2"></textarea>
                        </div>
                        
                        <!-- Foto Barang -->
                        <div class="mb-3">
                            <label for="foto" class="form-label">Foto Barang <span class="text-danger">*</span></label>
                            <input type="file" class="form-control" id="foto" name="foto" 
                                   accept="image/jpeg,image/png,image/gif" required>
                            <small class="text-muted">Maksimal 200KB (Format: JPG, PNG, GIF)</small>
                            <div class="invalid-feedback" id="fotoError"></div>
                        </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>
<script>
$(document).ready(function() {
    // Validasi ukuran file sebelum upload
    $('#foto').on('change', function() {
        const file = this.files[0];
        const maxSize = 200 * 1024; // 200KB
        const fotoError = $('#fotoError');
        
        if (file) {
            if (file.size > maxSize) {
                fotoError.text('Ukuran file melebihi 200KB');
                $(this).addClass('is-invalid');
                this.value = ''; // Clear input
            } else {
                $(this).removeClass('is-invalid');
                fotoError.text('');
            }
        }
    });
    
    // Validasi form sebelum submit
    $('#formBarang').on('submit', function(e) {
        const fileInput = $('#foto')[0];
        if (fileInput.files.length > 0) {
            const file = fileInput.files[0];
            if (file.size > 200 * 1024) {
                e.preventDefault();
                alert('Ukuran file foto melebihi batas 200KB');
                return false;
            }
        }
        return true;
    });
});
</script>

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