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

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

// Handle approval/rejection
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $request_id = (int)$_POST['request_id'];
    $action = $_POST['action'];
    
    try {
        $pdo->beginTransaction();
        
        if ($action == 'approve') {
            // Get request details
            $stmt = $pdo->prepare("
                SELECT bh.*, a.kondisi 
                FROM borrow_history bh 
                JOIN assets a ON bh.asset_id = a.id 
                WHERE bh.id = ?
            ");
            $stmt->execute([$request_id]);
            $request = $stmt->fetch();
            
            if ($request) {
                // Approve the request
                $stmt = $pdo->prepare("UPDATE borrow_history SET status = 'borrowed' WHERE id = ?");
                $stmt->execute([$request_id]);
                
                // Update asset status
                $stmt = $pdo->prepare("
                    UPDATE assets 
                    SET status_borrower = 'borrowed', 
                        assigned_employee = ?,
                        assign_date = CURDATE()
                    WHERE id = ?
                ");
                $stmt->execute([$request['borrower_employee_id'], $request['asset_id']]);
                
                $message = 'Permintaan berhasil disetujui!';
                $message_type = 'success';
            }
            
        } elseif ($action == 'reject') {
            // Get asset ID before rejecting
            $stmt = $pdo->prepare("SELECT asset_id FROM borrow_history WHERE id = ?");
            $stmt->execute([$request_id]);
            $borrow_record = $stmt->fetch();
            
            if ($borrow_record) {
                // Update status to rejected
                $stmt = $pdo->prepare("UPDATE borrow_history SET status = 'rejected' WHERE id = ?");
                $stmt->execute([$request_id]);
                
                // Set asset back to available
                $stmt = $pdo->prepare("
                    UPDATE assets 
                    SET status_borrower = 'available', 
                        assigned_employee = NULL,
                        assign_date = NULL
                    WHERE id = ?
                ");
                $stmt->execute([$borrow_record['asset_id']]);
                
                $message = 'Permintaan berhasil ditolak!';
                $message_type = 'success';
            }
        }
        
        $pdo->commit();
        
    } catch (Exception $e) {
        $pdo->rollback();
        $message = 'Terjadi kesalahan: ' . $e->getMessage();
        $message_type = 'error';
    }
}

// Get pending requests
$stmt = $pdo->prepare("
    SELECT bh.*, 
           a.asset_name, a.asset_number, a.asset_category, a.kondisi,
           b.full_name as borrower_name, b.jabatan, b.organization,
           DATEDIFF(CURDATE(), bh.created_at) as days_pending
    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();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Persetujuan - 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'
                    }
                }
            }
        }
    </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</h1>
                        <p class="text-sm text-gray-500">Kelola permintaan peminjaman</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="text-sm text-gray-600"><?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">
                        Logout
                    </a>
                </div>
            </div>
        </div>
    </header>

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

        <!-- Stats -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <div class="text-center">
                <h2 class="text-2xl font-bold text-gray-800"><?php echo count($pending_requests); ?></h2>
                <p class="text-gray-600">Permintaan Menunggu Persetujuan</p>
            </div>
        </div>

        <!-- Pending Requests -->
        <?php if (empty($pending_requests)): ?>
        <div class="bg-white rounded-xl shadow-lg p-8 text-center">
            <div class="text-green-500 mb-4">
                <svg class="w-16 h-16 mx-auto" 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>
            <h3 class="text-lg font-semibold text-gray-800 mb-2">Semua Permintaan Sudah Diproses</h3>
            <p class="text-gray-600">Tidak ada permintaan yang menunggu persetujuan</p>
        </div>
        <?php else: ?>
        <div class="space-y-4">
            <?php foreach ($pending_requests as $request): ?>
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-800"><?php echo $request['asset_name']; ?></h3>
                        <p class="text-gray-600"><?php echo $request['asset_number']; ?> • <?php echo $request['asset_category']; ?></p>
                        <p class="text-sm text-gray-500">
                            Kondisi: <span class="<?php echo $request['kondisi'] == 'baik' ? 'text-green-600' : 'text-yellow-600'; ?>">
                                <?php echo ucfirst($request['kondisi']); ?>
                            </span>
                        </p>
                    </div>
                    <span class="bg-red-100 text-red-800 px-3 py-1 rounded-full text-sm">
                        <?php echo $request['days_pending'] > 1 ? $request['days_pending'] . ' hari' : 'Baru'; ?>
                    </span>
                </div>

                <!-- Borrower Info -->
                <div class="bg-gray-50 rounded-lg p-4 mb-4">
                    <h4 class="font-semibold text-gray-800 mb-2">Peminjam</h4>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
                        <div>
                            <span class="text-gray-600">Nama:</span>
                            <p class="font-medium"><?php echo $request['borrower_name']; ?></p>
                        </div>
                        <div>
                            <span class="text-gray-600">ID:</span>
                            <p class="font-medium"><?php echo $request['borrower_employee_id']; ?></p>
                        </div>
                        <div>
                            <span class="text-gray-600">Jabatan:</span>
                            <p class="font-medium"><?php echo $request['jabatan']; ?></p>
                        </div>
                        <div>
                            <span class="text-gray-600">Organisasi:</span>
                            <p class="font-medium"><?php echo $request['organization']; ?></p>
                        </div>
                        <div>
                            <span class="text-gray-600">workcenter:</span>
                            <p class="font-medium"><?php echo $request['workcenter'] ?? '-'; ?></p>
                        </div>
                        <div>
                            <span class="text-gray-600">Preference Pro:</span>
                            <p class="font-medium"><?php echo $request['preference_pro'] ?? '-'; ?></p>
                        </div>
                    </div>
                    
                    <?php if ($request['notes']): ?>
                    <div class="mt-3">
                        <span class="text-gray-600">Catatan:</span>
                        <p class="font-medium"><?php echo nl2br(htmlspecialchars($request['notes'])); ?></p>
                    </div>
                    <?php endif; ?>
                    
                    <div class="mt-3">
                        <span class="text-gray-600">Tanggal Pengajuan:</span>
                        <p class="font-medium"><?php echo date('d F Y, H:i', strtotime($request['created_at'])); ?> WIB</p>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="flex gap-3">
                    <form method="POST" class="inline" onsubmit="return confirm('Yakin ingin menyetujui permintaan ini?')">
                        <input type="hidden" name="request_id" value="<?php echo $request['id']; ?>">
                        <input type="hidden" name="action" value="approve">
                        <button type="submit" 
                                class="bg-green-500 hover:bg-green-600 text-white px-6 py-2 rounded-lg font-medium 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>
                    </form>
                    
                    <form method="POST" class="inline" onsubmit="return confirm('Yakin ingin menolak permintaan ini?')">
                        <input type="hidden" name="request_id" value="<?php echo $request['id']; ?>">
                        <input type="hidden" name="action" value="reject">
                        <button type="submit" 
                                class="bg-red-500 hover:bg-red-600 text-white px-6 py-2 rounded-lg font-medium 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>
                    </form>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

    <script>
        // Auto refresh every 2 minutes
        setInterval(function() {
            if (!document.querySelector('form:hover')) {
                location.reload();
            }
        }, 120000);

        // Add loading state to buttons
        document.querySelectorAll('form').forEach(form => {
            form.addEventListener('submit', function() {
                const button = this.querySelector('button[type="submit"]');
                button.disabled = true;
                button.innerHTML = '<div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>Processing...';
            });
        });
    </script>
</body>
</html>