<?php
session_start();

// Security check
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: ../../index.html?error=session");
    exit;
}

require_once __DIR__ . '/../DataBase/koneksi.php';

// Generate CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Fetch data untuk dropdown
$sql_kantor = "SELECT id, kode_kantor, nama_kantor FROM ref_kantor ORDER BY nama_kantor";
$result_kantor = $conn->query($sql_kantor);

$sql_kategori = "SELECT id, kode_kategori, nomor_kategori, nama_kategori FROM ref_kategori ORDER BY nomor_kategori";
$result_kategori = $conn->query($sql_kategori);

$sql_sumber = "SELECT id, kode_sumber, nomor_sumber, nama_sumber FROM ref_sumber_dana ORDER BY nomor_sumber";
$result_sumber = $conn->query($sql_sumber);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF validation
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $error = "Token keamanan tidak valid!";
    } else {
        // Get form data
        $id_kantor = intval($_POST['id_kantor']);
        $id_kategori = intval($_POST['id_kategori']);
        $id_jenis_asset = intval($_POST['id_jenis_asset']);
        $id_sumber_dana = intval($_POST['id_sumber_dana']);
        $jenis_barang = trim($_POST['jenis_barang']);
        $merk = trim($_POST['merk']);
        $no_seri = trim($_POST['no_seri']);
        $tahun_perolehan = intval($_POST['tahun_perolehan']);
        $harga_perolehan = floatval($_POST['harga_perolehan']);
        $kondisi = $_POST['kondisi'];
        $status = $_POST['status'];
        
        // Generate kode aset otomatis
        $stmt = $conn->prepare("CALL generate_kode_aset(?, ?, ?, ?, @kode_aset)");
        $stmt->bind_param("iiii", $id_kantor, $id_kategori, $id_jenis_asset, $id_sumber_dana);
        $stmt->execute();
        $stmt->close();
        
        // Get generated kode
        $result = $conn->query("SELECT @kode_aset AS kode");
        $row = $result->fetch_assoc();
        $kode_aset_auto = $row['kode'];
        
        // Get prefix huruf dan nomor urut
        $stmt2 = $conn->prepare("SELECT prefix_huruf FROM ref_jenis_asset WHERE id = ?");
        $stmt2->bind_param("i", $id_jenis_asset);
        $stmt2->execute();
        $result2 = $stmt2->get_result();
        $row2 = $result2->fetch_assoc();
        $prefix_huruf = $row2['prefix_huruf'];
        $stmt2->close();
        
        // Hitung nomor urut
        $stmt3 = $conn->prepare("SELECT COALESCE(MAX(nomor_urut), 0) + 1 AS urut FROM inventory WHERE id_kantor = ? AND id_kategori = ? AND prefix_huruf = ?");
        $stmt3->bind_param("iis", $id_kantor, $id_kategori, $prefix_huruf);
        $stmt3->execute();
        $result3 = $stmt3->get_result();
        $row3 = $result3->fetch_assoc();
        $nomor_urut = $row3['urut'];
        $stmt3->close();
        
        // Insert ke database
        $sql_insert = "INSERT INTO inventory (
            kode_aset, kode_aset_auto, jenis_barang, merk, no_seri, 
            tahun_perolehan, harga_perolehan, kondisi, status, kantor,
            id_kantor, id_kategori, id_jenis_asset, id_sumber_dana, 
            prefix_huruf, nomor_urut
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 
            (SELECT nama_kantor FROM ref_kantor WHERE id = ?),
            ?, ?, ?, ?, ?, ?)";
        
        $stmt_insert = $conn->prepare($sql_insert);
        $stmt_insert->bind_param(
            "sssssissiiiiiisi",
            $kode_aset_auto, $kode_aset_auto, $jenis_barang, $merk, $no_seri,
            $tahun_perolehan, $harga_perolehan, $kondisi, $status,
            $id_kantor, $id_kantor, $id_kategori, $id_jenis_asset, 
            $id_sumber_dana, $prefix_huruf, $nomor_urut
        );
        
        if ($stmt_insert->execute()) {
            $success = "✅ Asset berhasil ditambahkan dengan kode: <strong>$kode_aset_auto</strong>";
            $new_id = $conn->insert_id;
        } else {
            $error = "❌ Gagal menambahkan asset: " . $conn->error;
        }
        $stmt_insert->close();
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tambah Inventory - ACF Edu Hub</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Segoe UI', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            padding: 35px;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        }
        
        .header {
            border-bottom: 3px solid #8B4789;
            padding-bottom: 20px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h2 {
            color: #1e293b;
            font-size: 28px;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .btn-back {
            background: #64748b;
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-back:hover {
            background: #475569;
            transform: translateY(-2px);
        }
        
        .alert {
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 600;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
            border-left: 4px solid #22c55e;
        }
        
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }
        
        .kode-preview {
            background: #f8fafc;
            padding: 20px;
            border-radius: 10px;
            border: 2px dashed #8B4789;
            margin-bottom: 25px;
            text-align: center;
        }
        
        .kode-preview label {
            font-size: 13px;
            color: #64748b;
            font-weight: 600;
            display: block;
            margin-bottom: 8px;
        }
        
        .kode-preview .kode {
            font-family: 'Courier New', monospace;
            font-size: 32px;
            font-weight: 900;
            color: #8B4789;
            letter-spacing: 2px;
        }
        
        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin-bottom: 25px;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        .form-group.full-width {
            grid-column: 1 / -1;
        }
        
        .form-group label {
            font-weight: 600;
            color: #334155;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .form-group label .required {
            color: #ef4444;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            padding: 12px 15px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;
            font-family: 'Segoe UI', sans-serif;
        }
        
        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #8B4789;
            box-shadow: 0 0 0 3px rgba(139, 71, 137, 0.1);
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }
        
        .form-actions {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 2px solid #f1f5f9;
        }
        
        .btn {
            padding: 13px 28px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            font-size: 15px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: #8B4789;
            color: white;
        }
        
        .btn-primary:hover {
            background: #6d3669;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(139, 71, 137, 0.3);
        }
        
        .btn-secondary {
            background: #e2e8f0;
            color: #475569;
        }
        
        .btn-secondary:hover {
            background: #cbd5e1;
        }
        
        .info-box {
            background: #eff6ff;
            border-left: 4px solid #3b82f6;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 25px;
            font-size: 13px;
            color: #1e40af;
            line-height: 1.6;
        }
        
        @media (max-width: 768px) {
            .form-grid {
                grid-template-columns: 1fr;
            }
            
            .header {
                flex-direction: column;
                gap: 15px;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <h2>
            <i class="fas fa-plus-circle"></i>
            Tambah Asset Baru
        </h2>
        <a href="inventory_list_staff.php" class="btn-back">
            <i class="fas fa-arrow-left"></i> Kembali
        </a>
    </div>
    
    <?php if (isset($success)): ?>
    <div class="alert alert-success">
        <i class="fas fa-check-circle" style="font-size: 20px;"></i>
        <div><?= $success ?></div>
    </div>
    <?php endif; ?>
    
    <?php if (isset($error)): ?>
    <div class="alert alert-error">
        <i class="fas fa-exclamation-circle" style="font-size: 20px;"></i>
        <div><?= $error ?></div>
    </div>
    <?php endif; ?>
    
    <div class="info-box">
        <strong><i class="fas fa-info-circle"></i> Format Kode Asset:</strong><br>
        [KODE_KANTOR].[NO_KATEGORI].[PREFIX+NO_URUT].[NO_SUMBER]<br>
        Contoh: <strong>PST.01.A01.01</strong> = Pusat, Elektronik, Asset A urut ke-1, Hibah
    </div>
    
    <div class="kode-preview" id="kodePreview" style="display: none;">
        <label>Preview Kode Asset:</label>
        <div class="kode" id="kodeDisplay">---</div>
    </div>
    
    <form method="POST" action="" id="formInventory">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
        
        <div class="form-grid">
            <div class="form-group">
                <label>
                    <i class="fas fa-building"></i>
                    Kantor <span class="required">*</span>
                </label>
                <select name="id_kantor" id="id_kantor" required onchange="updatePreview()">
                    <option value="">-- Pilih Kantor --</option>
                    <?php while($kantor = $result_kantor->fetch_assoc()): ?>
                    <option value="<?= $kantor['id'] ?>" data-kode="<?= $kantor['kode_kantor'] ?>">
                        <?= htmlspecialchars($kantor['kode_kantor']) ?> - <?= htmlspecialchars($kantor['nama_kantor']) ?>
                    </option>
                    <?php endwhile; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label>
                    <i class="fas fa-folder"></i>
                    Kategori <span class="required">*</span>
                </label>
                <select name="id_kategori" id="id_kategori" required onchange="loadJenisAsset(); updatePreview();">
                    <option value="">-- Pilih Kategori --</option>
                    <?php while($kategori = $result_kategori->fetch_assoc()): ?>
                    <option value="<?= $kategori['id'] ?>" data-nomor="<?= $kategori['nomor_kategori'] ?>">
                        <?= htmlspecialchars($kategori['kode_kategori']) ?> - <?= htmlspecialchars($kategori['nama_kategori']) ?>
                    </option>
                    <?php endwhile; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label>
                    <i class="fas fa-box"></i>
                    Jenis Asset <span class="required">*</span>
                </label>
                <select name="id_jenis_asset" id="id_jenis_asset" required onchange="updatePreview()">
                    <option value="">-- Pilih Kategori Dulu --</option>
                </select>
            </div>
            
            <div class="form-group">
                <label>
                    <i class="fas fa-hand-holding-usd"></i>
                    Sumber Dana <span class="required">*</span>
                </label>
                <select name="id_sumber_dana" id="id_sumber_dana" required onchange="updatePreview()">
                    <option value="">-- Pilih Sumber Dana --</option>
                    <?php while($sumber = $result_sumber->fetch_assoc()): ?>
                    <option value="<?= $sumber['id'] ?>" data-nomor="<?= $sumber['nomor_sumber'] ?>">
                        <?= htmlspecialchars($sumber['kode_sumber']) ?> - <?= htmlspecialchars($sumber['nama_sumber']) ?>
                    </option>
                    <?php endwhile; ?>
                </select>
            </div>
            
            <div class="form-group full-width">
                <label>
                    <i class="fas fa-tag"></i>
                    Nama Barang <span class="required">*</span>
                </label>
                <input type="text" name="jenis_barang" placeholder="Contoh: Laptop Asus ROG" required>
            </div>
            
            <div class="form-group">
                <label>
                    <i class="fas fa-trademark"></i>
                    Merk
                </label>
                <input type="text" name="merk" placeholder="Contoh: ASUS">
            </div>
            
            <div class="form-group">
                <label>
                    <i class="fas fa-barcode"></i>
                    No. Seri
                </label>
                <input type="text" name="no_seri" placeholder="Contoh: XYZ123456">
            </div>
            
            <div class="form-group">
                <label>
                    <i class="fas fa-calendar"></i>
                    Tahun Perolehan <span class="required">*</span>
                </label>
                <input type="number" name="tahun_perolehan" min="2000" max="2100" value="<?= date('Y') ?>" required>
            </div>
            
            <div class="form-group">
                <label>
                    <i class="fas fa-money-bill-wave"></i>
                    Harga Perolehan <span class="required">*</span>
                </label>
                <input type="number" name="harga_perolehan" step="0.01" placeholder="0" required>
            </div>
            
            <div class="form-group">
                <label>
                    <i class="fas fa-tools"></i>
                    Kondisi <span class="required">*</span>
                </label>
                <select 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="form-group">
                <label>
                    <i class="fas fa-info-circle"></i>
                    Status <span class="required">*</span>
                </label>
                <select name="status" required>
                    <option value="aktif">Aktif</option>
                    <option value="nonaktif">Non-Aktif</option>
                </select>
            </div>
        </div>
        
        <div class="form-actions">
            <button type="reset" class="btn btn-secondary">
                <i class="fas fa-undo"></i> Reset
            </button>
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-save"></i> Simpan Asset
            </button>
        </div>
    </form>
</div>

<script>
// Load jenis asset based on kategori
function loadJenisAsset() {
    const kategoriId = document.getElementById('id_kategori').value;
    const jenisSelect = document.getElementById('id_jenis_asset');
    
    jenisSelect.innerHTML = '<option value="">-- Loading... --</option>';
    
    if (!kategoriId) {
        jenisSelect.innerHTML = '<option value="">-- Pilih Kategori Dulu --</option>';
        return;
    }
    
    fetch(`get_jenis_asset.php?kategori_id=${kategoriId}`)
        .then(response => response.json())
        .then(data => {
            jenisSelect.innerHTML = '<option value="">-- Pilih Jenis Asset --</option>';
            data.forEach(item => {
                const option = document.createElement('option');
                option.value = item.id;
                option.setAttribute('data-prefix', item.prefix_huruf);
                option.textContent = `${item.kode_jenis} - ${item.nama_jenis} (${item.prefix_huruf})`;
                jenisSelect.appendChild(option);
            });
        })
        .catch(error => {
            console.error('Error:', error);
            jenisSelect.innerHTML = '<option value="">-- Error Loading Data --</option>';
        });
}

// Update kode preview
function updatePreview() {
    const kantor = document.getElementById('id_kantor');
    const kategori = document.getElementById('id_kategori');
    const jenis = document.getElementById('id_jenis_asset');
    const sumber = document.getElementById('id_sumber_dana');
    
    if (kantor.value && kategori.value && jenis.value && sumber.value) {
        const kodeKantor = kantor.options[kantor.selectedIndex].getAttribute('data-kode');
        const noKategori = kategori.options[kategori.selectedIndex].getAttribute('data-nomor');
        const prefix = jenis.options[jenis.selectedIndex].getAttribute('data-prefix');
        const noSumber = sumber.options[sumber.selectedIndex].getAttribute('data-nomor');
        
        const kodePreview = `${kodeKantor}.${noKategori}.${prefix}XX.${noSumber}`;
        
        document.getElementById('kodeDisplay').textContent = kodePreview;
        document.getElementById('kodePreview').style.display = 'block';
    } else {
        document.getElementById('kodePreview').style.display = 'none';
    }
}

// Form validation
document.getElementById('formInventory').addEventListener('submit', function(e) {
    const required = this.querySelectorAll('[required]');
    let valid = true;
    
    required.forEach(field => {
        if (!field.value) {
            valid = false;
            field.style.borderColor = '#ef4444';
        } else {
            field.style.borderColor = '#e2e8f0';
        }
    });
    
    if (!valid) {
        e.preventDefault();
        alert('⚠️ Mohon lengkapi semua field yang wajib diisi!');
    }
});
</script>

</body>
</html>

<?php
$conn->close();
?>