<?php
// Start session
session_start();

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

// Redirect if not borrower user - using functions from connection.php
if (!is_logged_in() || !is_user_type('borrower')) {
    header("Location: ../login.php");
    exit();
}

// Get borrower data
$borrower_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM borrower_users WHERE id = ?");
$stmt->bind_param("i", $borrower_id);
$stmt->execute();
$borrower_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Check if account is active, redirect to logout if not
if ($borrower_data['status'] == 'nonactive') {
    error_log("Nonactive borrower attempted to access check borrowing: " . $_SESSION['username']);
    $_SESSION = array();
    session_destroy();
    header("Location: ../login.php?error=inactive");
    exit();
}

// Set page title
$page_title = "Riwayat Peminjaman";

// Log activity using audit_logs
create_audit_log($conn, 'Check Borrowing', $borrower_id, 'borrower', 'borrower user checked borrowing history');

// Get borrowing history
$history_stmt = $conn->prepare("
    SELECT 
        st.*,
        bu.nama_borrower,
        COUNT(ti.id) as total_items,
        SUM(CASE WHEN ti.dikembalikan = 1 THEN 1 ELSE 0 END) as returned_items,
        MIN(ti.tanggal_kembali) as first_return_date,
        MAX(ti.tanggal_kembali) as last_return_date
    FROM stock_transactions st
    LEFT JOIN borrower_users bu ON st.borrower_id = bu.id
    LEFT JOIN transaction_items ti ON st.id = ti.transaction_id
    WHERE st.borrower_id = ?
    GROUP BY st.id
    ORDER BY st.tanggal_transaksi DESC
");
$history_stmt->bind_param("i", $borrower_id);
$history_stmt->execute();
$history_result = $history_stmt->get_result();
$history_stmt->close();

// Function to calculate week number in year
function getWeekOfYear($date) {
    return date('W', strtotime($date));
}

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

<!-- Main Content Area -->
<main class="flex-1 p-4 lg:p-6 overflow-auto bg-gradient-to-br from-green-50 via-lime-50 to-emerald-50">
    <!-- Header Section -->
    <div class="mb-6 lg:mb-8">
        <div class="flex items-center mb-4">
            <div class="p-3 rounded-full bg-gradient-to-r from-green-500 to-emerald-600 text-white mr-4">
                <i class="fas fa-history text-xl lg:text-2xl"></i>
            </div>
            <div>
                <h1 class="text-2xl lg:text-3xl font-bold text-gray-800">Riwayat Peminjaman</h1>
                <p class="text-sm lg:text-base text-gray-600">Lihat dan kelola riwayat peminjaman color panel Anda</p>
            </div>
        </div>
    </div>

    <!-- History List -->
    <div class="space-y-4 lg:space-y-6">
        <?php while ($transaction = $history_result->fetch_assoc()): ?>
            <?php
            // Calculate progress
            $progress_percentage = $transaction['total_items'] > 0 ? 
                ($transaction['returned_items'] / $transaction['total_items']) * 100 : 0;
            
            // Determine if transaction is completed
            $is_completed = $transaction['status_peminjaman'] == 'Dikembalikan';
            
            // Check if overdue
            $current_time = new DateTime();
            $return_time = new DateTime($transaction['tanggal_pengembalian']);
            $return_time->add(new DateInterval('PT15M')); // Add 15 minutes tolerance
            $is_overdue = $current_time > $return_time && !$is_completed;
            
            // Check if needs immediate return (after return time but within tolerance)
            $immediate_return_time = new DateTime($transaction['tanggal_pengembalian']);
            $needs_immediate_return = $current_time >= $immediate_return_time && $current_time <= $return_time && !$is_completed;
            ?>
            
            <div class="bg-white rounded-xl shadow-md border <?php echo $is_completed ? 'opacity-75 border-gray-300' : 'border-green-200'; ?> overflow-hidden">
                <!-- Transaction Header -->
                <div class="p-4 lg:p-6 <?php echo $is_completed ? 'bg-gray-50' : 'bg-white'; ?> border-b border-gray-200">
                    <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-3 lg:space-y-0">
                        <div class="flex-1">
                            <div class="flex items-center mb-2">
                                <h3 class="text-lg lg:text-xl font-semibold <?php echo $is_completed ? 'text-gray-600 line-through' : 'text-gray-800'; ?>">
                                    <?php echo htmlspecialchars($transaction['reservation_number']); ?>
                                </h3>
                                
                                <!-- Status badges -->
                                <div class="ml-3 flex flex-wrap gap-2">
                                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium
                                        <?php 
                                        if ($transaction['status_peminjaman'] == 'Dikembalikan') {
                                            echo 'bg-gray-100 text-gray-800';
                                        } elseif ($is_overdue) {
                                            echo 'bg-red-100 text-red-800';
                                        } elseif ($needs_immediate_return) {
                                            echo 'bg-yellow-100 text-yellow-800';
                                        } else {
                                            echo 'bg-green-100 text-green-800';
                                        }
                                        ?>">
                                        <i class="fas fa-<?php 
                                        if ($transaction['status_peminjaman'] == 'Dikembalikan') {
                                            echo 'check-circle';
                                        } elseif ($is_overdue) {
                                            echo 'exclamation-triangle';
                                        } elseif ($needs_immediate_return) {
                                            echo 'clock';
                                        } else {
                                            echo 'hourglass-half';
                                        }
                                        ?> mr-1"></i>
                                        <?php 
                                        if ($transaction['status_peminjaman'] == 'Dikembalikan') {
                                            echo 'Selesai';
                                        } elseif ($is_overdue) {
                                            echo 'Terlambat';
                                        } elseif ($needs_immediate_return) {
                                            echo 'Segera Kembalikan';
                                        } else {
                                            echo 'Dipinjam';
                                        }
                                        ?>
                                    </span>
                                </div>
                            </div>
                            
                            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 text-sm">
                                <div>
                                    <span class="text-gray-500">Tanggal Pinjam:</span>
                                    <p class="font-medium text-gray-800"><?php echo date('d/m/Y H:i', strtotime($transaction['tanggal_transaksi'])); ?></p>
                                </div>
                                <div>
                                    <span class="text-gray-500">Batas Kembali:</span>
                                    <p class="font-medium text-gray-800"><?php echo date('d/m/Y H:i', strtotime($transaction['tanggal_pengembalian'])); ?></p>
                                </div>
                                <div>
                                    <span class="text-gray-500">Total Item:</span>
                                    <p class="font-medium text-gray-800"><?php echo $transaction['total_items']; ?> item</p>
                                </div>
                                <div>
                                    <span class="text-gray-500">Progress:</span>
                                    <p class="font-medium text-gray-800"><?php echo $transaction['returned_items']; ?>/<?php echo $transaction['total_items']; ?></p>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Action Button -->
                        <div class="flex items-center space-x-3">
                            <!-- Progress Bar -->
<div class="hidden lg:block w-24">
    <div class="w-full bg-gray-200 rounded-full h-2">
        <div class="bg-green-500 h-2 rounded-full transition-all duration-300" 
             style="width: <?php echo $progress_percentage; ?>%"></div>
    </div>
    <span class="text-xs text-gray-500 mt-1"><?php echo round($progress_percentage); ?>%</span>
</div>
                            
                            <button onclick="toggleTransactionDetail('transaction-<?php echo $transaction['id']; ?>')" 
                                    class="px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-lg hover:from-green-600 hover:to-emerald-700 transition-all duration-200 text-sm font-medium">
                                <i class="fas fa-eye mr-1"></i>
                                Detail
                            </button>
                        </div>
                    </div>
                    
                    <!-- Mobile Progress Bar -->
<div class="lg:hidden mt-3">
    <div class="flex items-center justify-between text-xs text-gray-500 mb-1">
        <span>Progress Pengembalian</span>
        <span><?php echo round($progress_percentage); ?>%</span>
    </div>
    <div class="w-full bg-gray-200 rounded-full h-2">
        <div class="bg-green-500 h-2 rounded-full transition-all duration-300" 
             style="width: <?php echo $progress_percentage; ?>%"></div>
    </div>
</div>
                </div>
                
                <!-- Transaction Detail (Hidden by default) -->
                <div id="transaction-<?php echo $transaction['id']; ?>" class="hidden">
                    <div class="p-4 lg:p-6 bg-gray-50">
                        <div id="transaction-items-<?php echo $transaction['id']; ?>">
                            <!-- Items will be loaded here via AJAX -->
                            <div class="flex justify-center py-4">
                                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-green-500"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endwhile; ?>
        
        <?php if (mysqli_num_rows($history_result) == 0): ?>
            <div class="bg-white rounded-xl shadow-md p-8 text-center">
                <div class="w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
                    <i class="fas fa-inbox text-2xl text-gray-400"></i>
                </div>
                <h3 class="text-lg font-medium text-gray-800 mb-2">Belum Ada Riwayat Peminjaman</h3>
                <p class="text-gray-600 mb-4">Anda belum pernah melakukan peminjaman color panel.</p>
                <a href="formulir_isi_peminjam.php" class="inline-flex items-center px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-lg hover:from-green-600 hover:to-emerald-700 transition-all duration-200">
                    <i class="fas fa-plus mr-2"></i>
                    Mulai Peminjaman
                </a>
            </div>
        <?php endif; ?>
    </div>
</main>

<!-- Return Item Modal -->
<div id="returnModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen px-4 text-center">
        <div class="fixed inset-0 bg-black opacity-50"></div>
        <div class="relative bg-white rounded-xl max-w-md w-full p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-800">Kembalikan Item</h3>
                <button onclick="closeReturnModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div id="returnModalContent">
                <!-- Content will be loaded here -->
            </div>
        </div>
    </div>
</div>

<!-- Camera Modal -->
<div id="cameraModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen px-4 text-center">
        <div class="fixed inset-0 bg-black opacity-50"></div>
        <div class="relative bg-white rounded-xl max-w-lg w-full p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-800" id="cameraTitle">Ambil Foto</h3>
                <button onclick="closeCameraModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div class="space-y-4">
                <video id="cameraPreview" class="w-full rounded-lg" autoplay playsinline></video>
                <canvas id="cameraCanvas" class="hidden"></canvas>
                
                <div class="flex space-x-3">
                    <button onclick="capturePhoto()" class="flex-1 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
                        <i class="fas fa-camera mr-2"></i>
                        Ambil Foto
                    </button>
                    <button onclick="closeCameraModal()" class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors">
                        Batal
                    </button>
                </div>
                
                <div id="capturedPreview" class="hidden">
                    <img id="capturedImage" class="w-full rounded-lg mb-3" />
                    <div class="flex space-x-3">
                        <button onclick="confirmPhoto()" class="flex-1 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors">
                            <i class="fas fa-check mr-2"></i>
                            Gunakan Foto
                        </button>
                        <button onclick="retakePhoto()" class="px-4 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition-colors">
                            <i class="fas fa-redo mr-2"></i>
                            Foto Ulang
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Enhanced Photo Modal for viewing photos -->
<div id="photoViewModal" class="fixed inset-0 z-60 hidden overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen px-4 text-center">
        <div class="fixed inset-0 bg-black opacity-90" onclick="closePhotoViewModal()"></div>
        <div class="relative bg-white rounded-xl max-w-4xl w-full p-4 m-4">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-800" id="photoViewModalTitle">Foto</h3>
                <div class="flex items-center space-x-2">
                    <button onclick="downloadPhoto()" class="px-3 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm">
                        <i class="fas fa-download mr-1"></i>
                        Download
                    </button>
                    <button onclick="closePhotoViewModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
            </div>
            
            <div class="text-center">
                <img id="photoViewModalImage" class="max-w-full max-h-[70vh] h-auto rounded-lg mx-auto shadow-lg" alt="Foto" />
            </div>
            
            <div class="mt-4 text-center">
                <div id="photoViewModalInfo" class="mb-4 text-sm text-gray-600"></div>
                <button onclick="closePhotoViewModal()" class="px-6 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// Global variables
let currentPhotoType = '';
let currentItemId = '';
let currentStream = null;
let currentPhotoData = '';
let currentPhotoInfo = '';

// Toggle transaction detail
function toggleTransactionDetail(elementId) {
    const element = document.getElementById(elementId);
    const transactionId = elementId.split('-')[1];
    
    if (element.classList.contains('hidden')) {
        element.classList.remove('hidden');
        loadTransactionItems(transactionId);
    } else {
        element.classList.add('hidden');
    }
}

// Load transaction items via AJAX
function loadTransactionItems(transactionId) {
    const container = document.getElementById(`transaction-items-${transactionId}`);
    
    fetch('get_transaction_items_peminjam.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `transaction_id=${transactionId}`
    })
    .then(response => response.text())
    .then(data => {
        container.innerHTML = data;
    })
    .catch(error => {
        console.error('Error:', error);
        container.innerHTML = '<p class="text-red-600 text-center">Error loading items</p>';
    });
}

