<?php
session_start();

// Perbaikan path - 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('formatRupiah')) {
    function formatRupiah($angka) {
        return 'Rp ' . number_format($angka, 0, ',', '.');
    }
}

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

// Pagination
$limit = 15;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $limit;

// Search & Filter
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$filter_kategori = isset($_GET['kategori']) ? $_GET['kategori'] : '';
$filter_kantor = isset($_GET['kantor']) ? $_GET['kantor'] : '';

// Build query - sesuaikan dengan struktur tabel yang sebenarnya
$where = "WHERE 1=1";
$params = [];
$types = "";

if ($search) {
    $where .= " AND (i.jenis_barang LIKE ? OR i.jenis_inventory LIKE ? OR i.kantor LIKE ?)";
    $searchParam = "%$search%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
    $types .= "sss";
}

if ($filter_kategori !== '') {
    $where .= " AND i.kategori = ?";
    $params[] = $filter_kategori;
    $types .= "s";
}

if ($filter_kantor !== '') {
    $where .= " AND i.kantor = ?";
    $params[] = $filter_kantor;
    $types .= "s";
}

// Count total records
$sqlCount = "SELECT COUNT(*) as total FROM inventory i $where";
$stmtCount = $conn->prepare($sqlCount);
if (!empty($params)) {
    $stmtCount->bind_param($types, ...$params);
}
$stmtCount->execute();
$totalRecords = $stmtCount->get_result()->fetch_assoc()['total'];
$totalPages = ceil($totalRecords / $limit);

// Get data
$sql = "SELECT * FROM inventory i $where ORDER BY i.tanggal_perolehan DESC, i.id DESC LIMIT ? OFFSET ?";

$stmt = $conn->prepare($sql);
$params[] = $limit;
$params[] = $start;
$types .= "ii";

if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();

