<?php
session_start();

// Perbaikan path koneksi - sesuaikan dengan struktur folder
require_once __DIR__ . '/../../DataBase/koneksi.php';

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

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

// Function logActivity jika belum ada
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']);

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id == 0) {
    header("Location: ../inventory_list.php");
    exit;
}

// Get data barang
$sql = "SELECT * FROM inventory WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$barang = $result->fetch_assoc();

if (!$barang) {
    header("Location: ../inventory_list.php");
    exit;
}

// Get dropdown data - cek apakah tabel relasi ada
$kategoriList = $conn->query("SHOW TABLES LIKE 'kategori'");
$sumberDanaList = $conn->query("SHOW TABLES LIKE 'sumber_dana'");
$kantorList = $conn->query("SHOW TABLES LIKE 'kantor'");
$jenisBarangList = $conn->query("SHOW TABLES LIKE 'jenis_barang'");

// Jika tabel relasi ada, ambil datanya
$hasKategori = $kategoriList && $kategoriList->num_rows > 0;
$hasSumberDana = $sumberDanaList && $sumberDanaList->num_rows > 0;
$hasKantor = $kantorList && $kantorList->num_rows > 0;
$hasJenisBarang = $jenisBarangList && $jenisBarangList->num_rows > 0;

if ($hasKategori) {
    $kategoriList = $conn->query("SELECT * FROM kategori ORDER BY nama_kategori");
}
if ($hasSumberDana) {
    $sumberDanaList = $conn->query("SELECT * FROM sumber_dana ORDER BY nama_sumber");
}
if ($hasKantor) {
    $kantorList = $conn->query("SELECT * FROM kantor WHERE status='active' ORDER BY nama_kantor");
    if (!$kantorList || $kantorList->num_rows == 0) {
        $kantorList = $conn->query("SELECT * FROM kantor ORDER BY nama_kantor");
    }
}
if ($hasJenisBarang) {
    $jenisBarangList = $conn->query("SELECT jb.*, k.nama_kategori FROM jenis_barang jb LEFT JOIN kategori k ON jb.kategori_id = k.id ORDER BY jb.nama_jenis");
}

