<?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
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'] : '';

// Get unique locations for filter dropdown
$lokasi_query = "SELECT DISTINCT lokasi_posisi FROM borrower_users 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>
        
        <div class="grid grid-cols-1 md:grid-cols-3 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>

            <!-- 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>
    </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>
// Load data on page load
document.addEventListener('DOMContentLoaded', function() {
    loadHistoryData();
});

// Real-time search for NIK
let searchTimeout;
document.getElementById('search_nik').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(function() {
        loadHistoryData();
    }, 500);
});

// Load history data with AJAX
function loadHistoryData() {
    const lokasi = document.getElementById('filter_lokasi').value;
    const nik = document.getElementById('search_nik').value;
    
    const params = new URLSearchParams();
    if (lokasi) params.append('lokasi_posisi', lokasi);
    if (nik) params.append('search_nik', nik);
    
    fetch('ajax_history_pengembalian.php?' + params.toString())
        .then(response => response.text())
        .then(data => {
            document.getElementById('history-table-container').innerHTML = data;
        })
        .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>';
        });
}

// Apply filters
function applyFilters() {
    loadHistoryData();
}

// Reset filters
function resetFilters() {
    document.getElementById('filter_lokasi').value = '';
    document.getElementById('search_nik').value = '';
    loadHistoryData();
}

// 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'; ?>