<?php
require_once '../includes/header.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: /dashboard.php');
    exit;
}

$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf();
    $order_id = $_POST['order_id'];
    $action = $_POST['action'];
    $new_status = ($action === 'approve') ? 'completed' : 'rejected';

    try {
        $stmt = $pdo->prepare("UPDATE orders SET status = ?, confirmation_date = CURRENT_TIMESTAMP WHERE id = ?");
        if ($stmt->execute([$new_status, $order_id])) {
            $message = "Status pesanan #" . e($order_id) . " berhasil diubah menjadi '" . e($new_status) . "'.";
        } else {
            $error = "Gagal mengubah status pesanan.";
        }
    } catch (PDOException $e) {
        $error = "Database error: " . $e->getMessage();
        error_log($e->getMessage());
    }
}

// Ambil semua pesanan untuk ditampilkan
$orders_stmt = $pdo->query("
    SELECT o.*, u.username, c.title as course_title 
    FROM orders o 
    JOIN users u ON o.user_id = u.id 
    JOIN courses c ON o.course_id = c.id 
    ORDER BY o.order_date DESC
");
$orders = $orders_stmt->fetchAll();
?>
<main class="container mx-auto p-4 md:p-8">
    <a href="index.php" class="text-blue-500 font-semibold hover:underline mb-6 inline-block">&larr; Kembali ke Admin Dashboard</a>
    <h1 class="text-3xl font-bold text-gray-800 mb-8">Kelola Pesanan</h1>
    <?php if ($message): ?><div class="bg-green-100 p-4 rounded-lg mb-6 text-green-800"><?= e($message) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="bg-red-100 p-4 rounded-lg mb-6 text-red-800"><?= e($error) ?></div><?php endif; ?>
    
    <div class="bg-white rounded-xl shadow-lg overflow-x-auto">
        <table class="w-full text-sm text-left">
            <thead class="text-xs text-gray-700 uppercase bg-gray-50">
                <tr>
                    <th class="px-6 py-3">ID</th>
                    <th class="px-6 py-3">Tanggal</th>
                    <th class="px-6 py-3">Pengguna</th>
                    <th class="px-6 py-3">Kursus</th>
                    <th class="px-6 py-3">Jumlah</th>
                    <th class="px-6 py-3">Status</th>
                    <th class="px-6 py-3">Bukti</th>
                    <th class="px-6 py-3">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($orders)): ?>
                    <tr><td colspan="8" class="text-center py-6 text-gray-500">Belum ada pesanan.</td></tr>
                <?php else: ?>
                    <?php foreach ($orders as $order): ?>
                    <tr class="border-b hover:bg-gray-50">
                        <td class="px-6 py-4 font-bold">#<?= $order['id'] ?></td>
                        <td class="px-6 py-4 text-gray-600"><?= date('d M Y', strtotime($order['order_date'])) ?></td>
                        <td class="px-6 py-4"><?= e($order['username']) ?></td>
                        <td class="px-6 py-4"><?= e($order['course_title']) ?></td>
                        <td class="px-6 py-4">Rp <?= number_format($order['amount']) ?></td>
                        <td class="px-6 py-4">
                            <span class="px-2 py-1 font-semibold text-xs rounded-full 
                            <?= $order['status'] === 'completed' ? 'bg-green-100 text-green-800' : '' ?>
                            <?= $order['status'] === 'awaiting_confirmation' ? 'bg-yellow-100 text-yellow-800' : '' ?>
                            <?= $order['status'] === 'pending' ? 'bg-gray-100 text-gray-800' : '' ?>
                            <?= $order['status'] === 'rejected' ? 'bg-red-100 text-red-800' : '' ?>
                            "><?= e(str_replace('_', ' ', ucfirst($order['status']))) ?></span>
                        </td>
                        <td class="px-6 py-4">
                            <?php if ($order['payment_proof']): ?>
                                <a href="/<?= e($order['payment_proof']) ?>" target="_blank" class="text-blue-600 hover:underline">Lihat</a>
                            <?php else: ?> - <?php endif; ?>
                        </td>
                        <td class="px-6 py-4">
                            <?php if ($order['status'] === 'awaiting_confirmation'): ?>
                                <div class="flex gap-2">
                                    <form method="POST" action="manage_orders.php">
                                        <input type="hidden" name="csrf_token" value="<?= e(generate_csrf_token()); ?>">
                                        <input type="hidden" name="order_id" value="<?= $order['id'] ?>">
                                        <input type="hidden" name="action" value="approve">
                                        <button type="submit" class="text-xs bg-green-500 text-white px-2 py-1 rounded hover:bg-green-600">Setujui</button>
                                    </form>
                                    <form method="POST" action="manage_orders.php">
                                        <input type="hidden" name="csrf_token" value="<?= e(generate_csrf_token()); ?>">
                                        <input type="hidden" name="order_id" value="<?= $order['id'] ?>">
                                        <input type="hidden" name="action" value="reject">
                                        <button type="submit" class="text-xs bg-red-500 text-white px-2 py-1 rounded hover:bg-red-600">Tolak</button>
                                    </form>
                                </div>
                            <?php else: ?> - <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</main>
<?php require_once '../includes/footer.php'; ?>