// Show return modal
function showReturnModal(itemId, codeBarang, componentName, colorName) {
    const modal = document.getElementById('returnModal');
    const content = document.getElementById('returnModalContent');
    
    content.innerHTML = `
        <div class="text-center mb-6">
            <div class="w-16 h-16 mx-auto mb-4 bg-green-100 rounded-full flex items-center justify-center">
                <i class="fas fa-undo text-2xl text-green-600"></i>
            </div>
            <h4 class="text-lg font-semibold text-gray-800 mb-2">${codeBarang}</h4>
            <p class="text-gray-600">${colorName} - ${componentName}</p>
        </div>
        
        <div class="space-y-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Kondisi Item</label>
                <div class="grid grid-cols-3 gap-2">
                    <button type="button" onclick="selectCondition('baik', ${itemId})" 
                            class="condition-btn px-3 py-2 border-2 border-gray-300 rounded-lg text-sm font-medium hover:border-green-500 transition-colors"
                            data-condition="baik">
                        <i class="fas fa-check-circle text-green-500 mb-1"></i>
                        <div>Baik</div>
                    </button>
                    <button type="button" onclick="selectCondition('rusak', ${itemId})" 
                            class="condition-btn px-3 py-2 border-2 border-gray-300 rounded-lg text-sm font-medium hover:border-red-500 transition-colors"
                            data-condition="rusak">
                        <i class="fas fa-tools text-red-500 mb-1"></i>
                        <div>Rusak</div>
                    </button>
                    <button type="button" onclick="selectCondition('hilang', ${itemId})" 
                            class="condition-btn px-3 py-2 border-2 border-gray-300 rounded-lg text-sm font-medium hover:border-yellow-500 transition-colors"
                            data-condition="hilang">
                        <i class="fas fa-question-circle text-yellow-500 mb-1"></i>
                        <div>Hilang</div>
                    </button>
                </div>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Catatan</label>
                <textarea id="returnNotes" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500" 
                          rows="3" placeholder="Tambahkan catatan (opsional)"></textarea>
            </div>
            
            <div class="space-y-3">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        Foto Kondisi Cat <span class="text-red-500">*</span>
                    </label>
                    <div class="flex space-x-3">
                        <button type="button" onclick="openCamera('condition', ${itemId})" 
                                class="flex-1 px-4 py-2 border-2 border-dashed border-gray-300 rounded-lg hover:border-green-500 transition-colors">
                            <i class="fas fa-camera text-gray-400 mb-1"></i>
                            <div class="text-sm text-gray-600">Ambil Foto Kondisi</div>
                        </button>
                        <div id="conditionPhotoPreview" class="hidden w-16 h-16 rounded-lg overflow-hidden border-2 border-green-500">
                            <img class="w-full h-full object-cover" />
                        </div>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        Foto Bukti Penempatan <span class="text-red-500">*</span>
                    </label>
                    <div class="flex space-x-3">
                        <button type="button" onclick="openCamera('placement', ${itemId})" 
                                class="flex-1 px-4 py-2 border-2 border-dashed border-gray-300 rounded-lg hover:border-green-500 transition-colors">
                            <i class="fas fa-camera text-gray-400 mb-1"></i>
                            <div class="text-sm text-gray-600">Ambil Foto Penempatan</div>
                        </button>
                        <div id="placementPhotoPreview" class="hidden w-16 h-16 rounded-lg overflow-hidden border-2 border-green-500">
                            <img class="w-full h-full object-cover" />
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="flex space-x-3 pt-4">
                <button onclick="closeReturnModal()" 
                        class="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                    Batal
                </button>
                <button id="confirmReturnBtn" onclick="confirmReturn(${itemId})" 
                        class="flex-1 px-4 py-2 bg-gray-400 text-white rounded-lg cursor-not-allowed transition-colors"
                        disabled>
                    Kembalikan Peminjaman
                </button>
            </div>
        </div>
    `;
    
    modal.classList.remove('hidden');
    currentItemId = itemId;
}

