<?php
session_start();

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

/* =========================
   2. DATABASE CONNECTION
========================= */
$koneksiPath = '';
$possiblePaths = [
    __DIR__ . '/../../DataBase/koneksi.php',
    __DIR__ . '/../../database/koneksi.php',
    __DIR__ . '/../../db/koneksi.php',
    __DIR__ . '/../DataBase/koneksi.php',
    __DIR__ . '/../database/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");
}

require_once $koneksiPath;

if (!$conn) {
    die("Koneksi database gagal!");
}

/* =========================
   3. CSRF TOKEN
========================= */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/* =========================
   4. GET FILTER PARAMETER
========================= */
$filter_kantor = $_GET['kantor'] ?? '';
$filter_status = $_GET['status'] ?? '';
$search = $_GET['search'] ?? '';

// Pagination
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

/* =========================
   5. BUILD QUERY
========================= */
$where = [];
$params = [];
$types = '';

if ($filter_status !== '') {
    $where[] = "status = ?";
    $params[] = $filter_status;
    $types .= 's';
}

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

if ($search !== '') {
    $where[] = "(kode_aset LIKE ? OR kode_aset_auto LIKE ? OR jenis_barang LIKE ?)";
    $like = "%$search%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $types .= 'sss';
}

$whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

// Get total count
$countSql = "SELECT COUNT(*) as total FROM inventory $whereClause";
if (!empty($params)) {
    $countStmt = $conn->prepare($countSql);
    $countStmt->bind_param($types, ...$params);
    $countStmt->execute();
    $countResult = $countStmt->get_result();
    $totalRows = $countResult->fetch_assoc()['total'];
} else {
    $totalRows = $conn->query($countSql)->fetch_assoc()['total'];
}

$totalPages = ceil($totalRows / $perPage);

// Get paginated data
$sql = "SELECT id, kode_aset, kode_aset_auto, jenis_barang, kantor, status, kategori, sumber_dana, merk, foto
        FROM inventory $whereClause 
        ORDER BY id DESC 
        LIMIT ? OFFSET ?";

$limitParams = $params;
$limitParams[] = $perPage;
$limitParams[] = $offset;
$limitTypes = $types . 'ii';

$stmt = $conn->prepare($sql);
if (!empty($limitParams)) {
    $stmt->bind_param($limitTypes, ...$limitParams);
}
$stmt->execute();
$result = $stmt->get_result();

