<?php
require_once '../config/connection.php';
checkUserType(['superadmin']);

$message = '';
$message_type = '';

// Handle approval/rejection
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && isset($_POST['borrow_id'])) {
        $borrow_id = (int)$_POST['borrow_id'];
        $action = $_POST['action'];
        $notes = isset($_POST['notes']) ? sanitize($_POST['notes']) : '';
        
        try {
            if ($action === 'approve') {
                // Approve the request
                $stmt = $pdo->prepare("
                    UPDATE borrow_history 
                    SET status = 'borrowed', 
                        tanggal_peminjam = NOW(),
                        notes = ?,
                        updated_at = NOW()
                    WHERE id = ? AND status = 'pending_approval'
                ");
                $stmt->execute([$notes, $borrow_id]);
                
                // Update asset status
                $stmt = $pdo->prepare("
                    UPDATE assets 
                    SET status_borrower = 'borrowed', 
                        assigned_employee = (
                            SELECT borrower_employee_id 
                            FROM borrow_history 
                            WHERE id = ?
                        ),
                        assign_date = NOW(),
                        updated_at = NOW()
                    WHERE id = (
                        SELECT asset_id 
                        FROM borrow_history 
                        WHERE id = ?
                    )
                ");
                $stmt->execute([$borrow_id, $borrow_id]);
                
                $message = 'Peminjaman berhasil disetujui!';
                $message_type = 'success';
                
            } elseif ($action === 'reject') {
                // Reject the request
                $stmt = $pdo->prepare("
                    UPDATE borrow_history 
                    SET status = 'rejected',
                        notes = ?,
                        updated_at = NOW()
                    WHERE id = ? AND status = 'pending_approval'
                ");
                $stmt->execute([$notes, $borrow_id]);
                
                $message = 'Peminjaman berhasil ditolak!';
                $message_type = 'success';
            }
        } catch (Exception $e) {
            $message = 'Error: ' . $e->getMessage();
            $message_type = 'error';
        }
    }
}

// Get all pending requests with detailed information
$stmt = $pdo->prepare("
    SELECT 
        bh.*,
        a.asset_name,
        a.asset_number,
        a.asset_category,
        a.description as asset_description,
        a.barcode_number,
        b.full_name as borrower_name,
        b.employee_id as borrower_employee_id,
        b.organization as borrower_organization,
        b.branch_name as borrower_branch,
        b.jabatan as borrower_position
    FROM borrow_history bh
    JOIN assets a ON bh.asset_id = a.id
    JOIN borrowers b ON bh.borrower_employee_id = b.employee_id
    WHERE bh.status = 'pending_approval'
    ORDER BY bh.created_at ASC
");
$stmt->execute();
$pending_requests = $stmt->fetchAll();

// Get statistics
$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM borrow_history WHERE status = 'pending_approval'");
$stmt->execute();
$total_pending = $stmt->fetch()['total'];

$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM borrow_history WHERE status = 'borrowed'");
$stmt->execute();
$total_borrowed = $stmt->fetch()['total'];

$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM borrow_history WHERE status = 'rejected'");
$stmt->execute();
$total_rejected = $stmt->fetch()['total'];
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Persetujuan Peminjaman - Tools Room</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'leaf-green': '#90EE90',
                        'dark-leaf': '#32CD32',
                        'soft-gray': '#F5F5F5',
                        'medium-gray': '#9CA3AF'
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-soft-gray min-h-screen">
    <!-- Header -->
    <header class="bg-white shadow-sm border-b-2 border-leaf-green">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-4">
                <div class="flex items-center space-x-4">
                    <a href="dashboard.php" class="text-dark-leaf hover:text-green-600">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                        </svg>
                    </a>
                    <img src="../images/logo.png" alt="Logo" class="h-10 w-10" onerror="this.style.display='none'">
                    <div>
                        <h1 class="text-xl font-bold text-gray-800">Persetujuan Peminjaman</h1>
                        <p class="text-sm text-medium-gray">Kelola permintaan peminjaman asset</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="text-sm text-gray-600">Halo, <?php echo $_SESSION['user_name']; ?></span>
                    <a href="../logout.php" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg text-sm transition duration-200">
                        Logout
                    </a>
                </div>
            </div>
        </div>
    </header>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Alert Messages -->
        <?php if ($message): ?>
        <div class="mb-6 p-4 rounded-lg <?php echo $message_type === 'success' ? 'bg-green-100 text-green-700 border border-green-200' : 'bg-red-100 text-red-700 border border-red-200'; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-red-400">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">Pending</p>
                        <p class="text-3xl font-bold text-red-600"><?php echo $total_pending; ?></p>
                    </div>
                    <div class="bg-red-100 p-3 rounded-full">
                        <svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                </div>
                <p class="text-xs text-medium-gray mt-2">Menunggu persetujuan</p>
            </div>

            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-blue-400">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">Disetujui</p>
                        <p class="text-3xl font-bold text-blue-600"><?php echo $total_borrowed; ?></p>
                    </div>
                    <div class="bg-blue-100 p-3 rounded-full">
                        <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                </div>
                <p class="text-xs text-medium-gray mt-2">Sedang dipinjam</p>
            </div>

            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-gray-400">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">Ditolak</p>
                        <p class="text-3xl font-bold text-gray-600"><?php echo $total_rejected; ?></p>
                    </div>
                    <div class="bg-gray-100 p-3 rounded-full">
                        <svg class="w-6 h-6 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                </div>
                <p class="text-xs text-medium-gray mt-2">Permintaan ditolak</p>
            </div>
        </div>

        <!-- Pending Requests -->
        <div class="bg-white rounded-xl shadow-lg">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800">Permintaan Peminjaman Pending</h3>
                <p class="text-sm text-medium-gray">Total: <?php echo count($pending_requests); ?> permintaan</p>
            </div>

            <?php if (empty($pending_requests)): ?>
            <div class="p-8 text-center">
                <svg class="w-16 h-16 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <h3 class="text-lg font-medium text-gray-800 mb-2">Tidak Ada Permintaan Pending</h3>
                <p class="text-medium-gray">Semua permintaan peminjaman sudah diproses</p>
            </div>
            <?php else: ?>
            <div class="divide-y divide-gray-200">
                <?php foreach ($pending_requests as $request): ?>
                <div class="p-6">
                    <div class="flex items-start justify-between">
                        <div class="flex-1">
                            <!-- Borrower Info -->
                            <div class="mb-4">
                                <div class="flex items-center space-x-3 mb-2">
                                    <div class="bg-blue-100 p-2 rounded-full">
                                        <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                                        </svg>
                                    </div>
                                    <div>
                                        <h4 class="text-lg font-semibold text-gray-800"><?php echo htmlspecialchars($request['borrower_name']); ?></h4>
                                        <p class="text-sm text-medium-gray"><?php echo htmlspecialchars($request['borrower_employee_id']); ?></p>
                                    </div>
                                </div>
                                <div class="ml-10">
                                    <p class="text-sm text-gray-600"><strong>Organisasi:</strong> <?php echo htmlspecialchars($request['borrower_organization']); ?></p>
                                    <p class="text-sm text-gray-600"><strong>Cabang:</strong> <?php echo htmlspecialchars($request['borrower_branch']); ?></p>
                                    <p class="text-sm text-gray-600"><strong>Jabatan:</strong> <?php echo htmlspecialchars($request['borrower_position']); ?></p>
                                </div>
                            </div>

                            <!-- Asset Info -->
                            <div class="mb-4 bg-gray-50 p-4 rounded-lg">
                                <div class="flex items-center space-x-3 mb-2">
                                    <div class="bg-green-100 p-2 rounded-full">
                                        <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path>
                                        </svg>
                                    </div>
                                    <div>
                                        <h5 class="font-semibold text-gray-800"><?php echo htmlspecialchars($request['asset_name']); ?></h5>
                                        <p class="text-sm text-medium-gray"><?php echo htmlspecialchars($request['asset_number']); ?></p>
                                    </div>
                                </div>
                                <div class="ml-10">
                                    <p class="text-sm text-gray-600"><strong>Kategori:</strong> <?php echo htmlspecialchars($request['asset_category']); ?></p>
                                    <?php if ($request['barcode_number']): ?>
                                    <p class="text-sm text-gray-600"><strong>Barcode:</strong> <?php echo htmlspecialchars($request['barcode_number']); ?></p>
                                    <?php endif; ?>
                                    <?php if ($request['asset_description']): ?>
                                    <p class="text-sm text-gray-600"><strong>Deskripsi:</strong> <?php echo htmlspecialchars($request['asset_description']); ?></p>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Request Info -->
                            <div class="mb-4">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                                    <div>
                                        <p class="text-medium-gray">Tanggal Pengajuan:</p>
                                        <p class="font-medium text-gray-800"><?php echo date('d F Y, H:i', strtotime($request['created_at'])); ?></p>
                                    </div>
                                    <div>
                                        <p class="text-medium-gray">workcenter/Keperluan:</p>
                                        <p class="font-medium text-gray-800"><?php echo htmlspecialchars($request['workcenter']); ?></p>
                                    </div>
                                    <?php if ($request['preference_pro']): ?>
                                    <div class="md:col-span-2">
                                        <p class="text-medium-gray">Preference/Keterangan:</p>
                                        <p class="font-medium text-gray-800"><?php echo htmlspecialchars($request['preference_pro']); ?></p>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="flex flex-col space-y-2 ml-6">
                            <button onclick="showApprovalModal(<?php echo $request['id']; ?>, 'approve', '<?php echo htmlspecialchars($request['borrower_name']); ?>', '<?php echo htmlspecialchars($request['asset_name']); ?>')" 
                                    class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg text-sm transition duration-200 flex items-center space-x-2">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                                </svg>
                                <span>Setujui</span>
                            </button>
                            <button onclick="showApprovalModal(<?php echo $request['id']; ?>, 'reject', '<?php echo htmlspecialchars($request['borrower_name']); ?>', '<?php echo htmlspecialchars($request['asset_name']); ?>')" 
                                    class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg text-sm transition duration-200 flex items-center space-x-2">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                </svg>
                                <span>Tolak</span>
                            </button>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Approval Modal -->
    <div id="approvalModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <h3 id="modalTitle" class="text-lg font-medium text-gray-900 mb-4"></h3>
                <p id="modalMessage" class="text-sm text-gray-600 mb-4"></p>
                
                <form method="POST">
                    <input type="hidden" name="borrow_id" id="modalBorrowId">
                    <input type="hidden" name="action" id="modalAction">
                    
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Catatan (Opsional)</label>
                        <textarea name="notes" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf" placeholder="Tambahkan catatan jika diperlukan..."></textarea>
                    </div>

                    <div class="flex justify-end space-x-3">
                        <button type="button" onclick="hideApprovalModal()" class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200">
                            Batal
                        </button>
                        <button type="submit" id="modalSubmitBtn" class="px-4 py-2 text-sm font-medium text-white rounded-md">
                            Konfirmasi
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function showApprovalModal(borrowId, action, borrowerName, assetName) {
            const modal = document.getElementById('approvalModal');
            const title = document.getElementById('modalTitle');
            const message = document.getElementById('modalMessage');
            const borrowIdInput = document.getElementById('modalBorrowId');
            const actionInput = document.getElementById('modalAction');
            const submitBtn = document.getElementById('modalSubmitBtn');
            
            borrowIdInput.value = borrowId;
            actionInput.value = action;
            
            if (action === 'approve') {
                title.textContent = 'Setujui Peminjaman';
                message.textContent = `Apakah Anda yakin ingin menyetujui peminjaman asset "${assetName}" oleh ${borrowerName}?`;
                submitBtn.textContent = 'Setujui';
                submitBtn.className = 'px-4 py-2 text-sm font-medium text-white bg-green-500 rounded-md hover:bg-green-600';
            } else {
                title.textContent = 'Tolak Peminjaman';
                message.textContent = `Apakah Anda yakin ingin menolak peminjaman asset "${assetName}" oleh ${borrowerName}?`;
                submitBtn.textContent = 'Tolak';
                submitBtn.className = 'px-4 py-2 text-sm font-medium text-white bg-red-500 rounded-md hover:bg-red-600';
            }
            
            modal.classList.remove('hidden');
        }
        
        function hideApprovalModal() {
            document.getElementById('approvalModal').classList.add('hidden');
        }
        
        // Close modal when clicking outside
        document.getElementById('approvalModal').addEventListener('click', function(e) {
            if (e.target === this) {
                hideApprovalModal();
            }
        });
    </script>
</body>
</html>