<?php
session_start();

// Perbaikan path koneksi - dari pages/admin/ ke DataBase/
require_once __DIR__ . '/../../DataBase/koneksi.php';

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

// Function helper jika belum ada
if (!function_exists('checkRole')) {
    function checkRole($allowedRoles) {
        if (!isset($_SESSION['role']) && !isset($_SESSION['user_type'])) {
            header("Location: ../../index.html?error=unauthorized");
            exit;
        }
        $userRole = $_SESSION['role'] ?? $_SESSION['user_type'] ?? '';
        if (!in_array($userRole, $allowedRoles)) {
            header("Location: ../../index.html?error=unauthorized");
            exit;
        }
    }
}

if (!function_exists('logActivity')) {
    function logActivity($user_id, $activity, $module = '', $reference_id = 0) {
        global $conn;
        $sql = "INSERT INTO activity_log (user_id, activity, module, reference_id) VALUES (?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param("issi", $user_id, $activity, $module, $reference_id);
            $stmt->execute();
        }
    }
}

checkRole(['A', 'M']);

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

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 = str_replace(['.', ','], '', $_POST['harga_perolehan']);
    
    // Validation
    if (empty($tanggal_perolehan) || empty($jenis_barang) || empty($harga_perolehan)) {
        $error = "Tanggal perolehan, jenis barang, dan harga harus diisi!";
    } else {
        // Get no terakhir
        $lastNoQuery = $conn->query("SELECT MAX(no) as last_no FROM inventory");
        $lastNo = 0;
        if ($lastNoQuery && $lastNoQuery->num_rows > 0) {
            $lastNo = $lastNoQuery->fetch_assoc()['last_no'] ?? 0;
        }
        $no_urut = $lastNo + 1;
        
        $sql = "INSERT INTO inventory (no, tanggal_perolehan, kategori, sumber_dana, kantor, jenis_barang, jenis_inventory, harga_perolehan) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("issssssd", $no_urut, $tanggal_perolehan, $kategori, $sumber_dana, $kantor, $jenis_barang, $jenis_inventory, $harga_perolehan);
        
        if ($stmt->execute()) {
            $inventory_id = $stmt->insert_id;
            
            // Log aktivitas
            if (isset($_SESSION['user_id'])) {
                logActivity($_SESSION['user_id'], "Menambah barang inventory: $jenis_barang", 'inventory', $inventory_id);
            }
            
            $success = "Data barang berhasil ditambahkan!";
            
            // Redirect after 1.5 seconds
            echo "<script>
                setTimeout(function() {
                    window.location.href = 'kelola_barang.php';
                }, 1500);
            </script>";
        } else {
            $error = "Gagal menambahkan data: " . $conn->error;
        }
    }
}