/* =========================
   7. DATA DROPDOWN
========================= */
$result_kantor = $conn->query("
    SELECT DISTINCT kantor 
    FROM inventory 
    WHERE kantor IS NOT NULL AND kantor != ''
    ORDER BY kantor
");

/* =========================
   8. CEK KODE ASET KOSONG
========================= */
$check_missing = $conn->query("
    SELECT COUNT(*) AS total
    FROM inventory
    WHERE 
        (kode_aset IS NULL OR kode_aset = '')
        AND
        (kode_aset_auto IS NULL OR kode_aset_auto = '')
");
$missing_count = $check_missing->fetch_assoc()['total'];
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Panel Cetak Label - 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;
            --light: #CDE8E5;
            --lightest: #EEF7FF;
            --dark: #2d3748;
            --gray: #64748b;
            --border: #e2e8f0;
        }

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

        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            padding: 20px;
            color: var(--dark);
        }

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

        /* Header */
        .page-header {
            background: white;
            padding: 30px;
            border-radius: 12px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border-left: 6px solid var(--primary);
        }

        .page-header h1 {
            color: var(--dark);
            font-size: 28px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

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

        .page-subtitle {
            color: var(--gray);
            font-size: 14px;
        }

        /* Alert */
        .alert {
            padding: 16px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 600;
        }

        .alert-warning {
            background: #fef3c7;
            color: #854d0e;
            border-left: 4px solid #f59e0b;
        }

        .alert-info {
            background: #dbeafe;
            color: #1e40af;
            border-left: 4px solid #3b82f6;
        }

        /* Filters */
        .filters {
            background: white;
            padding: 24px;
            border-radius: 12px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .filter-grid {
            display: grid;
            grid-template-columns: 2fr 1fr 1fr auto;
            gap: 16px;
            align-items: end;
        }

        .filter-group label {
            display: block;
            font-size: 12px;
            font-weight: 700;
            color: var(--gray);
            text-transform: uppercase;
            margin-bottom: 8px;
            letter-spacing: 0.5px;
        }

        .filter-input, .filter-select {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid var(--border);
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.2s;
        }

        .filter-input:focus, .filter-select:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(122, 178, 178, 0.1);
        }

        /* Stats */
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
        }

        .stat-icon.primary { background: var(--lightest); color: var(--primary); }
        .stat-icon.success { background: #d1fae5; color: #059669; }

        .stat-info h3 {
            font-size: 28px;
            font-weight: 700;
            color: var(--dark);
        }

        .stat-info p {
            font-size: 13px;
            color: var(--gray);
        }

        /* Items Grid */
        .items-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }

        .item-card {
            background: white;
            border-radius: 12px;
            padding: 16px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: all 0.3s;
            border: 2px solid transparent;
        }

        .item-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 16px rgba(0,0,0,0.15);
            border-color: var(--primary);
        }

        .item-card.selected {
            border-color: var(--primary);
            background: var(--lightest);
        }

        .item-header {
            display: flex;
            align-items: start;
            gap: 12px;
            margin-bottom: 12px;
        }

        .item-checkbox {
            width: 20px;
            height: 20px;
            cursor: pointer;
            accent-color: var(--primary);
        }

        .item-photo {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            object-fit: cover;
            border: 2px solid var(--border);
        }

        .item-placeholder {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            background: var(--border);
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--gray);
            font-size: 24px;
        }

        .item-details {
            flex: 1;
        }

        .item-name {
            font-size: 16px;
            font-weight: 700;
            color: var(--dark);
            margin-bottom: 6px;
            line-height: 1.3;
        }

        .item-info {
            font-size: 12px;
            color: var(--gray);
            margin-bottom: 4px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .item-info i {
            width: 14px;
            color: var(--primary);
        }

        .status-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 10px;
            font-weight: 700;
            text-transform: uppercase;
        }

        .status-aktif { background: #d1fae5; color: #065f46; }
        .status-nonaktif { background: #fee2e2; color: #991b1b; }

        /* Buttons */
        .btn {
            padding: 12px 24px;
            border-radius: 8px;
            border: none;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }

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

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

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

        .btn-secondary:hover {
            border-color: var(--primary);
            color: var(--primary);
        }

        /* Action Bar */
        .action-bar {
            background: white;
            padding: 20px 24px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            position: sticky;
            top: 20px;
            z-index: 100;
        }

        .selection-info {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .selection-count {
            font-size: 16px;
            font-weight: 700;
            color: var(--dark);
        }

        .selection-count strong {
            color: var(--primary);
            font-size: 20px;
        }

        /* Pagination */
        .pagination-wrapper {
            background: white;
            padding: 20px 24px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .pagination-info {
            color: var(--gray);
            font-size: 14px;
        }

        .pagination-info strong {
            color: var(--dark);
            font-weight: 700;
        }

        .pagination {
            display: flex;
            gap: 8px;
        }

        .page-btn {
            min-width: 40px;
            height: 40px;
            padding: 0 12px;
            border: 2px solid var(--border);
            background: white;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }

        .page-btn:hover:not(:disabled) {
            border-color: var(--primary);
            color: var(--primary);
        }

        .page-btn.active {
            background: var(--primary);
            border-color: var(--primary);
            color: white;
        }

        .page-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* Empty State */
        .empty-state {
            background: white;
            padding: 60px 20px;
            border-radius: 12px;
            text-align: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .empty-state i {
            font-size: 64px;
            color: var(--border);
            margin-bottom: 16px;
        }

        .empty-state h3 {
            font-size: 20px;
            color: var(--dark);
            margin-bottom: 8px;
        }

        .empty-state p {
            color: var(--gray);
        }

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

            .items-grid {
                grid-template-columns: 1fr;
            }

            .action-bar {
                flex-direction: column;
                gap: 12px;
            }

            .pagination-wrapper {
                flex-direction: column;
                gap: 16px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="page-header">
            <h1><i class="fas fa-print"></i> Panel Cetak Label</h1>
            <p class="page-subtitle">Pilih item yang ingin dicetak labelnya</p>
        </div>

        <!-- Warning if missing codes -->
        <?php if ($missing_count > 0): ?>
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle"></i>
                <span><strong><?= $missing_count ?></strong> item belum memiliki kode aset</span>
            </div>
        <?php endif; ?>

        <!-- Filters -->
        <div class="filters">
            <form method="GET" id="filterForm">
                <div class="filter-grid">
                    <div class="filter-group">
                        <label><i class="fas fa-search"></i> Pencarian</label>
                        <input type="text" name="search" class="filter-input" placeholder="Cari kode atau nama barang..." value="<?= htmlspecialchars($search) ?>">
                    </div>
                    
                    <div class="filter-group">
                        <label><i class="fas fa-map-marker-alt"></i> Kantor</label>
                        <select name="kantor" class="filter-select">
                            <option value="">Semua Kantor</option>
                            <?php while ($k = $result_kantor->fetch_assoc()): ?>
                                <option value="<?= htmlspecialchars($k['kantor']) ?>" <?= $filter_kantor === $k['kantor'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($k['kantor']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label><i class="fas fa-tag"></i> Status</label>
                        <select name="status" class="filter-select">
                            <option value="">Semua Status</option>
                            <option value="aktif" <?= $filter_status === 'aktif' ? 'selected' : '' ?>>Aktif</option>
                            <option value="nonaktif" <?= $filter_status === 'nonaktif' ? 'selected' : '' ?>>Nonaktif</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-filter"></i> Filter
                    </button>
                </div>
            </form>
        </div>

        <!-- Stats -->
        <div class="stats">
            <div class="stat-card">
                <div class="stat-icon primary">
                    <i class="fas fa-box"></i>
                </div>
                <div class="stat-info">
                    <h3><?= $totalRows ?></h3>
                    <p>Total Item</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon success">
                    <i class="fas fa-check-square"></i>
                </div>
                <div class="stat-info">
                    <h3 id="selectedCount">0</h3>
                    <p>Dipilih</p>
                </div>
            </div>
        </div>

        <!-- Action Bar -->
        <form action="cetak_label_massal.php" method="POST" target="_blank" id="printForm">
            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
            
            <div class="action-bar">
                <div class="selection-info">
                    <button type="button" class="btn btn-secondary" onclick="selectAll()">
                        <i class="fas fa-check-double"></i> Pilih Semua
                    </button>
                    <button type="button" class="btn btn-secondary" onclick="deselectAll()">
                        <i class="fas fa-times"></i> Batal Pilih
                    </button>
                </div>
                <button type="submit" class="btn btn-primary" id="printBtn" disabled>
                    <i class="fas fa-print"></i> Cetak <span id="printCount">0</span> Label
                </button>
            </div>

            <!-- Items Grid -->
            <?php if ($result->num_rows > 0): ?>
                <div class="items-grid">
                    <?php while ($row = $result->fetch_assoc()): 
                        $kode = $row['kode_aset'] ?: $row['kode_aset_auto'] ?: 'BELUM ADA KODE';
                        $merk = $row['merk'] ?? '';
                        $hasCode = ($row['kode_aset'] || $row['kode_aset_auto']);
                    ?>
                        <div class="item-card" data-id="<?= $row['id'] ?>">
                            <div class="item-header">
                                <input type="checkbox" 
                                       name="ids[]" 
                                       value="<?= $row['id'] ?>" 
                                       class="item-checkbox"
                                       <?= !$hasCode ? 'disabled title="Belum memiliki kode"' : '' ?>
                                       onchange="updateSelection()">
                                
                                <?php if (!empty($row['foto']) && file_exists(__DIR__ . '/../../uploads/inventory/' . $row['foto'])): ?>
                                    <img src="../../uploads/inventory/<?= htmlspecialchars($row['foto']) ?>" class="item-photo" alt="Foto">
                                <?php else: ?>
                                    <div class="item-placeholder">
                                        <i class="fas fa-image"></i>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="item-details">
                                    <div class="item-name"><?= htmlspecialchars($row['jenis_barang']) ?></div>
                                    <div class="item-info">
                                        <i class="fas fa-barcode"></i>
                                        <strong><?= htmlspecialchars($kode) ?></strong>
                                    </div>
                                    <?php if ($merk): ?>
                                        <div class="item-info">
                                            <i class="fas fa-tag"></i>
                                            <?= htmlspecialchars($merk) ?>
                                        </div>
                                    <?php endif; ?>
                                    <div class="item-info">
                                        <i class="fas fa-map-marker-alt"></i>
                                        <?= htmlspecialchars($row['kantor']) ?>
                                    </div>
                                    <span class="status-badge status-<?= $row['status'] ?>">
                                        <?= htmlspecialchars($row['status']) ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                    <?php endwhile; ?>
                </div>
            <?php else: ?>
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <h3>Tidak Ada Data</h3>
                    <p>Tidak ada item yang sesuai dengan filter yang dipilih</p>
                </div>
            <?php endif; ?>
        </form>

        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
            <div class="pagination-wrapper">
                <div class="pagination-info">
                    Menampilkan <strong><?= min($offset + 1, $totalRows) ?></strong> - <strong><?= min($offset + $perPage, $totalRows) ?></strong> dari <strong><?= $totalRows ?></strong> item
                </div>
                <div class="pagination">
                    <button class="page-btn" <?= $page <= 1 ? 'disabled' : '' ?> onclick="goToPage(<?= $page - 1 ?>)">
                        <i class="fas fa-chevron-left"></i>
                    </button>
                    
                    <?php
                    for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++):
                    ?>
                        <button class="page-btn <?= $i === $page ? 'active' : '' ?>" onclick="goToPage(<?= $i ?>)">
                            <?= $i ?>
                        </button>
                    <?php endfor; ?>
                    
                    <button class="page-btn" <?= $page >= $totalPages ? 'disabled' : '' ?> onclick="goToPage(<?= $page + 1 ?>)">
                        <i class="fas fa-chevron-right"></i>
                    </button>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function updateSelection() {
            const checkboxes = document.querySelectorAll('.item-checkbox:checked');
            const count = checkboxes.length;
            
            document.getElementById('selectedCount').textContent = count;
            document.getElementById('printCount').textContent = count;
            document.getElementById('printBtn').disabled = count === 0;
            
            // Update card styling
            document.querySelectorAll('.item-card').forEach(card => {
                const checkbox = card.querySelector('.item-checkbox');
                if (checkbox && checkbox.checked) {
                    card.classList.add('selected');
                } else {
                    card.classList.remove('selected');
                }
            });
        }

        function selectAll() {
            document.querySelectorAll('.item-checkbox:not(:disabled)').forEach(cb => {
                cb.checked = true;
            });
            updateSelection();
        }

        function deselectAll() {
            document.querySelectorAll('.item-checkbox').forEach(cb => {
                cb.checked = false;
            });
            updateSelection();
        }

        function goToPage(page) {
            const form = document.getElementById('filterForm');
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'page';
            input.value = page;
            form.appendChild(input);
            form.submit();
        }

        // Validate before submit
        document.getElementById('printForm').addEventListener('submit', function(e) {
            const count = document.querySelectorAll('.item-checkbox:checked').length;
            if (count === 0) {
                e.preventDefault();
                alert('Pilih minimal 1 item untuk dicetak');
                return false;
            }
            return true;
        });

        // Initialize
        updateSelection();
    </script>
</body>
</html>

<?php
$stmt->close();
$conn->close();
?>