// Select condition
let selectedCondition = '';
let conditionPhoto = '';
let placementPhoto = '';

function selectCondition(condition, itemId) {
    selectedCondition = condition;
    
    // Update UI
    document.querySelectorAll('.condition-btn').forEach(btn => {
        btn.classList.remove('border-green-500', 'border-red-500', 'border-yellow-500', 'bg-green-50', 'bg-red-50', 'bg-yellow-50');
        btn.classList.add('border-gray-300');
    });
    
    const selectedBtn = document.querySelector(`[data-condition="${condition}"]`);
    if (condition === 'baik') {
        selectedBtn.classList.add('border-green-500', 'bg-green-50');
    } else if (condition === 'rusak') {
        selectedBtn.classList.add('border-red-500', 'bg-red-50');
    } else {
        selectedBtn.classList.add('border-yellow-500', 'bg-yellow-50');
    }
    
    checkReturnFormValid();
}

// Check if return form is valid
function checkReturnFormValid() {
    const confirmBtn = document.getElementById('confirmReturnBtn');
    
    if (selectedCondition && conditionPhoto && placementPhoto) {
        confirmBtn.disabled = false;
        confirmBtn.classList.remove('bg-gray-400', 'cursor-not-allowed');
        confirmBtn.classList.add('bg-green-500', 'hover:bg-green-600');
    } else {
        confirmBtn.disabled = true;
        confirmBtn.classList.add('bg-gray-400', 'cursor-not-allowed');
        confirmBtn.classList.remove('bg-green-500', 'hover:bg-green-600');
    }
}

