<?php
session_start();

// 1. Proteksi Halaman - Cek Login
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: ../../index.html?error=unauthorized");
    exit;
}

// 2. Proteksi Role - Izinkan Staff (S), Admin (A), dan Manager (M)
$userRole = strtoupper(trim($_SESSION['role'] ?? ''));
$allowedRoles = ['S', 'A', 'M']; // Staff, Admin, dan Manager

if (!in_array($userRole, $allowedRoles)) {
    header("Location: ../../dashboard.php?error=access_denied");
    exit;
}

// 3. Tentukan halaman kembali berdasarkan role
if ($userRole === 'S') {
    $backUrl = '../staff/inventory_list_staff.php';
} else {
    $backUrl = '../inventory/inventory_list.php';
}

// 3. Koneksi Database - Coba beberapa path
$koneksiPath = '';
$possiblePaths = [
    __DIR__ . '/../../DataBase/koneksi.php',
    __DIR__ . '/../../database/koneksi.php',
    __DIR__ . '/../../db/koneksi.php',
    __DIR__ . '/../../config/koneksi.php'
];

foreach ($possiblePaths as $path) {
    if (file_exists($path)) {
        $koneksiPath = $path;
        break;
    }
}

if (empty($koneksiPath)) {
    die("ERROR: File koneksi.php tidak ditemukan di lokasi berikut:<br>" . 
        implode('<br>', $possiblePaths) . 
        "<br><br>Pastikan path ke database benar!");
}

require_once $koneksiPath;

// 4. Cek koneksi database
if (!isset($conn) || $conn->connect_error) {
    die("ERROR: Koneksi database gagal. Cek file koneksi.php Anda.");
}

$success = '';
$error = '';

// 5. Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $tanggal_perolehan = $_POST['tanggal_perolehan'] ?? '';
    $kategori = trim($_POST['kategori'] ?? '');
    $sumber_dana = trim($_POST['sumber_dana'] ?? '');
    $kantor = trim($_POST['kantor'] ?? '');
    $jenis_barang = trim($_POST['jenis_barang'] ?? '');
    $jenis_inventory = trim($_POST['jenis_inventory'] ?? '');
    $harga_perolehan = $_POST['harga_perolehan'] ?? 0;
    
    if (empty($tanggal_perolehan) || empty($kategori) || empty($jenis_barang) || empty($harga_perolehan)) {
        $error = "Data bertanda bintang (*) wajib diisi!";
    } else {
        try {
            $stmt = $conn->prepare("INSERT INTO inventory (tanggal_perolehan, kategori, sumber_dana, kantor, jenis_barang, jenis_inventory, harga_perolehan, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'aktif')");
            
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            
            $stmt->bind_param("ssssssd", $tanggal_perolehan, $kategori, $sumber_dana, $kantor, $jenis_barang, $jenis_inventory, $harga_perolehan);
            
            if ($stmt->execute()) {
                $success = "Barang berhasil disimpan ke sistem!";
            } else {
                $error = "Kesalahan Database: " . $stmt->error;
            }
            $stmt->close();
        } catch (Exception $e) {
            $error = "Terjadi kesalahan: " . $e->getMessage();
        }
    }
}

