<?php
// Start session
session_start();

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

// Check if user is IT
if (!is_logged_in() || !is_user_type('it')) {
    echo '<div class="p-8 text-center text-red-600">Akses tidak diizinkan</div>';
    exit();
}

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

// Build the query
$query = "
    SELECT 
        ti.id as item_id,
        ti.tanggal_kembali,
        ti.kondisi_kembali,
        ti.catatan,
        ti.foto_bukti,
        ti.foto_pengembalian,
        ti.status_waktu,
        st.reservation_number,
        st.tanggal_transaksi,
        st.tanggal_pengembalian,
        bu.username as borrower_username,
        bu.nama_borrower,
        bu.nik,
        bu.lokasi_posisi,
        mcp.code_color,
        mcp.deskripsi as color_description,
        b.nama_buyer,
        cc.component_name,
        csi.kode_barang,
        csi.stock_number,
        csi.rack_no
    FROM transaction_items ti
    JOIN stock_transactions st ON ti.transaction_id = st.id
    JOIN borrower_users bu ON st.borrower_id = bu.id
    JOIN color_stock_items csi ON ti.stock_item_id = csi.id
    JOIN master_color_panel mcp ON csi.color_id = mcp.id
    JOIN buyers b ON mcp.buyer_id = b.id
    JOIN color_components cc ON csi.component_id = cc.id
    WHERE ti.dikembalikan = 1 
    AND ti.tanggal_kembali IS NOT NULL
";

$params = [];
$types = "";

// Add location filter
if (!empty($filter_lokasi)) {
    $query .= " AND bu.lokasi_posisi = ?";
    $params[] = $filter_lokasi;
    $types .= "s";
}

// Add NIK search filter
if (!empty($search_nik)) {
    $query .= " AND bu.nik LIKE ?";
    $params[] = "%{$search_nik}%";
    $types .= "s";
}

$query .= " ORDER BY ti.tanggal_kembali DESC";

// Prepare and execute query
$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
?>

