<?php
// Start session
session_start();

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

// Check if user is logged in and is borrower
if (!is_logged_in() || !is_user_type('borrower')) {
    http_response_code(403);
    exit('Unauthorized');
}

// Get transaction ID from POST
$transaction_id = isset($_POST['transaction_id']) ? intval($_POST['transaction_id']) : 0;

if (!$transaction_id) {
    http_response_code(400);
    exit('Invalid transaction ID');
}

// Verify the transaction belongs to the current borrower
$verify_stmt = $conn->prepare("SELECT id FROM stock_transactions WHERE id = ? AND borrower_id = ?");
$verify_stmt->bind_param("ii", $transaction_id, $_SESSION['user_id']);
$verify_stmt->execute();
if (!$verify_stmt->get_result()->fetch_assoc()) {
    http_response_code(403);
    exit('Access denied');
}
$verify_stmt->close();

// Get transaction items with detailed information
$items_stmt = $conn->prepare("
    SELECT 
        ti.*,
        csi.kode_barang,
        csi.rack_no,
        csi.lokasi,
        cc.component_name,
        mcp.code_color,
        mcp.deskripsi as color_description,
        b.nama_buyer,
        st.tanggal_pengembalian,
        st.status_peminjaman as transaction_status
    FROM transaction_items ti
    JOIN color_stock_items csi ON ti.stock_item_id = csi.id
    JOIN color_components cc ON csi.component_id = cc.id
    JOIN master_color_panel mcp ON csi.color_id = mcp.id
    JOIN buyers b ON mcp.buyer_id = b.id
    JOIN stock_transactions st ON ti.transaction_id = st.id
    WHERE ti.transaction_id = ?
    ORDER BY ti.id ASC
");
$items_stmt->bind_param("i", $transaction_id);
$items_stmt->execute();
$items_result = $items_stmt->get_result();
$items_stmt->close();

// Check if transaction is completed
$transaction_completed = false;
$return_deadline = '';
if ($items_result->num_rows > 0) {
    $items_result->data_seek(0);
    $first_item = $items_result->fetch_assoc();
    $transaction_completed = $first_item['transaction_status'] == 'Dikembalikan';
    $return_deadline = $first_item['tanggal_pengembalian'];
    $items_result->data_seek(0); // Reset pointer
}

// Function to check time status
function getTimeStatus($return_deadline, $is_returned, $return_time = null) {
    if ($is_returned && $return_time) {
        $deadline = new DateTime($return_deadline);
        $deadline->add(new DateInterval('PT15M')); // Add 15 minutes tolerance
        $actual_return = new DateTime($return_time);
        
        return $actual_return <= $deadline ? 'tepat' : 'overdue';
    }
    
    if (!$is_returned) {
        $current_time = new DateTime();
        $deadline = new DateTime($return_deadline);
        $deadline_with_tolerance = clone $deadline;
        $deadline_with_tolerance->add(new DateInterval('PT15M'));
        
        if ($current_time > $deadline_with_tolerance) {
            return 'overdue';
        } elseif ($current_time >= $deadline) {
            return 'warning'; // In tolerance period
        }
    }
    
    return 'normal';
}
?>

<div class="space-y-4">
    <?php if ($items_result->num_rows == 0): ?>
        <div class="text-center py-8">
            <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>
            <p class="text-gray-600">Tidak ada item dalam transaksi ini</p>
        </div>
    <?php else: ?>
        <?php while ($item = $items_result->fetch_assoc()): ?>
            <?php
            $time_status = getTimeStatus($return_deadline, $item['dikembalikan'], $item['tanggal_kembali']);
            $is_returned = $item['dikembalikan'] == 1;
            $return_date_formatted = $is_returned ? date('d/m/Y H:i', strtotime($item['tanggal_kembali'])) : '';
            ?>
            
            <div class="bg-white border border-gray-200 rounded-lg p-4 lg:p-6 <?php echo $is_returned ? 'opacity-75' : ''; ?>">
                <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
                    <!-- Item Information -->
                    <div class="flex-1">
                        <div class="flex items-start space-x-4">
                            <!-- Item Icon -->
                            <div class="flex-shrink-0">
                                <div class="w-12 h-12 bg-gradient-to-br from-green-100 to-emerald-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-paint-brush text-green-600 text-lg"></i>
                                </div>
                            </div>
                            
                            <!-- Item Details -->
                            <div class="flex-1 min-w-0">
                                <div class="flex items-center space-x-2 mb-2">
                                    <h4 class="text-lg font-semibold text-gray-800 <?php echo $is_returned ? 'line-through' : ''; ?>">
                                        <?php echo htmlspecialchars($item['kode_barang']); ?>
                                    </h4>
                                    
                                    <!-- Status Badge -->
                                    <?php if ($is_returned): ?>
                                        <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium
                                            <?php echo $item['status_waktu'] == 'tepat' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                            <i class="fas fa-<?php echo $item['status_waktu'] == 'tepat' ? 'check' : 'clock'; ?> mr-1"></i>
                                            <?php echo $item['status_waktu'] == 'tepat' ? 'Tepat Waktu' : 'Terlambat'; ?>
                                        </span>
                                    <?php else: ?>
                                        <?php if ($time_status == 'overdue'): ?>
                                            <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                <i class="fas fa-exclamation-triangle mr-1"></i>
                                                Terlambat
                                            </span>
                                        <?php elseif ($time_status == 'warning'): ?>
                                            <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 animate-pulse">
                                                <i class="fas fa-clock mr-1"></i>
                                                Segera Kembalikan
                                            </span>
                                        <?php else: ?>
                                            <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                <i class="fas fa-hourglass-half mr-1"></i>
                                                Dipinjam
                                            </span>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2 text-sm">
                                    <div>
                                        <span class="text-gray-500">Buyer:</span>
                                        <p class="font-medium text-gray-800"><?php echo htmlspecialchars($item['nama_buyer']); ?></p>
                                    </div>
                                    <div>
                                        <span class="text-gray-500">Warna:</span>
                                        <p class="font-medium text-gray-800"><?php echo htmlspecialchars($item['code_color']); ?></p>
                                    </div>
                                    <div>
                                        <span class="text-gray-500">Komponen:</span>
                                        <p class="font-medium text-gray-800"><?php echo htmlspecialchars($item['component_name']); ?></p>
                                    </div>
                                    <div>
                                        <span class="text-gray-500">Lokasi:</span>
                                        <p class="font-medium text-gray-800"><?php echo htmlspecialchars($item['lokasi']); ?></p>
                                    </div>
                                    <div>
                                        <span class="text-gray-500">Rak:</span>
                                        <p class="font-medium text-gray-800"><?php echo htmlspecialchars($item['rack_no']); ?></p>
                                    </div>
                                    <?php if ($is_returned): ?>
                                        <div>
                                            <span class="text-gray-500">Dikembalikan:</span>
                                            <p class="font-medium text-gray-800"><?php echo $return_date_formatted; ?></p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                
                                <?php if ($is_returned && !empty($item['catatan'])): ?>
                                    <div class="mt-3 p-3 bg-gray-50 rounded-lg">
                                        <span class="text-sm text-gray-500">Catatan:</span>
                                        <p class="text-sm text-gray-800 mt-1"><?php echo htmlspecialchars($item['catatan']); ?></p>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($is_returned && $item['kondisi_kembali'] != 'Baik'): ?>
                                    <div class="mt-2">
                                        <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium
                                            <?php echo $item['kondisi_kembali'] == 'Rusak' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'; ?>">
                                            <i class="fas fa-<?php echo $item['kondisi_kembali'] == 'Rusak' ? 'tools' : 'question-circle'; ?> mr-1"></i>
                                            Kondisi: <?php echo htmlspecialchars($item['kondisi_kembali']); ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                
                            </div>
                        </div>
                    </div>
                    
                    <!-- Action Button -->
                    <div class="flex-shrink-0">
                        <?php if (!$is_returned && !$transaction_completed): ?>
                            <button onclick="showReturnModal(<?php echo $item['id']; ?>, '<?php echo htmlspecialchars($item['kode_barang'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($item['component_name'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($item['code_color'], ENT_QUOTES); ?>')"
                                    class="w-full lg:w-auto 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-undo mr-2"></i>
                                Kembalikan
                            </button>
                        <?php elseif ($is_returned): ?>
                            <div class="flex flex-col space-y-2">
                                <span class="inline-flex items-center px-3 py-2 rounded-lg text-sm font-medium bg-green-100 text-green-600">
                                    <i class="fas fa-check-circle mr-2"></i>
                                    Dikembalikan
                                </span>
                                
                                <!-- Photo action buttons - alternative display -->
                                <div class="flex flex-col space-y-1">
                                    <?php if (!empty($item['foto_bukti'])): ?>
                                        <button onclick="showPhotoModal('<?php echo htmlspecialchars($item['foto_bukti'], ENT_QUOTES); ?>', 'Foto Kondisi Cat', '<?php echo htmlspecialchars($item['kode_barang']); ?>', '<?php echo $return_date_formatted; ?>')"
                                                class="px-3 py-1 bg-blue-500 text-white rounded text-xs hover:bg-blue-600 transition-colors">
                                            <i class="fas fa-image mr-1"></i>
                                            Lihat Kondisi
                                        </button>
                                    <?php endif; ?>
                                    <?php if (!empty($item['foto_pengembalian'])): ?>
                                        <button onclick="showPhotoModal('<?php echo htmlspecialchars($item['foto_pengembalian'], ENT_QUOTES); ?>', 'Foto Bukti Penempatan', '<?php echo htmlspecialchars($item['kode_barang']); ?>', '<?php echo $return_date_formatted; ?>')"
                                                class="px-3 py-1 bg-purple-500 text-white rounded text-xs hover:bg-purple-600 transition-colors">
                                            <i class="fas fa-camera mr-1"></i>
                                            Lihat Penempatan
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php else: ?>
                            <span class="inline-flex items-center px-3 py-2 rounded-lg text-sm font-medium bg-gray-100 text-gray-600">
                                <i class="fas fa-lock mr-2"></i>
                                Transaksi Selesai
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Progress indicator for mobile -->
                <div class="lg:hidden mt-4 pt-4 border-t border-gray-200">
                    <div class="flex items-center justify-between text-xs text-gray-500">
                        <span><?php echo $is_returned ? 'Dikembalikan' : 'Belum dikembalikan'; ?></span>
                        <div class="w-4 h-4 rounded-full <?php echo $is_returned ? 'bg-green-500' : 'bg-gray-300'; ?> flex items-center justify-center">
                            <?php if ($is_returned): ?>
                                <i class="fas fa-check text-white text-xs"></i>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        <?php endwhile; ?>
        
        <!-- Time Information -->
        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <div class="flex items-start space-x-3">
                <div class="flex-shrink-0">
                    <i class="fas fa-info-circle text-blue-600 text-lg"></i>
                </div>
                <div class="flex-1">
                    <h4 class="text-sm font-semibold text-blue-800 mb-2">Informasi Waktu Pengembalian</h4>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
                        <div>
                            <span class="text-blue-600">Batas Waktu:</span>
                            <p class="font-medium text-blue-800"><?php echo date('d/m/Y H:i', strtotime($return_deadline)); ?></p>
                        </div>
                        <div>
                            <span class="text-blue-600">Toleransi:</span>
                            <p class="font-medium text-blue-800">15 menit setelah batas waktu</p>
                        </div>
                    </div>
                    <div class="mt-2 text-xs text-blue-700">
                        <i class="fas fa-lightbulb mr-1"></i>
                        Pengembalian setelah toleransi akan dianggap terlambat
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
// Function to download photo directly
function downloadPhotoDirectly(photoData, filename) {
    try {
        // Create download link
        const link = document.createElement('a');
        link.href = photoData;
        
        // Add timestamp if filename doesn't have it
        const now = new Date();
        const timestamp = now.toISOString().slice(0, 19).replace(/[:.]/g, '-');
        const finalFilename = filename.includes('_2') ? `${filename}.jpg` : `${filename}_${timestamp}.jpg`;
        
        link.download = finalFilename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    } catch (error) {
        console.error('Error downloading photo:', error);
        alert('Gagal mendownload foto');
    }
}

// Enhanced photo viewing function
function showPhotoModal(photoData, title, codeBarang = '', returnDate = '') {
    // Use the global function from parent window
    if (window.parent && window.parent.showPhotoModal) {
        window.parent.showPhotoModal(photoData, title, codeBarang, returnDate);
    } else if (window.showPhotoViewModal) {
        let info = '';
        if (codeBarang && returnDate) {
            info = `${codeBarang} - ${returnDate}`;
        } else if (codeBarang) {
            info = codeBarang;
        }
        window.showPhotoViewModal(photoData, title, info);
    } else {
        // Fallback - open in new window
        const newWindow = window.open('', '_blank');
        newWindow.document.write(`
            <html>
                <head>
                    <title>${title}</title>
                    <style>
                        body { margin: 0; padding: 20px; text-align: center; font-family: Arial, sans-serif; }
                        img { max-width: 100%; height: auto; }
                        h3 { color: #333; }
                        .info { color: #666; margin-top: 10px; }
                    </style>
                </head>
                <body>
                    <h3>${title}</h3>
                    <img src="${photoData}" alt="${title}" />
                    <div class="info">${codeBarang} ${returnDate}</div>
                    <div style="margin-top: 20px;">
                        <button onclick="window.close()">Tutup</button>
                    </div>
                </body>
            </html>
        `);
    }
}
</script>