// 6. Ambil Data untuk Helper/Dropdown
try {
    $kategoriList = $conn->query("SELECT DISTINCT kategori FROM inventory WHERE kategori IS NOT NULL AND kategori != '' ORDER BY kategori ASC");
    $sumberDanaList = $conn->query("SELECT DISTINCT sumber_dana FROM inventory WHERE sumber_dana IS NOT NULL AND sumber_dana != '' ORDER BY sumber_dana ASC");
    $kantorList = $conn->query("SELECT DISTINCT kantor FROM inventory WHERE kantor IS NOT NULL AND kantor != '' ORDER BY kantor ASC");
    $recentItems = $conn->query("SELECT * FROM inventory ORDER BY no DESC LIMIT 8");
} catch (Exception $e) {
    $error = "Error mengambil data: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Barang Masuk - ACF EDU HUB</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root { --primary: #7AB2B2; --secondary: #4D869C; --bg: #f3f4f6; --text: #1e293b; }
        
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: var(--bg); color: var(--text); margin: 0; padding: 25px; }
        .container { max-width: 1200px; margin: 0 auto; }
        
        /* Layout */
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; }
        .grid { display: grid; grid-template-columns: 1.5fr 1fr; gap: 25px; }
        
        /* Cards */
        .card { background: white; border-radius: 16px; padding: 25px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); border: 1px solid #e2e8f0; }
        .card-title { font-size: 1.2rem; font-weight: 700; color: var(--primary); margin-bottom: 20px; display: flex; align-items: center; gap: 10px; border-bottom: 2px solid #f1f5f9; padding-bottom: 10px; }
        
        /* Forms */
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; font-size: 13px; font-weight: 600; margin-bottom: 6px; color: #64748b; }
        .form-control { width: 100%; padding: 12px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 14px; transition: all 0.3s; box-sizing: border-box; }
        .form-control:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(122, 178, 178, 0.1); }
        
        /* Buttons */
        .btn { padding: 12px 20px; border-radius: 8px; font-weight: 600; cursor: pointer; border: none; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; transition: 0.3s; }
        .btn-save { background: var(--primary); color: white; width: 100%; justify-content: center; margin-top: 10px; font-size: 15px; }
        .btn-save:hover { background: var(--secondary); transform: translateY(-1px); }
        .btn-back { background: white; color: var(--text); border: 1px solid #cbd5e1; }
        .btn-back:hover { background: #f8fafc; }
        
        /* Recent List */
        .item-list { list-style: none; padding: 0; margin: 0; max-height: 600px; overflow-y: auto; }
        .item-list::-webkit-scrollbar { width: 6px; }
        .item-list::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
        .item-card { display: flex; align-items: flex-start; gap: 15px; padding: 15px; border-bottom: 1px solid #f1f5f9; transition: 0.2s; }
        .item-card:hover { background: #f8fafc; }
        .icon-box { width: 40px; height: 40px; background: rgba(122, 178, 178, 0.1); color: var(--primary); border-radius: 10px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; margin-top: 2px; }
        .item-info { flex-grow: 1; }
        .item-name { font-weight: 700; font-size: 14px; margin: 0; }
        .item-sub { font-size: 11px; color: #64748b; margin-top: 2px; }
        .item-spec { font-size: 12px; color: #475569; margin-top: 4px; font-style: italic; }
        .item-price { text-align: right; font-weight: 800; color: #10b981; font-size: 14px; white-space: nowrap; }
        .badge-new { background: #22c55e; color: white; font-size: 10px; padding: 3px 8px; border-radius: 4px; font-weight: 700; margin-left: 8px; }
        .no-asset { font-size: 11px; color: #94a3b8; background: #f1f5f9; padding: 2px 6px; border-radius: 4px; margin-left: 5px; }

        /* Alerts */
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; display: flex; align-items: center; gap: 10px; }
        .alert-success { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
        .alert-error { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
        
        @media (max-width: 768px) {
            .grid { grid-template-columns: 1fr; }
            .form-row { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <div>
            <h1 style="margin:0; color:var(--primary); font-size: 1.8rem;"><i class="fas fa-box-open"></i> Manajemen Barang Masuk</h1>
            <p style="margin:5px 0 0; color:#64748b;">Pencatatan inventarisasi aset baru ACF EDU HUB</p>
        </div>
        <a href="<?= htmlspecialchars($backUrl) ?>" class="btn btn-back"><i class="fas fa-chevron-left"></i> Kembali</a>
    </div>

    <?php if($success): ?>
        <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if($error): ?>
        <div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="grid">
        <div class="card">
            <div class="card-title"><i class="fas fa-plus-circle"></i> Tambah Inventory Baru</div>
            <form method="POST">
                <div class="form-row">
                    <div class="form-group">
                        <label>Tanggal Perolehan *</label>
                        <input type="date" name="tanggal_perolehan" class="form-control" required value="<?= date('Y-m-d') ?>">
                    </div>
                    <div class="form-group">
                        <label>Kategori *</label>
                        <input type="text" name="kategori" class="form-control" list="listKat" placeholder="Contoh: Elektronik" required>
                        <datalist id="listKat">
                            <?php if(isset($kategoriList) && $kategoriList): while($k = $kategoriList->fetch_assoc()): ?>
                                <option value="<?= htmlspecialchars($k['kategori']) ?>">
                            <?php endwhile; endif; ?>
                        </datalist>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>Sumber Dana</label>
                        <input type="text" name="sumber_dana" class="form-control" list="listDana" placeholder="BOS / Yayasan">
                        <datalist id="listDana">
                            <?php if(isset($sumberDanaList) && $sumberDanaList): while($s = $sumberDanaList->fetch_assoc()): ?>
                                <option value="<?= htmlspecialchars($s['sumber_dana']) ?>">
                            <?php endwhile; endif; ?>
                        </datalist>
                    </div>
                    <div class="form-group">
                        <label>Kantor / Lokasi</label>
                        <input type="text" name="kantor" class="form-control" list="listKantor" placeholder="Pusat / Cabang">
                        <datalist id="listKantor">
                            <?php if(isset($kantorList) && $kantorList): while($kn = $kantorList->fetch_assoc()): ?>
                                <option value="<?= htmlspecialchars($kn['kantor']) ?>">
                            <?php endwhile; endif; ?>
                        </datalist>
                    </div>
                </div>

                <div class="form-group">
                    <label>Nama / Jenis Barang *</label>
                    <input type="text" name="jenis_barang" class="form-control" placeholder="Masukkan nama barang" required>
                </div>

                <div class="form-group">
                    <label>Spesifikasi / Detail Inventory</label>
                    <textarea name="jenis_inventory" class="form-control" rows="3" placeholder="Contoh: Asus ROG Strix, Core i7, RAM 16GB"></textarea>
                </div>

                <div class="form-group">
                    <label>Harga Perolehan (Rp) *</label>
                    <input type="number" name="harga_perolehan" class="form-control" placeholder="Hanya angka" step="0.01" required>
                </div>

                <button type="submit" class="btn btn-save"><i class="fas fa-save"></i> Simpan ke Inventory</button>
            </form>
        </div>

        <div class="card">
            <div class="card-title">
                <i class="fas fa-clock"></i> Baru Saja Ditambahkan
                <span style="margin-left: auto; font-size: 12px; font-weight: 500; color: #64748b;">
                    Total: <?= isset($recentItems) ? $recentItems->num_rows : 0 ?> item
                </span>
            </div>
            <div class="item-list">
                <?php if(isset($recentItems) && $recentItems && $recentItems->num_rows > 0): ?>
                    <?php while($row = $recentItems->fetch_assoc()): ?>
                        <div class="item-card">
                            <div class="icon-box"><i class="fas fa-box"></i></div>
                            <div class="item-info">
                                <p class="item-name">
                                    <?= htmlspecialchars($row['jenis_barang']) ?>
                                    <?php if(!empty($row['no'])): ?>
                                        <span class="no-asset">#<?= htmlspecialchars($row['no']) ?></span>
                                    <?php endif; ?>
                                    <span class="badge-new">BARU</span>
                                </p>
                                <p class="item-sub">
                                    <i class="far fa-calendar"></i> <?= date('d/m/Y', strtotime($row['tanggal_perolehan'])) ?> • 
                                    <i class="fas fa-tag"></i> <?= htmlspecialchars($row['kategori']) ?>
                                    <?php if(!empty($row['kantor'])): ?>
                                        • <i class="fas fa-building"></i> <?= htmlspecialchars($row['kantor']) ?>
                                    <?php endif; ?>
                                    <?php if(!empty($row['sumber_dana'])): ?>
                                        • <i class="fas fa-hand-holding-usd"></i> <?= htmlspecialchars($row['sumber_dana']) ?>
                                    <?php endif; ?>
                                </p>
                                <?php if(!empty($row['jenis_inventory'])): ?>
                                    <p class="item-spec">
                                        <i class="fas fa-info-circle"></i> <?= htmlspecialchars(strlen($row['jenis_inventory']) > 80 ? substr($row['jenis_inventory'], 0, 80) . '...' : $row['jenis_inventory']) ?>
                                    </p>
                                <?php else: ?>
                                    <p class="item-spec" style="color: #94a3b8;">
                                        <i class="fas fa-exclamation-circle"></i> Spesifikasi belum diisi
                                    </p>
                                <?php endif; ?>
                            </div>
                            <div class="item-price">Rp <?= number_format($row['harga_perolehan'], 0, ',', '.') ?></div>
                        </div>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div style="text-align:center; padding: 40px 20px;">
                        <i class="fas fa-inbox" style="font-size: 48px; color: #cbd5e1; margin-bottom: 10px;"></i>
                        <p style="color:#94a3b8; font-size:14px; margin: 0;">Belum ada data terbaru.</p>
                        <p style="color:#cbd5e1; font-size:12px; margin-top: 5px;">Mulai tambahkan barang baru di form sebelah kiri</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
    // Auto hide alert setelah 5 detik
    setTimeout(() => {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(a => a.style.opacity = '0');
        setTimeout(() => alerts.forEach(a => a.style.display = 'none'), 300);
    }, 5000);
</script>

</body>
</html>