<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Redirect if not IT user
if (!is_logged_in() || !is_user_type('it')) {
    header("Location: ../login.php");
    exit();
}

// Get IT user data
$it_id = $_SESSION['user_id'];

// Set page title
$page_title = "History Pengembalian Barang";

// Log activity using audit_logs_semarang
create_audit_log($conn, 'History Access', $it_id, 'it', 'IT user accessed history pengembalian barang');

// Get filter parameters
$filter_lokasi = isset($_GET['lokasi_posisi']) ? $_GET['lokasi_posisi'] : '';
$search_nik = isset($_GET['search_nik']) ? $_GET['search_nik'] : '';
$filter_kondisi = isset($_GET['kondisi_kembali']) ? $_GET['kondisi_kembali'] : '';

// Get unique locations for filter dropdown
$lokasi_query = "SELECT DISTINCT lokasi_posisi FROM borrower_users_semarang WHERE status = 'active' ORDER BY lokasi_posisi";
$lokasi_result = $conn->query($lokasi_query);

// Include header
include '../template_it/header.php';
?>

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">
    <!-- Page Header -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">History Pengembalian Barang</h2>
        <p class="text-gray-600">Lihat riwayat pengembalian barang beserta foto bukti dan dokumentasi</p>
    </div>

    <!-- Filter Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Filter & Pencarian</h3>
        
        <!-- Quick Stats -->
        <div id="quick-stats" class="grid grid-cols-3 gap-4 mb-6">
            <!-- Stats will be loaded here -->
        </div>

        <!-- Quick Filter Buttons -->
        <div class="flex flex-wrap gap-2 mb-4">
            <button onclick="quickFilterKondisi('')" class="px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm hover:bg-gray-200 transition-colors" id="btn-semua">
                Semua Kondisi
            </button>
            <button onclick="quickFilterKondisi('Baik')" class="px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm hover:bg-green-200 transition-colors" id="btn-baik">
                ✓ Baik
            </button>
            <button onclick="quickFilterKondisi('Rusak')" class="px-3 py-1 bg-red-100 text-red-700 rounded-full text-sm hover:bg-red-200 transition-colors" id="btn-rusak">
                ⚠ Rusak
            </button>
            <button onclick="quickFilterKondisi('Hilang')" class="px-3 py-1 bg-yellow-100 text-yellow-700 rounded-full text-sm hover:bg-yellow-200 transition-colors" id="btn-hilang">
                ⚡ Hilang
            </button>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <!-- Filter Lokasi Posisi -->
            <div>
                <label for="filter_lokasi" class="block text-sm font-medium text-gray-700 mb-2">Filter Lokasi Posisi</label>
                <select id="filter_lokasi" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">Semua Lokasi</option>
                    <?php while($lokasi_row = $lokasi_result->fetch_assoc()): ?>
                        <option value="<?php echo htmlspecialchars($lokasi_row['lokasi_posisi']); ?>" 
                                <?php echo ($filter_lokasi == $lokasi_row['lokasi_posisi']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($lokasi_row['lokasi_posisi']); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <!-- Search NIK -->
            <div>
                <label for="search_nik" class="block text-sm font-medium text-gray-700 mb-2">Cari berdasarkan NIK</label>
                <input type="text" id="search_nik" placeholder="Masukkan NIK peminjam..." 
                       value="<?php echo htmlspecialchars($search_nik); ?>"
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <!-- Filter Kondisi -->
            <div>
                <label for="filter_kondisi" class="block text-sm font-medium text-gray-700 mb-2">Filter Kondisi Barang</label>
                <select id="filter_kondisi" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">Semua Kondisi</option>
                    <option value="Baik" <?php echo ($filter_kondisi == 'Baik') ? 'selected' : ''; ?>>
                        <span class="text-green-600">✓ Baik</span>
                    </option>
                    <option value="Rusak" <?php echo ($filter_kondisi == 'Rusak') ? 'selected' : ''; ?>>
                        <span class="text-red-600">⚠ Rusak</span>
                    </option>
                    <option value="Hilang" <?php echo ($filter_kondisi == 'Hilang') ? 'selected' : ''; ?>>
                        <span class="text-yellow-600">⚡ Hilang</span>
                    </option>
                </select>
            </div>

            <!-- Action Buttons -->
            <div class="flex items-end space-x-2">
                <button onclick="applyFilters()" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors">
                    <i class="fas fa-search mr-2"></i>Filter
                </button>
                <button onclick="resetFilters()" class="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 transition-colors">
                    <i class="fas fa-refresh mr-2"></i>Reset
                </button>
            </div>
        </div>
    </div>

    <!-- History Table -->
    <div class="bg-white rounded-lg shadow-md">
        <div class="p-6 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800">Data History Pengembalian</h3>
        </div>
        
        <div class="overflow-x-auto">
            <div id="history-table-container">
                <!-- Table content will be loaded here -->
                <div class="flex justify-center items-center p-8">
                    <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                    <span class="ml-2 text-gray-600">Memuat data...</span>
                </div>
            </div>
        </div>
        
        <!-- Pagination Container -->
        <div id="pagination-container" class="p-4 border-t border-gray-200">
            <!-- Pagination will be loaded here -->
        </div>
    </div>
</main>

<!-- Photo Modal -->
<div id="photoModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-lg max-w-4xl max-h-full overflow-auto">
            <div class="p-4 border-b border-gray-200 flex justify-between items-center">
                <h3 id="modalTitle" class="text-lg font-semibold text-gray-800"></h3>
                <button onclick="closePhotoModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div class="p-4">
                <img id="modalImage" src="" alt="" class="max-w-full h-auto">
            </div>
            <div class="p-4 border-t border-gray-200">
                <p id="modalDescription" class="text-gray-600"></p>
            </div>
        </div>
    </div>
</div>

<script>
// Current page tracking
let currentPage = 1;

// Load data on page load
document.addEventListener('DOMContentLoaded', function() {
    loadHistoryData();
    loadQuickStats();
});

// Real-time search for NIK
let searchTimeout;
document.getElementById('search_nik').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(function() {
        currentPage = 1; // Reset to first page on search
        loadHistoryData();
        loadQuickStats();
    }, 500);
});

