<?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' && isset($_POST['proses_keluar'])) {
    $inventory_id = intval($_POST['inventory_id'] ?? 0);
    $tipe_transaksi = $_POST['tipe_transaksi'] ?? '';
    $tanggal = $_POST['tanggal_transaksi'] ?? '';
    $keterangan_dasar = trim($_POST['keterangan'] ?? '');
    $ke_kantor_id = !empty($_POST['ke_kantor_id']) ? intval($_POST['ke_kantor_id']) : null;
    $user_id = $_SESSION['user_id'] ?? 0;

    // Input Khusus Lelang
    $harga_lelang = isset($_POST['harga_lelang_clean']) ? str_replace('.', '', $_POST['harga_lelang_clean']) : 0;
    $pembeli_lelang = $_POST['pembeli_lelang'] ?? '';

    // Gabungkan keterangan jika lelang
    $keterangan_final = $keterangan_dasar;
    if ($tipe_transaksi === 'Lelang') {
        $keterangan_final .= " | Harga: Rp " . number_format((float)$harga_lelang, 0, ',', '.') . " | Pembeli: " . $pembeli_lelang;
    }

    if (!$inventory_id || !$tipe_transaksi || !$tanggal) {
        $error = "Mohon isi data wajib (*).";
    } else {
        $conn->begin_transaction();
        try {
            $stmt = $conn->prepare("SELECT no, jenis_barang FROM inventory WHERE id = ? AND status = 'aktif'");
            $stmt->bind_param("i", $inventory_id);
            $stmt->execute();
            $asset = $stmt->get_result()->fetch_assoc();

            if (!$asset) throw new Exception("Aset tidak aktif atau tidak ditemukan.");

            $status_baru = ($tipe_transaksi === 'Pindah') ? 'aktif' : strtolower($tipe_transaksi);

            // 1. Update Inventory
            $upd = $conn->prepare("UPDATE inventory SET status = ?, tanggal_keluar = ?, keterangan_keluar = ? WHERE id = ?");
            $upd->bind_param("sssi", $status_baru, $tanggal, $keterangan_final, $inventory_id);
            $upd->execute();

            // 2. Insert ke Transaksi
            $trans = $conn->prepare("INSERT INTO transaksi (inventory_id, tipe_transaksi, tanggal_transaksi, ke_kantor_id, keterangan, created_by) VALUES (?, ?, ?, ?, ?, ?)");
            $trans->bind_param("issisi", $inventory_id, $tipe_transaksi, $tanggal, $ke_kantor_id, $keterangan_final, $user_id);
            $trans->execute();

            $conn->commit();
            $success = "Berhasil mencatat transaksi $tipe_transaksi untuk aset {$asset['no']}.";
        } catch (Exception $e) {
            $conn->rollback();
            $error = $e->getMessage();
        }
    }
}