// Get filter options - ambil DISTINCT dari kolom
$kategoriList = $conn->query("SELECT DISTINCT kategori FROM inventory WHERE kategori IS NOT NULL AND kategori != '' ORDER BY kategori");
$kantorList = $conn->query("SELECT DISTINCT kantor FROM inventory WHERE kantor IS NOT NULL AND kantor != '' ORDER BY kantor");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Kelola Aset Inventory</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding: 30px;
            background: #f5f7fa;
        }

        .page-header {
            margin-bottom: 30px;
        }

        .page-header h1 {
            color: #2d3748;
            font-size: 28px;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .page-header p {
            color: #718096;
            font-size: 14px;
        }

        .header-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }

        .btn-group {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: #64748b;
            color: white;
        }

        .btn-secondary:hover {
            background: #475569;
            transform: translateY(-2px);
        }

        .btn-success {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(17, 153, 142, 0.4);
        }

        .btn-warning {
            background: #f59e0b;
            color: white;
        }

        .btn-warning:hover {
            background: #d97706;
            transform: translateY(-2px);
        }

        .btn-danger {
            background: #ef4444;
            color: white;
        }

        .btn-danger:hover {
            background: #dc2626;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }

        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-box {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            transition: transform 0.3s;
        }

        .stat-box:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.12);
        }

        .stat-box h4 {
            font-size: 12px;
            color: #718096;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 10px;
        }

        .stat-box .value {
            font-size: 24px;
            font-weight: bold;
            color: #2d3748;
        }

        .filter-section {
            background: white;
            padding: 25px;
            border-radius: 12px;
            margin-bottom: 25px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        .filter-row {
            display: grid;
            grid-template-columns: 2fr 1fr 1fr;
            gap: 15px;
            margin-bottom: 15px;
        }

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

        .form-group label {
            font-size: 13px;
            font-weight: 600;
            color: #4a5568;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .form-control {
            padding: 10px 14px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .table-container {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        thead {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        th {
            color: white;
            padding: 15px;
            text-align: left;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        tbody tr {
            border-bottom: 1px solid #e2e8f0;
            transition: background 0.3s;
        }

        tbody tr:hover {
            background: #f7fafc;
        }

        td {
            padding: 15px;
            font-size: 14px;
            color: #4a5568;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 30px;
        }

        .pagination a, .pagination span {
            padding: 10px 15px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            text-decoration: none;
            color: #4a5568;
            transition: all 0.3s;
            font-weight: 500;
        }

        .pagination a:hover {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-color: transparent;
            transform: translateY(-2px);
        }

        .pagination .active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-color: transparent;
        }

        .no-data {
            text-align: center;
            padding: 60px 20px;
            color: #a0aec0;
        }

        .no-data i {
            font-size: 48px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        .no-data p {
            font-size: 16px;
            margin-bottom: 20px;
        }

        @media (max-width: 1024px) {
            .filter-row {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            body {
                padding: 15px;
            }

            .stats-row {
                grid-template-columns: repeat(2, 1fr);
            }

            table {
                font-size: 12px;
            }

            th, td {
                padding: 10px 8px;
            }
        }
    </style>
</head>
<body>
    <div class="page-header">
        <h1><i class="fas fa-boxes"></i> Kelola Aset</h1>
        <p>Manajemen data barang dan aset inventory ACF</p>
    </div>

    <div class="header-actions">
        <a href="javascript:history.back()" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Kembali
        </a>
        <div class="btn-group">
            <a href="tambah_barang.php" class="btn btn-success">
                <i class="fas fa-plus"></i> Tambah Barang
            </a>
        </div>
    </div>

    <!-- Statistics -->
    <div class="stats-row">
        <div class="stat-box">
            <h4>TOTAL BARANG</h4>
            <div class="value"><?php echo number_format($totalRecords); ?></div>
        </div>
        <div class="stat-box">
            <h4>TOTAL NILAI</h4>
            <div class="value" style="font-size: 16px;">
                <?php 
                $totalNilaiQuery = $conn->query("SELECT SUM(harga_perolehan) as total FROM inventory");
                $totalNilai = 0;
                if ($totalNilaiQuery && $totalNilaiQuery->num_rows > 0) {
                    $totalNilai = $totalNilaiQuery->fetch_assoc()['total'] ?? 0;
                }
                echo formatRupiah($totalNilai);
                ?>
            </div>
        </div>
        <div class="stat-box">
            <h4>KATEGORI</h4>
            <div class="value">
                <?php 
                $totalKat = $conn->query("SELECT COUNT(DISTINCT kategori) as total FROM inventory WHERE kategori IS NOT NULL AND kategori != ''")->fetch_assoc()['total'];
                echo number_format($totalKat);
                ?>
            </div>
        </div>
        <div class="stat-box">
            <h4>LOKASI KANTOR</h4>
            <div class="value">
                <?php 
                $totalKantor = $conn->query("SELECT COUNT(DISTINCT kantor) as total FROM inventory WHERE kantor IS NOT NULL AND kantor != ''")->fetch_assoc()['total'];
                echo number_format($totalKantor);
                ?>
            </div>
        </div>
    </div>

    <!-- Filter Section -->
    <div class="filter-section">
        <form method="GET" action="">
            <div class="filter-row">
                <div class="form-group">
                    <label><i class="fas fa-search"></i> Cari Barang</label>
                    <input type="text" name="search" class="form-control" placeholder="Jenis barang, kantor, deskripsi..." value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <div class="form-group">
                    <label><i class="fas fa-tags"></i> Kategori</label>
                    <select name="kategori" class="form-control">
                        <option value="">Semua Kategori</option>
                        <?php if ($kategoriList): ?>
                            <?php while($kat = $kategoriList->fetch_assoc()): ?>
                                <option value="<?php echo htmlspecialchars($kat['kategori']); ?>" 
                                    <?php echo $filter_kategori == $kat['kategori'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($kat['kategori']); ?>
                                </option>
                            <?php endwhile; ?>
                        <?php endif; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label><i class="fas fa-building"></i> Kantor</label>
                    <select name="kantor" class="form-control">
                        <option value="">Semua Kantor</option>
                        <?php if ($kantorList): ?>
                            <?php while($kant = $kantorList->fetch_assoc()): ?>
                                <option value="<?php echo htmlspecialchars($kant['kantor']); ?>" 
                                    <?php echo $filter_kantor == $kant['kantor'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($kant['kantor']); ?>
                                </option>
                            <?php endwhile; ?>
                        <?php endif; ?>
                    </select>
                </div>
            </div>
            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-filter"></i> Filter
                </button>
                <a href="kelola_barang.php" class="btn btn-warning">
                    <i class="fas fa-redo"></i> Reset
                </a>
            </div>
        </form>
    </div>

    <!-- Table -->
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th style="width: 50px;">No</th>
                    <th>Tanggal</th>
                    <th>Jenis Barang</th>
                    <th>Kategori</th>
                    <th>Sumber Dana</th>
                    <th>Kantor</th>
                    <th>Harga</th>
                    <th style="width: 150px;">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($result->num_rows > 0): ?>
                    <?php 
                    $no = $start + 1;
                    while ($row = $result->fetch_assoc()): 
                    ?>
                    <tr>
                        <td><?php echo $no++; ?></td>
                        <td><?php echo date('d/m/Y', strtotime($row['tanggal_perolehan'])); ?></td>
                        <td>
                            <strong><?php echo htmlspecialchars($row['jenis_barang']); ?></strong><br>
                            <small style="color: #64748b;">
                                <?php 
                                $desc = $row['jenis_inventory'] ?? '';
                                echo htmlspecialchars(strlen($desc) > 40 ? substr($desc, 0, 40) . '...' : $desc); 
                                ?>
                            </small>
                        </td>
                        <td><?php echo htmlspecialchars($row['kategori'] ?? '-'); ?></td>
                        <td><?php echo htmlspecialchars($row['sumber_dana'] ?? '-'); ?></td>
                        <td><?php echo htmlspecialchars($row['kantor'] ?? '-'); ?></td>
                        <td><strong><?php echo formatRupiah($row['harga_perolehan']); ?></strong></td>
                        <td>
                            <div style="display: flex; gap: 5px;">
                                <a href="detail_barang.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-primary" title="Detail">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <?php if (isset($_SESSION['user_type']) && $_SESSION['user_type'] == 'A'): ?>
                                <a href="edit_barang.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-warning" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="hapus_barang.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-danger" 
                                   onclick="return confirm('Yakin ingin menghapus barang ini?')" title="Hapus">
                                    <i class="fas fa-trash"></i>
                                </a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="8" class="no-data">
                            <i class="fas fa-inbox" style="font-size: 48px; color: #cbd5e0;"></i>
                            <p>Tidak ada data inventory</p>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <div class="pagination">
        <?php if ($page > 1): ?>
            <a href="?page=<?php echo ($page-1); ?>&search=<?php echo urlencode($search); ?>&kategori=<?php echo urlencode($filter_kategori); ?>&kantor=<?php echo urlencode($filter_kantor); ?>">
                <i class="fas fa-chevron-left"></i> Prev
            </a>
        <?php endif; ?>
        
        <?php for ($i = max(1, $page-2); $i <= min($totalPages, $page+2); $i++): ?>
            <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&kategori=<?php echo urlencode($filter_kategori); ?>&kantor=<?php echo urlencode($filter_kantor); ?>" 
               class="<?php echo $i == $page ? 'active' : ''; ?>">
                <?php echo $i; ?>
            </a>
        <?php endfor; ?>
        
        <?php if ($page < $totalPages): ?>
            <a href="?page=<?php echo ($page+1); ?>&search=<?php echo urlencode($search); ?>&kategori=<?php echo urlencode($filter_kategori); ?>&kantor=<?php echo urlencode($filter_kantor); ?>">
                Next <i class="fas fa-chevron-right"></i>
            </a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</body>
</html>