// Load history data with AJAX
function loadHistoryData(page = currentPage) {
    const lokasi = document.getElementById('filter_lokasi').value;
    const nik = document.getElementById('search_nik').value;
    const kondisi = document.getElementById('filter_kondisi').value;
    
    const params = new URLSearchParams();
    if (lokasi) params.append('lokasi_posisi', lokasi);
    if (nik) params.append('search_nik', nik);
    if (kondisi) params.append('kondisi_kembali', kondisi);
    params.append('page', page);
    params.append('limit', 25); // 25 data per halaman
    
    // Show loading
    document.getElementById('history-table-container').innerHTML = 
        '<div class="flex justify-center items-center p-8">' +
        '<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>' +
        '<span class="ml-2 text-gray-600">Memuat data...</span>' +
        '</div>';
    
    fetch('ajax_history_pengembalian.php?' + params.toString())
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('history-table-container').innerHTML = data.html;
                generatePagination(data.totalPages, data.currentPage, data.totalData);
                currentPage = data.currentPage;
            } else {
                document.getElementById('history-table-container').innerHTML = 
                    '<div class="p-8 text-center text-red-600">Terjadi kesalahan: ' + data.message + '</div>';
                document.getElementById('pagination-container').innerHTML = '';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('history-table-container').innerHTML = 
                '<div class="p-8 text-center text-red-600">Terjadi kesalahan saat memuat data</div>';
            document.getElementById('pagination-container').innerHTML = '';
        });
}

// Quick filter for kondisi
function quickFilterKondisi(kondisi) {
    document.getElementById('filter_kondisi').value = kondisi;
    currentPage = 1;
    loadHistoryData();
    loadQuickStats();
    
    // Update button styles
    document.querySelectorAll('[id^="btn-"]').forEach(btn => {
        btn.classList.remove('ring-2', 'ring-blue-500');
    });
    
    const btnId = kondisi === '' ? 'btn-semua' : 'btn-' + kondisi.toLowerCase();
    document.getElementById(btnId).classList.add('ring-2', 'ring-blue-500');
}