// Get distinct values untuk autocomplete
$kategoriList = $conn->query("SELECT DISTINCT kategori FROM inventory WHERE kategori IS NOT NULL AND kategori != '' ORDER BY kategori");
$sumberDanaList = $conn->query("SELECT DISTINCT sumber_dana FROM inventory WHERE sumber_dana IS NOT NULL AND sumber_dana != '' ORDER BY sumber_dana");
$kantorList = $conn->query("SELECT DISTINCT kantor FROM inventory WHERE kantor IS NOT NULL AND kantor != '' ORDER BY kantor");
$jenisBarangList = $conn->query("SELECT DISTINCT jenis_barang FROM inventory WHERE jenis_barang IS NOT NULL AND jenis_barang != '' ORDER BY jenis_barang");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Tambah Barang</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            background: #f8fafc;
            margin: 0;
        }
        .container {
            max-width: 900px;
            margin: 0 auto;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .header h1 {
            color: #1e3a8a;
            font-size: 24px;
            margin: 0;
        }
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }
        .btn-secondary {
            background: #64748b;
            color: white;
        }
        .btn-primary {
            background: #1e3a8a;
            color: white;
        }
        .btn-primary:hover {
            background: #1e40af;
        }
        .card {
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .alert {
            padding: 12px 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #dc2626;
        }
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }
        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group.full {
            grid-column: 1 / -1;
        }
        .form-group label {
            display: block;
            font-size: 14px;
            font-weight: 600;
            color: #334155;
            margin-bottom: 8px;
        }
        .required {
            color: #dc2626;
        }
        .form-control {
            width: 100%;
            padding: 10px;
            border: 1px solid #e2e8f0;
            border-radius: 5px;
            font-size: 14px;
            box-sizing: border-box;
        }
        .form-control:focus {
            outline: none;
            border-color: #1e3a8a;
            box-shadow: 0 0 0 3px rgba(30, 58, 138, 0.1);
        }
        textarea.form-control {
            resize: vertical;
            min-height: 100px;
        }
        .form-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e2e8f0;
        }
        .help-text {
            font-size: 12px;
            color: #64748b;
            margin-top: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-plus-circle"></i> Tambah Barang Inventory</h1>
            <a href="javascript:history.back()" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Kembali
            </a>
        </div>

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

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

            <form method="POST" action="">
                <div class="form-grid">
                    <div class="form-group">
                        <label><i class="fas fa-calendar"></i> Tanggal Perolehan <span class="required">*</span></label>
                        <input type="date" name="tanggal_perolehan" class="form-control" required value="<?php echo date('Y-m-d'); ?>">
                    </div>

                    <div class="form-group">
                        <label><i class="fas fa-tags"></i> Kategori <span class="required">*</span></label>
                        <input type="text" name="kategori" class="form-control" required placeholder="Contoh: Peralatan, Kendaraan" list="kategori-list">
                        <datalist id="kategori-list">
                            <option value="Peralatan">
                            <option value="Kendaraan">
                            <option value="Elektronik">
                            <option value="Furniture">
                            <?php if ($kategoriList): ?>
                                <?php while($kat = $kategoriList->fetch_assoc()): ?>
                                    <option value="<?php echo htmlspecialchars($kat['kategori']); ?>">
                                <?php endwhile; ?>
                            <?php endif; ?>
                        </datalist>
                        <div class="help-text">Ketik atau pilih dari daftar</div>
                    </div>

                    <div class="form-group">
                        <label><i class="fas fa-money-bill-wave"></i> Sumber Dana <span class="required">*</span></label>
                        <input type="text" name="sumber_dana" class="form-control" required placeholder="Contoh: BOS, APBN, SE" list="sumber-list">
                        <datalist id="sumber-list">
                            <option value="Operasional">
                            <option value="BOS">
                            <option value="SE">
                            <option value="APBN">
                            <option value="Program">
                            <option value="Dana Terikat - SE">
                            <?php if ($sumberDanaList): ?>
                                <?php while($sd = $sumberDanaList->fetch_assoc()): ?>
                                    <option value="<?php echo htmlspecialchars($sd['sumber_dana']); ?>">
                                <?php endwhile; ?>
                            <?php endif; ?>
                        </datalist>
                        <div class="help-text">Ketik atau pilih dari daftar</div>
                    </div>

                    <div class="form-group">
                        <label><i class="fas fa-building"></i> Kantor <span class="required">*</span></label>
                        <input type="text" name="kantor" class="form-control" required placeholder="Contoh: Pusat, SDJ - Jakarta" list="kantor-list">
                        <datalist id="kantor-list">
                            <option value="Pusat">
                            <option value="Kantor Pusat">
                            <option value="SDJ - Jakarta Utara">
                            <option value="SDJ - Jakarta Selatan">
                            <option value="SDJ - Jakarta Timur">
                            <option value="SDJ - Semarang">
                            <option value="SDJ - Surabaya">
                            <option value="SDJ - Medan">
                            <option value="SDJ - Yogyakarta">
                            <?php if ($kantorList): ?>
                                <?php while($kant = $kantorList->fetch_assoc()): ?>
                                    <option value="<?php echo htmlspecialchars($kant['kantor']); ?>">
                                <?php endwhile; ?>
                            <?php endif; ?>
                        </datalist>
                        <div class="help-text">Ketik atau pilih dari daftar</div>
                    </div>

                    <div class="form-group">
                        <label><i class="fas fa-box"></i> Jenis Barang <span class="required">*</span></label>
                        <input type="text" name="jenis_barang" class="form-control" required placeholder="Contoh: Laptop, Printer, AC" list="jenis-list">
                        <datalist id="jenis-list">
                            <option value="Laptop">
                            <option value="Printer">
                            <option value="AC">
                            <option value="Sound System">
                            <option value="Proyektor/Infokus">
                            <option value="CCTV">
                            <option value="Motor">
                            <option value="Lemari">
                            <option value="Rak Buku">
                            <option value="Meja">
                            <option value="Kursi">
                            <option value="Web Cam">
                            <?php if ($jenisBarangList): ?>
                                <?php while($jb = $jenisBarangList->fetch_assoc()): ?>
                                    <option value="<?php echo htmlspecialchars($jb['jenis_barang']); ?>">
                                <?php endwhile; ?>
                            <?php endif; ?>
                        </datalist>
                        <div class="help-text">Ketik atau pilih dari daftar</div>
                    </div>

                    <div class="form-group">
                        <label><i class="fas fa-dollar-sign"></i> Harga Perolehan <span class="required">*</span></label>
                        <input type="text" name="harga_perolehan" class="form-control" required placeholder="0" id="harga">
                        <div class="help-text">Format otomatis: Rp 1.000.000</div>
                    </div>

                    <div class="form-group full">
                        <label><i class="fas fa-list-alt"></i> Jenis Inventory (Keterangan Detail)</label>
                        <textarea name="jenis_inventory" class="form-control" rows="4" placeholder="Contoh: BOS kinerja 2023 : Laptop Acer i3 : 1 buah

Atau: Penyaluran : Pusat : Tidak Terikat : Operasional : Pembelian laptop untuk staff"></textarea>
                        <div class="help-text">Isi dengan keterangan lengkap seperti program, spesifikasi, jumlah, dll</div>
                    </div>
                </div>

                <div class="form-actions">
                    <a href="javascript:history.back()" class="btn btn-secondary">
                        <i class="fas fa-times"></i> Batal
                    </a>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Simpan Data
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Format input harga
        const hargaInput = document.getElementById('harga');
        hargaInput.addEventListener('input', function(e) {
            let value = this.value.replace(/\D/g, '');
            this.value = new Intl.NumberFormat('id-ID').format(value);
        });

        // Auto uppercase untuk input tertentu
        document.querySelectorAll('input[list]').forEach(input => {
            input.addEventListener('blur', function() {
                // Capitalize first letter of each word
                this.value = this.value.replace(/\b\w/g, l => l.toUpperCase());
            });
        });
    </script>
</body>
</html>