// Camera functions
function openCamera(type, itemId) {
    currentPhotoType = type;
    currentItemId = itemId;
    
    const modal = document.getElementById('cameraModal');
    const title = document.getElementById('cameraTitle');
    const preview = document.getElementById('cameraPreview');
    const capturedPreview = document.getElementById('capturedPreview');
    
    title.textContent = type === 'condition' ? 'Foto Kondisi Cat' : 'Foto Bukti Penempatan';
    capturedPreview.classList.add('hidden');
    preview.classList.remove('hidden');
    
    modal.classList.remove('hidden');
    
    // Start camera
    navigator.mediaDevices.getUserMedia({ 
        video: { 
            facingMode: 'environment',  // Use back camera on mobile
            width: { ideal: 1280 },
            height: { ideal: 720 }
        } 
    })
    .then(stream => {
        currentStream = stream;
        preview.srcObject = stream;
    })
    .catch(err => {
        console.error('Error accessing camera:', err);
        alert('Tidak dapat mengakses kamera. Pastikan izin kamera telah diberikan.');
        closeCameraModal();
    });
}

function capturePhoto() {
    const video = document.getElementById('cameraPreview');
    const canvas = document.getElementById('cameraCanvas');
    const capturedImage = document.getElementById('capturedImage');
    const capturedPreview = document.getElementById('capturedPreview');
    
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    
    const ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0);
    
    const dataUrl = canvas.toDataURL('image/jpeg', 0.8);
    capturedImage.src = dataUrl;
    
    video.classList.add('hidden');
    capturedPreview.classList.remove('hidden');
}