// Generate pagination HTML
function generatePagination(totalPages, currentPage, totalData) {
    if (totalPages <= 1) {
        document.getElementById('pagination-container').innerHTML = 
            '<div class="text-sm text-gray-600">Total: ' + totalData + ' data</div>';
        return;
    }
    
    let paginationHtml = '<div class="flex flex-col sm:flex-row justify-between items-center space-y-2 sm:space-y-0">';
    
    // Info text
    const startItem = ((currentPage - 1) * 25) + 1;
    const endItem = Math.min(currentPage * 25, totalData);
    paginationHtml += '<div class="text-sm text-gray-600">';
    paginationHtml += 'Menampilkan ' + startItem + ' - ' + endItem + ' dari ' + totalData + ' data';
    paginationHtml += '</div>';
    
    // Pagination buttons
    paginationHtml += '<div class="flex items-center space-x-1">';
    
    // Previous button
    if (currentPage > 1) {
        paginationHtml += '<button onclick="goToPage(' + (currentPage - 1) + ')" class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors">';
        paginationHtml += '<i class="fas fa-chevron-left"></i>';
        paginationHtml += '</button>';
    }
    
    // Page numbers
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
    
    // Adjust start page if we're near the end
    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }
    
    // First page if not visible
    if (startPage > 1) {
        paginationHtml += '<button onclick="goToPage(1)" class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors">1</button>';
        if (startPage > 2) {
            paginationHtml += '<span class="px-2 text-gray-500">...</span>';
        }
    }
    
    // Visible page numbers
    for (let i = startPage; i <= endPage; i++) {
        if (i === currentPage) {
            paginationHtml += '<button class="px-3 py-1 bg-blue-600 text-white rounded">' + i + '</button>';
        } else {
            paginationHtml += '<button onclick="goToPage(' + i + ')" class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors">' + i + '</button>';
        }
    }
    
    // Last page if not visible
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            paginationHtml += '<span class="px-2 text-gray-500">...</span>';
        }
        paginationHtml += '<button onclick="goToPage(' + totalPages + ')" class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors">' + totalPages + '</button>';
    }
    
    // Next button
    if (currentPage < totalPages) {
        paginationHtml += '<button onclick="goToPage(' + (currentPage + 1) + ')" class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors">';
        paginationHtml += '<i class="fas fa-chevron-right"></i>';
        paginationHtml += '</button>';
    }
    
    paginationHtml += '</div></div>';
    
    document.getElementById('pagination-container').innerHTML = paginationHtml;
}

// Go to specific page
function goToPage(page) {
    currentPage = page;
    loadHistoryData(page);
}

// Apply filters
function applyFilters() {
    currentPage = 1; // Reset to first page
    loadHistoryData();
    loadQuickStats();
}

// Reset filters
function resetFilters() {
    document.getElementById('filter_lokasi').value = '';
    document.getElementById('search_nik').value = '';
    document.getElementById('filter_kondisi').value = '';
    currentPage = 1; // Reset to first page
    loadHistoryData();
    loadQuickStats();
}

// Load quick statistics
function loadQuickStats() {
    const lokasi = document.getElementById('filter_lokasi').value;
    const nik = document.getElementById('search_nik').value;
    const kondisi = document.getElementById('filter_kondisi').value;
    
    const params = new URLSearchParams();
    if (lokasi) params.append('lokasi_posisi', lokasi);
    if (nik) params.append('search_nik', nik);
    if (kondisi) params.append('kondisi_kembali', kondisi);
    params.append('stats_only', '1');
    
    fetch('ajax_history_pengembalian.php?' + params.toString())
        .then(response => response.json())
        .then(data => {
            if (data.success && data.stats) {
                let statsHtml = `
                    <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <div class="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                                    <i class="fas fa-check text-green-600"></i>
                                </div>
                            </div>
                            <div class="ml-3">
                                <p class="text-sm font-medium text-green-800">Kondisi Baik</p>
                                <p class="text-2xl font-bold text-green-900">${data.stats.baik}</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <div class="w-8 h-8 bg-red-100 rounded-full flex items-center justify-center">
                                    <i class="fas fa-exclamation-triangle text-red-600"></i>
                                </div>
                            </div>
                            <div class="ml-3">
                                <p class="text-sm font-medium text-red-800">Kondisi Rusak</p>
                                <p class="text-2xl font-bold text-red-900">${data.stats.rusak}</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <div class="w-8 h-8 bg-yellow-100 rounded-full flex items-center justify-center">
                                    <i class="fas fa-question-circle text-yellow-600"></i>
                                </div>
                            </div>
                            <div class="ml-3">
                                <p class="text-sm font-medium text-yellow-800">Kondisi Hilang</p>
                                <p class="text-2xl font-bold text-yellow-900">${data.stats.hilang}</p>
                            </div>
                        </div>
                    </div>
                `;
                document.getElementById('quick-stats').innerHTML = statsHtml;
            }
        })
        .catch(error => {
            console.error('Error loading stats:', error);
        });
}

// Show photo modal
function showPhoto(imageSrc, title, description) {
    document.getElementById('modalImage').src = imageSrc;
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalDescription').textContent = description;
    document.getElementById('photoModal').classList.remove('hidden');
}

// Close photo modal
function closePhotoModal() {
    document.getElementById('photoModal').classList.add('hidden');
}

// Close modal when clicking outside
document.getElementById('photoModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closePhotoModal();
    }
});
</script>

<?php include '../template_it/footer.php'; ?>