// Ambil data untuk dropdown
try {
    $listAset = $conn->query("SELECT id, no, jenis_barang FROM inventory WHERE status = 'aktif' ORDER BY no ASC");
    $listKantor = $conn->query("SELECT id, nama_kantor FROM kantor ORDER BY nama_kantor ASC");
} 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>Input Barang Keluar - 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 { --p: #7AB2B2; --s: #4D869C; --bg: #f8fafc; }
        body { font-family: 'Inter', sans-serif; background: var(--bg); padding: 20px; margin: 0; }
        
        .card { background: white; max-width: 700px; margin: 0 auto; padding: 30px; border-radius: 15px; box-shadow: 0 10px 25px rgba(0,0,0,0.05); }
        h2 { margin-top: 0; color: var(--p); display: flex; align-items: center; gap: 10px; }
        
        .form-group { margin-bottom: 20px; }
        label { display: block; font-weight: 600; margin-bottom: 8px; font-size: 14px; color: #475569; }
        .form-control { width: 100%; padding: 12px; border: 1px solid #e2e8f0; border-radius: 10px; box-sizing: border-box; outline: none; transition: 0.3s; font-size: 14px; }
        .form-control:focus { border-color: var(--p); box-shadow: 0 0 0 3px rgba(122, 178, 178, 0.1); }
        
        .btn-submit { background: var(--p); color: white; border: none; padding: 15px; width: 100%; border-radius: 10px; font-weight: bold; cursor: pointer; font-size: 16px; display: flex; align-items: center; justify-content: center; gap: 10px; }
        .btn-submit:hover { background: var(--s); }
        
        .dynamic-box { display: none; background: #f1f5f9; padding: 20px; border-radius: 10px; margin-bottom: 20px; border-left: 4px solid var(--p); }
        
        .alert { padding: 15px; border-radius: 10px; margin-bottom: 20px; font-size: 14px; }
        .alert-success { background: #dcfce7; color: #166534; border-left: 4px solid #22c55e; }
        .alert-error { background: #fee2e2; color: #991b1b; border-left: 4px solid #ef4444; }
        
        .flex-row { display: flex; gap: 15px; }
        .flex-row .form-group { flex: 1; }
        
        .back-link { text-align: center; margin-top: 15px; }
        .back-link a { color: #64748b; text-decoration: none; font-size: 14px; }
        .back-link a:hover { color: var(--p); }
    </style>
</head>
<body>

<div class="card">
    <h2><i class="fas fa-sign-out-alt"></i> Input Pengeluaran Aset</h2>
    
    <?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; ?>

    <form method="POST">
        <div class="form-group">
            <label>Pilih Aset *</label>
            <select name="inventory_id" class="form-control" required>
                <option value="">-- Cari No Aset / Nama --</option>
                <?php if(isset($listAset) && $listAset): while($row = $listAset->fetch_assoc()): ?>
                    <option value="<?= $row['id'] ?>"><?= htmlspecialchars($row['no']) ?> - <?= htmlspecialchars($row['jenis_barang']) ?></option>
                <?php endwhile; endif; ?>
            </select>
        </div>

        <div class="flex-row">
            <div class="form-group">
                <label>Tipe Pengeluaran *</label>
                <select name="tipe_transaksi" id="tipe_select" class="form-control" required onchange="toggleFields()">
                    <option value="">-- Pilih Tipe --</option>
                    <option value="Keluar">Keluar (Dibuang)</option>
                    <option value="Pindah">Pindah Lokasi</option>
                    <option value="Rusak">Rusak</option>
                    <option value="Lelang">Lelang / Dijual</option>
                </select>
            </div>
            <div class="form-group">
                <label>Tanggal *</label>
                <input type="date" name="tanggal_transaksi" class="form-control" value="<?= date('Y-m-d') ?>" required>
            </div>
        </div>

        <div id="box_pindah" class="dynamic-box">
            <label>Kantor Tujuan Mutasi *</label>
            <select name="ke_kantor_id" class="form-control">
                <option value="">-- Pilih Lokasi Baru --</option>
                <?php if(isset($listKantor) && $listKantor): while($k = $listKantor->fetch_assoc()): ?>
                    <option value="<?= $k['id'] ?>"><?= htmlspecialchars($k['nama_kantor']) ?></option>
                <?php endwhile; endif; ?>
            </select>
        </div>

        <div id="box_lelang" class="dynamic-box">
            <div class="flex-row" style="margin-bottom: 10px;">
                <div>
                    <label>Harga Lelang Terakhir (Rp) *</label>
                    <input type="text" id="v_harga" class="form-control" placeholder="Contoh: 5.000.000" onkeyup="formatRupiah(this)">
                    <input type="hidden" name="harga_lelang_clean" id="harga_asli">
                </div>
                <div>
                    <label>Nama Pembeli / Pemenang *</label>
                    <input type="text" name="pembeli_lelang" class="form-control" placeholder="Contoh: CV. Maju Jaya">
                </div>
            </div>
        </div>

        <div class="form-group">
            <label>Keterangan Alasan *</label>
            <textarea name="keterangan" class="form-control" rows="3" placeholder="Contoh: Kondisi rusak berat, dilelang karena penyusutan nilai, dll..." required></textarea>
        </div>

        <button type="submit" name="proses_keluar" class="btn-submit">
            <i class="fas fa-save"></i> SIMPAN DATA
        </button>
        
        <div class="back-link">
            <a href="<?= htmlspecialchars($backUrl) ?>"><i class="fas fa-arrow-left"></i> Kembali ke Inventory</a>
        </div>
    </form>
</div>

<script>
// 1. Fungsi format Rupiah (Titik otomatis saat mengetik)
function formatRupiah(elemen) {
    let value = elemen.value.replace(/[^,\d]/g, '').toString();
    let split = value.split(',');
    let sisa  = split[0].length % 3;
    let rupiah = split[0].substr(0, sisa);
    let ribuan = split[0].substr(sisa).match(/\d{3}/gi);

    if (ribuan) {
        let separator = sisa ? '.' : '';
        rupiah += separator + ribuan.join('.');
    }

    rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
    
    // Tampilkan di layar (dengan titik)
    elemen.value = rupiah;
    
    // Simpan angka asli ke hidden field (tanpa titik)
    document.getElementById('harga_asli').value = value.replace(/\./g, '');
}

// 2. Fungsi Toggle Tampilan Form Berdasarkan Tipe
function toggleFields() {
    const tipe = document.getElementById('tipe_select').value;
    const boxPindah = document.getElementById('box_pindah');
    const boxLelang = document.getElementById('box_lelang');

    // Sembunyikan semua dulu
    boxPindah.style.display = 'none';
    boxLelang.style.display = 'none';

    // Tampilkan sesuai pilihan
    if (tipe === 'Pindah') {
        boxPindah.style.display = 'block';
    } else if (tipe === 'Lelang') {
        boxLelang.style.display = 'block';
    }
}

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

</body>
</html>