<?php
// Start session
session_start();
// Include database connection
require_once "../config/connection.php";

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

// Get transaction ID from URL parameter
$transaction_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Redirect if no ID provided
if ($transaction_id <= 0) {
    header("Location: dashboard_it.php");
    exit();
}

// Get transaction details
$stmt = $conn->prepare("
    SELECT 
        st.*,
        bu.username as borrower_name,
        bu.email as borrower_email,
        bu.lokasi_posisi as borrower_location
    FROM 
        stock_transactions st
    JOIN 
        borrower_users bu ON st.borrower_id = bu.id
    WHERE 
        st.id = ?
");
$stmt->bind_param("i", $transaction_id);
$stmt->execute();
$transaction = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Redirect if transaction not found
if (!$transaction) {
    header("Location: dashboard_it.php");
    exit();
}

// Get transaction items
$stmt = $conn->prepare("
    SELECT 
        ti.*,
        csi.kode_barang,
        mcp.code_color,
        cc.component_name,
        b.nama_buyer
    FROM 
        transaction_items ti
    JOIN 
        color_stock_items csi ON ti.stock_item_id = csi.id
    JOIN 
        master_color_panel mcp ON csi.color_id = mcp.id
    JOIN 
        color_components cc ON csi.component_id = cc.id
    JOIN 
        buyers b ON mcp.buyer_id = b.id
    WHERE 
        ti.transaction_id = ?
    ORDER BY 
        ti.id ASC
");
$stmt->bind_param("i", $transaction_id);
$stmt->execute();
$items = $stmt->get_result();
$stmt->close();

// Set page title
$page_title = "Detail Transaksi";

// Log activity
$user_id = $_SESSION['user_id'];
$user_type = $_SESSION['user_type'];
log_activity($conn, $user_id, 'admin', 'View Transaction Details', "Admin viewed transaction ID: $transaction_id");

// Include header
include '../template_admin/header.php';

// Format status for display
function getStatusBadge($status) {
    switch ($status) {
        case 'Diajukan':
            return '<span class="bg-blue-100 text-blue-800 px-2 py-1 rounded-full text-xs font-medium">Diajukan</span>';
        case 'Disetujui':
            return '<span class="bg-green-100 text-green-800 px-2 py-1 rounded-full text-xs font-medium">Disetujui</span>';
        case 'Ditolak':
            return '<span class="bg-red-100 text-red-800 px-2 py-1 rounded-full text-xs font-medium">Ditolak</span>';
        case 'OnProccesing':
            return '<span class="bg-yellow-100 text-yellow-800 px-2 py-1 rounded-full text-xs font-medium">Dalam Proses</span>';
        default:
            return '<span class="bg-gray-100 text-gray-800 px-2 py-1 rounded-full text-xs font-medium">' . htmlspecialchars($status) . '</span>';
    }
}

// Format borrowing status for display
function getBorrowingStatusBadge($status) {
    switch ($status) {
        case 'None':
            return '<span class="bg-gray-100 text-gray-800 px-2 py-1 rounded-full text-xs font-medium">Belum Dipinjam</span>';
        case 'Dipinjam':
            return '<span class="bg-purple-100 text-purple-800 px-2 py-1 rounded-full text-xs font-medium">Sedang Dipinjam</span>';
        case 'Dikembalikan':
            return '<span class="bg-green-100 text-green-800 px-2 py-1 rounded-full text-xs font-medium">Sudah Dikembalikan</span>';
        default:
            return '<span class="bg-gray-100 text-gray-800 px-2 py-1 rounded-full text-xs font-medium">' . htmlspecialchars($status) . '</span>';
    }
}

// Calculate duration in hours and minutes
function calculateDuration($start, $end) {
    $start_time = strtotime($start);
    $end_time = strtotime($end);
    $diff_seconds = $end_time - $start_time;
    
    $hours = floor($diff_seconds / 3600);
    $minutes = floor(($diff_seconds % 3600) / 60);
    
    return "$hours jam $minutes menit";
}

// Check if transaction is overdue
$is_overdue = false;
$now = time();
$due_date = strtotime($transaction['tanggal_pengembalian']);
if ($transaction['status_peminjaman'] == 'Dipinjam' && $now > $due_date) {
    $is_overdue = true;
}

// Function to get time status
function getTimeStatusBadge($due_date, $status_peminjaman) {
    $now = time();
    $due = strtotime($due_date);
    
    if ($status_peminjaman == 'Dikembalikan') {
        return '<span class="bg-green-100 text-green-800 px-2 py-1 rounded-full text-xs font-medium">Selesai</span>';
    } elseif ($status_peminjaman == 'None') {
        return '<span class="bg-gray-100 text-gray-800 px-2 py-1 rounded-full text-xs font-medium">Belum Dimulai</span>';
    } elseif ($now > $due) {
        // Calculate overdue time
        $overdue_seconds = $now - $due;
        $overdue_hours = floor($overdue_seconds / 3600);
        $overdue_days = floor($overdue_hours / 24);
        $remaining_hours = $overdue_hours % 24;
        
        if ($overdue_days > 0) {
            $overdue_text = "$overdue_days hari";
            if ($remaining_hours > 0) {
                $overdue_text .= " $remaining_hours jam";
            }
        } else {
            $overdue_text = "$overdue_hours jam";
        }
        
        return '<span class="bg-red-100 text-red-800 px-2 py-1 rounded-full text-xs font-medium">Terlambat ' . $overdue_text . '</span>';
    } else {
        // Calculate remaining time
        $remaining_seconds = $due - $now;
        $remaining_hours = floor($remaining_seconds / 3600);
        
        if ($remaining_hours < 1) {
            $remaining_minutes = floor($remaining_seconds / 60);
            return '<span class="bg-orange-100 text-orange-800 px-2 py-1 rounded-full text-xs font-medium">Segera Berakhir (' . $remaining_minutes . ' menit)</span>';
        } elseif ($remaining_hours < 24) {
            return '<span class="bg-yellow-100 text-yellow-800 px-2 py-1 rounded-full text-xs font-medium">Tersisa ' . $remaining_hours . ' jam</span>';
        } else {
            $remaining_days = floor($remaining_hours / 24);
            return '<span class="bg-blue-100 text-blue-800 px-2 py-1 rounded-full text-xs font-medium">Tersisa ' . $remaining_days . ' hari</span>';
        }
    }
}
?>

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-teal-50 via-cyan-50 to-blue-50">
    <!-- Breadcrumb -->
    <div class="mb-4 flex items-center text-sm text-gray-500">
        <a href="dashboard_admin.php" class="hover:text-gray-700">
            <i class="fas fa-home mr-1"></i> Dashboard
        </a>
        <span class="mx-2">/</span>
        <span class="text-gray-700 font-medium">Detail Transaksi</span>
    </div>

    <!-- Back Button -->
    <div class="mb-4">
        <a href="javascript:history.back()" class="inline-flex items-center px-3 py-2 bg-gray-200 hover:bg-gray-300 rounded-lg transition-colors">
            <i class="fas fa-arrow-left mr-2"></i> Kembali
        </a>
    </div>

    <!-- Transaction Header Card -->
    <div class="bg-white rounded-xl shadow-md mb-6 overflow-hidden">
        <div class="bg-gradient-to-r from-teal-500 to-teal-600 px-6 py-4 text-white">
            <div class="flex flex-wrap items-center justify-between">
                <div>
                    <h2 class="text-xl font-bold">Reservasi: <?php echo htmlspecialchars($transaction['reservation_number']); ?></h2>
                    <p class="text-teal-100 mt-1">ID Transaksi: <?php echo $transaction_id; ?></p>
                </div>
                <div class="flex items-center mt-2 sm:mt-0">
                    <?php echo getStatusBadge($transaction['status']); ?>
                    <span class="mx-2">|</span>
                    <?php echo getBorrowingStatusBadge($transaction['status_peminjaman']); ?>
                    <span class="mx-2">|</span>
                    <?php echo getTimeStatusBadge($transaction['tanggal_pengembalian'], $transaction['status_peminjaman']); ?>
                </div>
            </div>
        </div>
        
        <div class="p-6">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- Borrower Information -->
                <div class="bg-gray-50 rounded-lg p-4">
                    <h3 class="text-gray-700 font-semibold mb-2 flex items-center">
                        <i class="fas fa-user mr-2 text-teal-500"></i> Informasi Peminjam
                    </h3>
                    <div class="space-y-2 text-sm">
                        <div class="flex items-start">
                            <span class="text-gray-500 w-24">Nama:</span>
                            <span class="font-medium"><?php echo htmlspecialchars($transaction['borrower_name']); ?></span>
                        </div>
                        <div class="flex items-start">
                            <span class="text-gray-500 w-24">Email:</span>
                            <span class="font-medium"><?php echo htmlspecialchars($transaction['borrower_email']); ?></span>
                        </div>
                        <div class="flex items-start">
                            <span class="text-gray-500 w-24">Lokasi:</span>
                            <span class="font-medium"><?php echo htmlspecialchars($transaction['borrower_location']); ?></span>
                        </div>
                    </div>
                </div>
                
                <!-- Transaction Dates -->
                <div class="bg-gray-50 rounded-lg p-4">
                    <h3 class="text-gray-700 font-semibold mb-2 flex items-center">
                        <i class="fas fa-calendar-alt mr-2 text-teal-500"></i> Waktu Peminjaman
                    </h3>
                    <div class="space-y-2 text-sm">
                        <div class="flex items-start">
                            <span class="text-gray-500 w-24">Tanggal:</span>
                            <span class="font-medium"><?php echo date('d/m/Y', strtotime($transaction['tanggal_transaksi'])); ?></span>
                        </div>
                        <div class="flex items-start">
                            <span class="text-gray-500 w-24">Mulai:</span>
                            <span class="font-medium"><?php echo date('H:i', strtotime($transaction['tanggal_transaksi'])); ?> WIB</span>
                        </div>
                        <div class="flex items-start">
                            <span class="text-gray-500 w-24">Selesai:</span>
                            <span class="font-medium <?php echo $is_overdue ? 'text-red-600' : ''; ?>">
                                <?php echo date('H:i', strtotime($transaction['tanggal_pengembalian'])); ?> WIB
                                <?php if ($is_overdue): ?>
                                <i class="fas fa-exclamation-circle ml-1 text-red-500"></i>
                                <?php endif; ?>
                            </span>
                        </div>
                        <div class="flex items-start">
                            <span class="text-gray-500 w-24">Durasi:</span>
                            <span class="font-medium"><?php echo calculateDuration($transaction['tanggal_transaksi'], $transaction['tanggal_pengembalian']); ?></span>
                        </div>
                    </div>
                </div>
                
                <!-- Transaction Status -->
                <div class="bg-gray-50 rounded-lg p-4">
                    <h3 class="text-gray-700 font-semibold mb-2 flex items-center">
                        <i class="fas fa-info-circle mr-2 text-teal-500"></i> Status Transaksi
                    </h3>
                    <div class="space-y-2 text-sm">
                        <div class="flex items-start">
                            <span class="text-gray-500 w-24">Status:</span>
                            <div><?php echo getStatusBadge($transaction['status']); ?></div>
                        </div>
                        <div class="flex items-start">
                            <span class="text-gray-500 w-24">Peminjaman:</span>
                            <div><?php echo getBorrowingStatusBadge($transaction['status_peminjaman']); ?></div>
                        </div>
                        <?php if ($transaction['status'] == 'Ditolak'): ?>
                        <div class="flex items-start">
                            <span class="text-gray-500 w-24">Alasan:</span>
                            <span class="text-red-600"><?php echo htmlspecialchars($transaction['catatan_tolak'] ?: 'Tidak ada alasan'); ?></span>
                        </div>
                        <?php endif; ?>
                        <?php if (!empty($transaction['keterangan'])): ?>
                        <div class="flex items-start">
                            <span class="text-gray-500 w-24">Keterangan:</span>
                            <span class="font-medium"><?php echo htmlspecialchars($transaction['keterangan']); ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Transaction Items -->
    <div class="bg-white rounded-xl shadow-md overflow-hidden">
        <div class="bg-gradient-to-r from-blue-500 to-blue-600 px-6 py-4 text-white">
            <h2 class="text-xl font-bold">Item yang Dipinjam</h2>
            <p class="text-blue-100 mt-1">Total: <?php echo $items->num_rows; ?> item</p>
        </div>

        <div class="p-6">
            <?php if ($items->num_rows > 0): ?>
            <div class="overflow-x-auto">
                <table class="min-w-full bg-white">
                    <thead>
                        <tr class="bg-gray-100 text-gray-700 text-left">
                            <th class="py-3 px-4 rounded-tl-lg font-semibold">Kode Barang</th>
                            <th class="py-3 px-4 font-semibold">Color</th>
                            <th class="py-3 px-4 font-semibold">Component</th>
                            <th class="py-3 px-4 font-semibold">Lokasi Asal</th>
                            <th class="py-3 px-4 font-semibold">Lokasi Tujuan</th>
                            <th class="py-3 px-4 font-semibold">Status</th>
                            <th class="py-3 px-4 rounded-tr-lg font-semibold">Kondisi Kembali</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($item = $items->fetch_assoc()): ?>
                        <tr class="border-b hover:bg-gray-50">
                            <td class="py-3 px-4 font-medium"><?php echo htmlspecialchars($item['kode_barang']); ?></td>
                            <td class="py-3 px-4">
                                <div>
                                    <span class="font-medium"><?php echo htmlspecialchars($item['code_color']); ?></span>
                                    <div class="text-xs text-gray-500"><?php echo htmlspecialchars($item['nama_buyer']); ?></div>
                                </div>
                            </td>
                            <td class="py-3 px-4"><?php echo htmlspecialchars($item['component_name']); ?></td>
                            <td class="py-3 px-4">
                                <span class="px-2 py-1 bg-blue-100 text-blue-800 rounded-full text-xs">
                                    <?php echo htmlspecialchars($item['lokasi_asal']); ?>
                                </span>
                            </td>
                            <td class="py-3 px-4">
                                <span class="px-2 py-1 bg-purple-100 text-purple-800 rounded-full text-xs">
                                    <?php echo htmlspecialchars($item['lokasi_tujuan']); ?>
                                </span>
                            </td>
                            <td class="py-3 px-4">
                                <?php if ($item['dikembalikan']): ?>
                                <span class="px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs">
                                    Dikembalikan <?php echo date('d/m/Y H:i', strtotime($item['tanggal_kembali'])); ?>
                                </span>
                                <?php else: ?>
                                <span class="px-2 py-1 bg-yellow-100 text-yellow-800 rounded-full text-xs">
                                    Belum Dikembalikan
                                </span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3 px-4">
                                <?php if ($item['dikembalikan']): ?>
                                    <?php if ($item['kondisi_kembali'] == 'Baik'): ?>
                                    <span class="px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs">
                                        Baik
                                    </span>
                                    <?php elseif ($item['kondisi_kembali'] == 'Rusak'): ?>
                                    <span class="px-2 py-1 bg-orange-100 text-orange-800 rounded-full text-xs">
                                        Rusak
                                    </span>
                                    <?php elseif ($item['kondisi_kembali'] == 'Hilang'): ?>
                                    <span class="px-2 py-1 bg-red-100 text-red-800 rounded-full text-xs">
                                        Hilang
                                    </span>
                                    <?php endif; ?>
                                    
                                    <?php if (!empty($item['catatan'])): ?>
                                    <div class="text-xs text-gray-500 mt-1">
                                        <i class="fas fa-info-circle"></i> <?php echo htmlspecialchars($item['catatan']); ?>
                                    </div>
                                    <?php endif; ?>
                                <?php else: ?>
                                <span class="text-gray-400 text-xs">-</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
            <?php else: ?>
            <div class="text-center py-8">
                <div class="mx-auto w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                    <i class="fas fa-exclamation-triangle text-gray-500 text-2xl"></i>
                </div>
                <h3 class="text-lg font-medium text-gray-800 mb-2">Tidak Ada Item</h3>
                <p class="text-gray-500">Tidak ada item yang terdaftar dalam transaksi ini.</p>
            </div>
            <?php endif; ?>
        </div>
    </div>
</main>

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