$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 {
        $sql = "UPDATE inventory SET 
                tanggal_perolehan = ?,
                kategori = ?,
                sumber_dana = ?,
                kantor = ?,
                jenis_barang = ?,
                jenis_inventory = ?,
                harga_perolehan = ?
                WHERE id = ?";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssssssdi", $tanggal_perolehan, $kategori, $sumber_dana, $kantor, $jenis_barang, $jenis_inventory, $harga_perolehan, $id);
        
        if ($stmt->execute()) {
            // Log aktivitas
            if (isset($_SESSION['user_id'])) {
                logActivity($_SESSION['user_id'], "Mengubah data barang inventory: $jenis_barang", 'inventory', $id);
            }
            
            $success = "Data barang berhasil diperbarui!";
            
            // Refresh data
            $stmt2 = $conn->prepare("SELECT * FROM inventory WHERE id = ?");
            $stmt2->bind_param("i", $id);
            $stmt2->execute();
            $barang = $stmt2->get_result()->fetch_assoc();
            
            // Redirect after 1.5 seconds
            echo "<script>
                setTimeout(function() {
                    window.history.back();
                }, 1500);
            </script>";
        } else {
            $error = "Gagal memperbarui data: " . $conn->error;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Aset - ACF EDU HUB</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-teal: #7AB2B2;
            --secondary-teal: #4D869C;
            --light-mint: #CDE8E5;
            --lightest-mint: #EEF7FF;
            --text-dark: #1e293b;
            --text-medium: #475569;
            --text-light: #64748b;
            --border-color: #e2e8f0;
            --success-green: #10b981;
            --success-light: #d1fae5;
            --error-red: #ef4444;
            --error-light: #fee2e2;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: linear-gradient(135deg, var(--lightest-mint) 0%, var(--light-mint) 100%);
            padding: 24px;
            color: var(--text-dark);
            min-height: 100vh;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
        }

        /* Header */
        .page-header {
            background: white;
            padding: 24px 28px;
            border-radius: 16px;
            border-left: 5px solid var(--primary-teal);
            margin-bottom: 24px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
        }

        .page-header h1 {
            font-size: 26px;
            font-weight: 800;
            color: var(--text-dark);
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .page-header h1 i {
            color: var(--primary-teal);
        }

        /* Buttons */
        .btn {
            padding: 11px 20px;
            border: none;
            border-radius: 12px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 700;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
            font-family: 'Inter', sans-serif;
        }

        .btn-secondary {
            background: white;
            color: var(--text-dark);
            border: 2px solid var(--border-color);
        }

        .btn-secondary:hover {
            background: var(--lightest-mint);
            border-color: var(--primary-teal);
        }

        .btn-primary {
            background: var(--primary-teal);
            color: white;
        }

        .btn-primary:hover {
            background: var(--secondary-teal);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(122, 178, 178, 0.3);
        }

        /* Card */
        .card {
            background: white;
            border-radius: 16px;
            padding: 32px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
            border: 1px solid var(--border-color);
        }

        /* Alerts */
        .alert {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 14px;
            font-weight: 500;
            animation: slideDown 0.4s ease;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .alert i {
            font-size: 18px;
        }

        .alert-danger {
            background: var(--error-light);
            color: #991b1b;
            border-left: 4px solid var(--error-red);
        }

        .alert-success {
            background: var(--success-light);
            color: #065f46;
            border-left: 4px solid var(--success-green);
        }

        /* Form */
        .form-section-title {
            font-size: 16px;
            font-weight: 700;
            color: var(--text-dark);
            margin-bottom: 20px;
            padding-bottom: 12px;
            border-bottom: 2px solid var(--light-mint);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .form-section-title i {
            color: var(--primary-teal);
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 24px;
            margin-bottom: 24px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full {
            grid-column: 1 / -1;
        }

        .form-group label {
            font-size: 13px;
            font-weight: 700;
            color: var(--text-medium);
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .required {
            color: var(--error-red);
            margin-left: 4px;
        }

        .form-control {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid var(--border-color);
            border-radius: 10px;
            font-size: 14px;
            font-family: 'Inter', sans-serif;
            color: var(--text-dark);
            transition: all 0.3s ease;
            background: white;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary-teal);
            box-shadow: 0 0 0 3px rgba(122, 178, 178, 0.1);
            background: var(--lightest-mint);
        }

        textarea.form-control {
            resize: vertical;
            min-height: 100px;
            font-family: 'Inter', sans-serif;
        }

        /* Datalist styling hint */
        .input-hint {
            font-size: 11px;
            color: var(--text-light);
            margin-top: 4px;
        }

        /* Form Actions */
        .form-actions {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            margin-top: 32px;
            padding-top: 24px;
            border-top: 2px solid var(--border-color);
        }

        /* Info Box */
        .info-box {
            background: var(--lightest-mint);
            border-left: 4px solid var(--primary-teal);
            padding: 16px 20px;
            border-radius: 10px;
            margin-bottom: 24px;
            font-size: 13px;
            color: var(--text-medium);
            display: flex;
            align-items: start;
            gap: 12px;
        }

        .info-box i {
            color: var(--primary-teal);
            font-size: 16px;
            margin-top: 2px;
        }

        /* Responsive */
        @media (max-width: 768px) {
            body {
                padding: 16px;
            }

            .page-header {
                padding: 20px;
            }

            .page-header h1 {
                font-size: 20px;
            }

            .card {
                padding: 24px 20px;
            }

            .form-grid {
                grid-template-columns: 1fr;
                gap: 20px;
            }

            .form-actions {
                flex-direction: column-reverse;
            }

            .btn {
                width: 100%;
                justify-content: center;
            }
        }

        @media (max-width: 480px) {
            .page-header {
                flex-direction: column;
                align-items: stretch;
            }

            .btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="page-header">
            <h1>
                <i class="fas fa-edit"></i>
                Edit Data Aset
            </h1>
            <a href="javascript:history.back()" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Kembali
            </a>
        </div>

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

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

            <!-- Info Box -->
            <div class="info-box">
                <i class="fas fa-info-circle"></i>
                <div>
                    <strong>Informasi:</strong> Field yang ditandai dengan <span class="required">*</span> wajib diisi. 
                    Beberapa field memiliki suggestion otomatis saat Anda mengetik.
                </div>
            </div>

            <!-- Form -->
            <form method="POST" action="">
                <!-- Section: Informasi Dasar -->
                <div class="form-section-title">
                    <i class="fas fa-file-alt"></i>
                    Informasi Dasar Aset
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>
                            Tanggal Perolehan
                            <span class="required">*</span>
                        </label>
                        <input 
                            type="date" 
                            name="tanggal_perolehan" 
                            class="form-control" 
                            required 
                            value="<?php echo htmlspecialchars($barang['tanggal_perolehan']); ?>"
                        >
                    </div>

                    <div class="form-group">
                        <label>
                            Kategori
                            <span class="required">*</span>
                        </label>
                        <input 
                            type="text" 
                            name="kategori" 
                            class="form-control" 
                            required 
                            value="<?php echo htmlspecialchars($barang['kategori']); ?>" 
                            list="kategori-list"
                            placeholder="Pilih atau ketik kategori"
                        >
                        <datalist id="kategori-list">
                            <option value="Peralatan">
                            <option value="Kendaraan">
                            <option value="Furniture">
                            <option value="Elektronik">
                            <option value="Perlengkapan">
                        </datalist>
                        <div class="input-hint">Ketik untuk melihat suggestion</div>
                    </div>

                    <div class="form-group">
                        <label>
                            Jenis Barang
                            <span class="required">*</span>
                        </label>
                        <input 
                            type="text" 
                            name="jenis_barang" 
                            class="form-control" 
                            required 
                            value="<?php echo htmlspecialchars($barang['jenis_barang']); ?>" 
                            list="jenis-list"
                            placeholder="Nama barang/aset"
                        >
                        <datalist id="jenis-list">
                            <option value="Laptop">
                            <option value="Printer">
                            <option value="Sound System">
                            <option value="Lemari">
                            <option value="Rak Buku">
                            <option value="CCTV">
                            <option value="Proyektor/Infokus">
                            <option value="Motor">
                            <option value="AC">
                            <option value="Pintu Alumunium">
                            <option value="Web Cam">
                        </datalist>
                    </div>

                    <div class="form-group">
                        <label>
                            Harga Perolehan
                            <span class="required">*</span>
                        </label>
                        <input 
                            type="text" 
                            name="harga_perolehan" 
                            class="form-control" 
                            required 
                            id="harga" 
                            value="<?php echo number_format($barang['harga_perolehan'], 0, ',', '.'); ?>"
                            placeholder="0"
                        >
                        <div class="input-hint">Format: Rp 1.000.000</div>
                    </div>
                </div>

                <!-- Section: Lokasi & Dana -->
                <div class="form-section-title" style="margin-top: 32px;">
                    <i class="fas fa-map-marker-alt"></i>
                    Lokasi & Sumber Dana
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>
                            Kantor/Lokasi
                            <span class="required">*</span>
                        </label>
                        <input 
                            type="text" 
                            name="kantor" 
                            class="form-control" 
                            required 
                            value="<?php echo htmlspecialchars($barang['kantor']); ?>" 
                            list="kantor-list"
                            placeholder="Pilih lokasi"
                        >
                        <datalist id="kantor-list">
                            <option value="Pusat">
                            <option value="SDJ Medan">
                            <option value="SDJ - Surabaya">
                            <option value="SDJ - Jakarta Utara">
                            <option value="SDJ - Semarang">
                            <option value="SDJ - Jakarta Selatan">
                            <option value="SDJ - Jakarta Timur">
                            <option value="SDJ - Yogyakarta">
                        </datalist>
                    </div>

                    <div class="form-group">
                        <label>
                            Sumber Dana
                            <span class="required">*</span>
                        </label>
                        <input 
                            type="text" 
                            name="sumber_dana" 
                            class="form-control" 
                            required 
                            value="<?php echo htmlspecialchars($barang['sumber_dana']); ?>" 
                            list="sumber-list"
                            placeholder="Pilih sumber dana"
                        >
                        <datalist id="sumber-list">
                            <option value="Operasional">
                            <option value="BOS">
                            <option value="SE">
                            <option value="Program">
                            <option value="Terikat">
                        </datalist>
                    </div>
                </div>

                <!-- Section: Detail Tambahan -->
                <div class="form-section-title" style="margin-top: 32px;">
                    <i class="fas fa-list"></i>
                    Detail Tambahan
                </div>

                <div class="form-grid">
                    <div class="form-group full">
                        <label>Keterangan Detail Aset</label>
                        <textarea 
                            name="jenis_inventory" 
                            class="form-control" 
                            rows="4"
                            placeholder="Masukkan spesifikasi, merk, kondisi, atau informasi tambahan lainnya..."
                        ><?php echo htmlspecialchars($barang['jenis_inventory']); ?></textarea>
                        <div class="input-hint">Optional: Tambahkan informasi detail seperti spesifikasi, kondisi, dll.</div>
                    </div>
                </div>

                <!-- Form Actions -->
                <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 Perubahan
                    </button>
                </div>
            </form>
        </div>
    </div>

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

        // Fokus ke input harga
        hargaInput.addEventListener('focus', function() {
            this.select();
        });

        // Validasi form sebelum submit
        document.querySelector('form').addEventListener('submit', function(e) {
            const harga = document.getElementById('harga').value.replace(/\D/g, '');
            if (!harga || harga === '0') {
                e.preventDefault();
                alert('Harga perolehan harus diisi dan lebih dari 0!');
                document.getElementById('harga').focus();
                return false;
            }
        });

        // Auto-hide success message
        const successAlert = document.querySelector('.alert-success');
        if (successAlert) {
            setTimeout(() => {
                successAlert.style.opacity = '0';
                successAlert.style.transform = 'translateY(-10px)';
                setTimeout(() => {
                    successAlert.style.display = 'none';
                }, 300);
            }, 3000);
        }
    </script>
</body>
</html>