<?php
session_start();

if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'A') {
    header("Location: ../index.html?error=unauthorized");
    exit;
}

require_once '../database/koneksi.php';

$action = $_GET['action'] ?? 'add';
$id = $_GET['id'] ?? 0;
$data = null;

if ($action === 'edit' && $id > 0) {
    $sql = "SELECT * FROM inventory WHERE id = ?";
    $stmt = $koneksi->prepare($sql);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
}

$pageTitle = $action === 'edit' ? 'Edit Inventory' : 'Tambah Inventory';
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            background: #f7fafc;
            padding: 30px;
        }
        
        .form-container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .form-header {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .form-title {
            font-size: 24px;
            color: #2d3748;
            margin-bottom: 8px;
        }
        
        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group.full-width {
            grid-column: 1 / -1;
        }
        
        label {
            display: block;
            font-size: 14px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 8px;
        }
        
        .required {
            color: #e53e3e;
        }
        
        input, select, textarea {
            width: 100%;
            padding: 12px 14px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;
            box-sizing: border-box;
        }
        
        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #667eea;
        }
        
        textarea {
            resize: vertical;
            min-height: 100px;
        }
        
        .btn-group {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e2e8f0;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }
        
        .btn-secondary {
            background: #e2e8f0;
            color: #4a5568;
        }
        
        .btn-secondary:hover {
            background: #cbd5e0;
        }
    </style>