<table class="min-w-full divide-y divide-gray-200">
    <thead class="bg-gray-50">
        <tr>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Reservasi</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Peminjam</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Barang</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal Kembali</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kondisi</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status Waktu</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Foto Bukti</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Foto Pengembalian</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Catatan</th>
        </tr>
    </thead>
    <tbody class="bg-white divide-y divide-gray-200">
        <?php if ($result->num_rows > 0): ?>
            <?php while ($row = $result->fetch_assoc()): ?>
                <tr class="hover:bg-gray-50">
                    <!-- Reservasi -->
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($row['reservation_number']); ?></div>
                        <div class="text-sm text-gray-500">
                            Pinjam: <?php echo date('d/m/Y H:i', strtotime($row['tanggal_transaksi'])); ?>
                        </div>
                    </td>

                    <!-- Peminjam -->
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($row['nama_borrower']); ?></div>
                        <div class="text-sm text-gray-500">NIK: <?php echo htmlspecialchars($row['nik']); ?></div>
                        <div class="text-sm text-gray-500"><?php echo htmlspecialchars($row['lokasi_posisi']); ?></div>
                    </td>

                    <!-- Barang -->
                    <td class="px-6 py-4">
                        <div class="text-sm font-medium text-gray-900">
                            <?php echo htmlspecialchars($row['nama_buyer'] . ' ' . $row['code_color']); ?>
                        </div>
                        <div class="text-sm text-gray-500"><?php echo htmlspecialchars($row['component_name']); ?></div>
                        <div class="text-sm text-gray-500">
                            <?php echo htmlspecialchars($row['kode_barang']); ?> - Rack: <?php echo htmlspecialchars($row['rack_no']); ?>
                        </div>
                    </td>

                    <!-- Tanggal Kembali -->
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-gray-900">
                            <?php echo date('d/m/Y', strtotime($row['tanggal_kembali'])); ?>
                        </div>
                        <div class="text-sm text-gray-500">
                            <?php echo date('H:i:s', strtotime($row['tanggal_kembali'])); ?>
                        </div>
                    </td>

                    <!-- Kondisi -->
                    <td class="px-6 py-4 whitespace-nowrap">
                        <?php
                        $kondisi_color = '';
                        switch($row['kondisi_kembali']) {
                            case 'Baik':
                                $kondisi_color = 'bg-green-100 text-green-800';
                                break;
                            case 'Rusak':
                                $kondisi_color = 'bg-red-100 text-red-800';
                                break;
                            case 'Hilang':
                                $kondisi_color = 'bg-yellow-100 text-yellow-800';
                                break;
                            default:
                                $kondisi_color = 'bg-gray-100 text-gray-800';
                        }
                        ?>
                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full <?php echo $kondisi_color; ?>">
                            <?php echo htmlspecialchars($row['kondisi_kembali']); ?>
                        </span>
                    </td>

                    <!-- Status Waktu -->
                    <td class="px-6 py-4 whitespace-nowrap">
                        <?php
                        $status_color = '';
                        $status_text = '';
                        switch($row['status_waktu']) {
                            case 'tepat':
                                $status_color = 'bg-green-100 text-green-800';
                                $status_text = 'Tepat Waktu';
                                break;
                            case 'overdue':
                                $status_color = 'bg-red-100 text-red-800';
                                $status_text = 'Terlambat';
                                break;
                            default:
                                $status_color = 'bg-gray-100 text-gray-800';
                                $status_text = 'Normal';
                        }
                        ?>
                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full <?php echo $status_color; ?>">
                            <?php echo $status_text; ?>
                        </span>
                    </td>

                    <!-- Foto Bukti -->
                    <td class="px-6 py-4 whitespace-nowrap text-center">
                        <?php if (!empty($row['foto_bukti'])): ?>
                            <button onclick="showPhoto('<?php echo $row['foto_bukti']; ?>', 'Foto Bukti Kondisi', 'Foto kondisi barang saat dikembalikan - <?php echo htmlspecialchars($row['kode_barang']); ?>')" 
                                    class="text-blue-600 hover:text-blue-800">
                                <i class="fas fa-image text-lg"></i>
                                <div class="text-xs">Lihat Foto</div>
                            </button>
                        <?php else: ?>
                            <span class="text-gray-400">
                                <i class="fas fa-times"></i>
                                <div class="text-xs">Tidak Ada</div>
                            </span>
                        <?php endif; ?>
                    </td>

                    <!-- Foto Pengembalian -->
                    <td class="px-6 py-4 whitespace-nowrap text-center">
                        <?php if (!empty($row['foto_pengembalian'])): ?>
                            <button onclick="showPhoto('<?php echo $row['foto_pengembalian']; ?>', 'Foto Pengembalian', 'Foto dokumentasi pengembalian barang ke rack - <?php echo htmlspecialchars($row['kode_barang']); ?>')" 
                                    class="text-green-600 hover:text-green-800">
                                <i class="fas fa-camera text-lg"></i>
                                <div class="text-xs">Lihat Foto</div>
                            </button>
                        <?php else: ?>
                            <span class="text-gray-400">
                                <i class="fas fa-times"></i>
                                <div class="text-xs">Tidak Ada</div>
                            </span>
                        <?php endif; ?>
                    </td>

                    <!-- Catatan -->
                    <td class="px-6 py-4">
                        <div class="text-sm text-gray-900 max-w-xs overflow-hidden">
                            <?php if (!empty($row['catatan'])): ?>
                                <div title="<?php echo htmlspecialchars($row['catatan']); ?>" class="truncate">
                                    <?php echo htmlspecialchars(substr($row['catatan'], 0, 50)); ?>
                                    <?php if (strlen($row['catatan']) > 50): ?>...<?php endif; ?>
                                </div>
                            <?php else: ?>
                                <span class="text-gray-400">-</span>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr>
                <td colspan="9" class="px-6 py-8 text-center text-gray-500">
                    <i class="fas fa-inbox text-4xl mb-4 text-gray-300"></i>
                    <div class="text-lg font-medium">Tidak ada data history pengembalian</div>
                    <div class="text-sm">
                        <?php if (!empty($filter_lokasi) || !empty($search_nik)): ?>
                            Coba ubah filter atau kriteria pencarian
                        <?php else: ?>
                            Belum ada barang yang dikembalikan
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
        <?php endif; ?>
    </tbody>
</table>

<?php if ($result->num_rows > 0): ?>
    <div class="bg-gray-50 px-6 py-3 border-t border-gray-200">
        <div class="flex items-center justify-between">
            <div class="text-sm text-gray-700">
                Menampilkan <span class="font-medium"><?php echo $result->num_rows; ?></span> data history pengembalian
            </div>
            <div class="text-sm text-gray-500">
                Data diurutkan berdasarkan tanggal pengembalian terbaru
            </div>
        </div>
    </div>
<?php endif; ?>

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