function retakePhoto() {
    const video = document.getElementById('cameraPreview');
    const capturedPreview = document.getElementById('capturedPreview');
    
    video.classList.remove('hidden');
    capturedPreview.classList.add('hidden');
}

function confirmPhoto() {
    const capturedImage = document.getElementById('capturedImage');
    const dataUrl = capturedImage.src;
    
    if (currentPhotoType === 'condition') {
        conditionPhoto = dataUrl;
        const preview = document.getElementById('conditionPhotoPreview');
        preview.querySelector('img').src = dataUrl;
        preview.classList.remove('hidden');
    } else {
        placementPhoto = dataUrl;
        const preview = document.getElementById('placementPhotoPreview');
        preview.querySelector('img').src = dataUrl;
        preview.classList.remove('hidden');
    }
    
    checkReturnFormValid();
    closeCameraModal();
}

function closeCameraModal() {
    const modal = document.getElementById('cameraModal');
    modal.classList.add('hidden');
    
    if (currentStream) {
        currentStream.getTracks().forEach(track => track.stop());
        currentStream = null;
    }
}

// Confirm return
function confirmReturn(itemId) {
    const notes = document.getElementById('returnNotes').value;
    
    if (!selectedCondition || !conditionPhoto || !placementPhoto) {
        alert('Harap lengkapi semua data terlebih dahulu');
        return;
    }
    
    // Show loading
    const confirmBtn = document.getElementById('confirmReturnBtn');
    confirmBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Memproses...';
    confirmBtn.disabled = true;
    
    // Send return request
    fetch('process_return_peminjam.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `item_id=${itemId}&condition=${selectedCondition}&notes=${encodeURIComponent(notes)}&condition_photo=${encodeURIComponent(conditionPhoto)}&placement_photo=${encodeURIComponent(placementPhoto)}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            closeReturnModal();
            // Reload the page to show updated status
            location.reload();
        } else {
            alert('Error: ' + data.message);
            confirmBtn.innerHTML = 'Kembalikan Peminjaman';
            confirmBtn.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Terjadi kesalahan saat memproses pengembalian');
        confirmBtn.innerHTML = 'Kembalikan Peminjaman';
        confirmBtn.disabled = false;
    });
}