</head>
<body>
    <div class="form-container">
        <div class="form-header">
            <h1 class="form-title"><?php echo $pageTitle; ?></h1>
            <p style="color: #718096; font-size: 14px;">Lengkapi formulir di bawah ini</p>
        </div>
        
        <div class="form-grid">
            <input type="hidden" id="formAction" value="<?php echo $action; ?>">
            <input type="hidden" id="formId" value="<?php echo $id; ?>">
            
            <!-- ROW 1: Tanggal & Kategori -->
            <div class="form-group">
                <label>Tanggal Perolehan <span class="required">*</span></label>
                <input type="date" id="tanggal_perolehan" 
                       value="<?php echo $data['tanggal_perolehan'] ?? ''; ?>" required>
            </div>
            
            <div class="form-group">
                <label>Kategori <span class="required">*</span></label>
                <select id="kategori" required>
                    <option value="" disabled <?php echo empty($data['kategori']) ? 'selected' : ''; ?>>-- Pilih Kategori --</option>
                    <option value="Peralatan" <?php echo ($data['kategori'] ?? '') === 'Peralatan' ? 'selected' : ''; ?>>Peralatan</option>
                    <option value="Kendaraan" <?php echo ($data['kategori'] ?? '') === 'Kendaraan' ? 'selected' : ''; ?>>Kendaraan</option>
                </select>
            </div>

            <!-- ROW 2: Sumber Dana & Kantor -->
            <div class="form-group">
                <label>Sumber Dana <span class="required">*</span></label>
                <input type="text" id="sumber_dana" 
                       value="<?php echo htmlspecialchars($data['sumber_dana'] ?? ''); ?>"
                       placeholder="Contoh: BOS, SE, Operasional" required>
            </div>
            
            <div class="form-group">
                <label>Kantor <span class="required">*</span></label>
                <input type="text" id="kantor" 
                       value="<?php echo htmlspecialchars($data['kantor'] ?? ''); ?>"
                       placeholder="Contoh: Pusat, SDJ Medan" required>
            </div>

            <!-- ROW 3: Jenis Barang & Merk (TAMBAHAN) -->
            <div class="form-group">
                <label>Jenis Barang <span class="required">*</span></label>
                <input type="text" id="jenis_barang" 
                       value="<?php echo htmlspecialchars($data['jenis_barang'] ?? ''); ?>"
                       placeholder="Contoh: Laptop, Printer, AC" required>
            </div>
            
            <!-- FIELD BARU: Merk — ini yang hilang dan bikin nama kosong -->
            <div class="form-group">
                <label>Merk</label>
                <input type="text" id="merk" 
                       value="<?php echo htmlspecialchars($data['merk'] ?? ''); ?>"
                       placeholder="Contoh: Lenovo, Epson, Samsung">
            </div>

            <!-- ROW 4: Harga Perolehan & Kondisi -->
            <div class="form-group">
                <label>Harga Perolehan <span class="required">*</span></label>
                <input type="number" id="harga_perolehan" 
                       value="<?php echo $data['harga_perolehan'] ?? '0'; ?>"
                       placeholder="0" min="0" required>
            </div>

            <div class="form-group">
                <label>Kondisi</label>
                <select id="kondisi">
                    <option value="" disabled <?php echo empty($data['kondisi']) ? 'selected' : ''; ?>>-- Pilih Kondisi --</option>
                    <option value="Baik" <?php echo ($data['kondisi'] ?? '') === 'Baik' ? 'selected' : ''; ?>>Baik</option>
                    <option value="Rusak" <?php echo ($data['kondisi'] ?? '') === 'Rusak' ? 'selected' : ''; ?>>Rusak</option>
                    <option value="Sedang" <?php echo ($data['kondisi'] ?? '') === 'Sedang' ? 'selected' : ''; ?>>Sedang</option>
                </select>
            </div>

            <!-- ROW 5: Spesifikasi (TAMBAHAN) -->
            <!-- FIELD BARU: Spesifikasi — ada di tabel tapi tidak diisi dari form -->
            <div class="form-group full-width">
                <label>Spesifikasi</label>
                <textarea id="spesifikasi" placeholder="Contoh: Processor: Intel Core i3, RAM: 8GB, Storage: SSD 256GB..."><?php echo htmlspecialchars($data['spesifikasi'] ?? ''); ?></textarea>
            </div>

            <!-- ROW 6: Jenis Inventory / Deskripsi -->
            <div class="form-group full-width">
                <label>Jenis Inventory (Deskripsi) <span class="required">*</span></label>
                <textarea id="jenis_inventory" required placeholder="Masukkan deskripsi lengkap inventory..."><?php echo htmlspecialchars($data['jenis_inventory'] ?? ''); ?></textarea>
            </div>
        </div>
        
        <div class="btn-group">
            <button type="button" class="btn btn-secondary" onclick="window.location.href='inventory_list.php'">
                <i class="fas fa-times"></i> Batal
            </button>
            <button type="button" class="btn btn-primary" onclick="submitForm()">
                <i class="fas fa-save"></i> <?php echo $action === 'edit' ? 'Update' : 'Simpan'; ?>
            </button>
        </div>
    </div>
    
    <script>
        function submitForm() {
            const action = document.getElementById('formAction').value;
            const id = document.getElementById('formId').value;
            
            const formData = new FormData();
            formData.append('tanggal_perolehan', document.getElementById('tanggal_perolehan').value);
            formData.append('kategori', document.getElementById('kategori').value);
            formData.append('sumber_dana', document.getElementById('sumber_dana').value);
            formData.append('kantor', document.getElementById('kantor').value);
            formData.append('jenis_barang', document.getElementById('jenis_barang').value);
            formData.append('merk', document.getElementById('merk').value);                         // TAMBAHAN
            formData.append('harga_perolehan', document.getElementById('harga_perolehan').value);
            formData.append('spesifikasi', document.getElementById('spesifikasi').value);           // TAMBAHAN
            formData.append('jenis_inventory', document.getElementById('jenis_inventory').value);

            // Kondisi hanya kirim kalau dipilih
            const kondisi = document.getElementById('kondisi').value;
            if (kondisi) {
                formData.append('kondisi', kondisi);
            }
            
            if (action === 'edit') {
                formData.append('id', id);
            }
            
            const url = action === 'edit' ? '../api/update_inventory.php' : '../api/add_inventory.php';
            
            fetch(url, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    window.location.href = 'inventory_list.php';
                } else {
                    alert(data.message || 'Terjadi kesalahan');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Terjadi kesalahan saat menyimpan data');
            });
        }
    </script>
</body>
</html>