function closeReturnModal() {
    const modal = document.getElementById('returnModal');
    modal.classList.add('hidden');
    
    // Reset form
    selectedCondition = '';
    conditionPhoto = '';
    placementPhoto = '';
}

// Enhanced photo viewing functions
function showPhotoViewModal(photoData, title, info = '') {
    const modal = document.getElementById('photoViewModal');
    const titleElement = document.getElementById('photoViewModalTitle');
    const imageElement = document.getElementById('photoViewModalImage');
    const infoElement = document.getElementById('photoViewModalInfo');
    
    titleElement.textContent = title;
    imageElement.src = photoData;
    infoElement.textContent = info;
    
    currentPhotoData = photoData;
    currentPhotoInfo = `${title} - ${info}`;
    
    modal.classList.remove('hidden');
}

function closePhotoViewModal() {
    const modal = document.getElementById('photoViewModal');
    modal.classList.add('hidden');
    currentPhotoData = '';
    currentPhotoInfo = '';
}

function downloadPhoto() {
    if (!currentPhotoData) {
        alert('Tidak ada foto untuk didownload');
        return;
    }
    
    try {
        // Create download link
        const link = document.createElement('a');
        link.href = currentPhotoData;
        
        // Generate filename with timestamp
        const now = new Date();
        const timestamp = now.toISOString().slice(0, 19).replace(/[:.]/g, '-');
        const filename = `foto_${currentPhotoInfo.replace(/[^a-zA-Z0-9]/g, '_')}_${timestamp}.jpg`;
        
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    } catch (error) {
        console.error('Error downloading photo:', error);
        alert('Gagal mendownload foto');
    }
}

// Global function for viewing photos (called from transaction items)
window.showPhotoModal = function(photoData, title, codeBarang = '', returnDate = '') {
    let info = '';
    if (codeBarang && returnDate) {
        info = `${codeBarang} - ${returnDate}`;
    } else if (codeBarang) {
        info = codeBarang;
    }
    
    showPhotoViewModal(photoData, title, info);
};
</script>

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