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

// Check if admin is logged in
if (!isAdminLoggedIn()) {
    redirect(SITE_URL . 'admin/login.php');
}

$pageTitle = "Kelola Pesanan";

// Handle status update
if (isset($_GET['update_status']) && isset($_GET['order_id']) && isset($_GET['status'])) {
    $order_id = (int)$_GET['order_id'];
    $status = $_GET['status'];
    $allowed_statuses = ['pending', 'processing', 'shipped', 'delivered', 'cancelled'];
    
    if (in_array($status, $allowed_statuses)) {
        try {
            $conn = connectDB();
            $stmt = $conn->prepare("UPDATE orders SET status = :status WHERE order_id = :order_id");
            $stmt->bindParam(':status', $status);
            $stmt->bindParam(':order_id', $order_id);
            $stmt->execute();
            
            $success = "Status pesanan berhasil diperbarui";
        } catch (PDOException $e) {
            $error = "Kesalahan: " . $e->getMessage();
        }
    }
}

// Filter by status
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$allowed_filters = ['', 'pending', 'processing', 'shipped', 'delivered', 'cancelled'];
if (!in_array($status_filter, $allowed_filters)) {
    $status_filter = '';
}

// Get orders with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

try {
    $conn = connectDB();
    
    // Build query based on filters
    $query = "SELECT o.*, u.name as user_name, 
              CASE WHEN o.payment_proof IS NOT NULL AND o.payment_verified_at IS NULL AND o.payment_rejected_at IS NULL THEN 1 ELSE 0 END as needs_verification 
              FROM orders o LEFT JOIN users u ON o.user_id = u.user_id";
    $countQuery = "SELECT COUNT(*) as total FROM orders";
    $params = [];
    
    if (!empty($status_filter)) {
        $query .= " WHERE o.status = :status";
        $countQuery .= " WHERE status = :status";
        $params[':status'] = $status_filter;
    }
    
    $query .= " ORDER BY o.created_at DESC LIMIT :offset, :limit";
    
    // Count total orders
    $stmt = $conn->prepare($countQuery);
    if (!empty($params)) {
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
    }
    $stmt->execute();
    $totalOrders = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    $totalPages = ceil($totalOrders / $limit);
    
    // Get orders for current page
    $stmt = $conn->prepare($query);
    if (!empty($params)) {
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
    }
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $error = "Kesalahan: " . $e->getMessage();
}

include '../header.php';
?>

<div class="admin-header">
    <h1>Kelola Pesanan</h1>
    <div class="filter-options">
        <a href="<?php echo SITE_URL; ?>admin/orders/index.php" class="filter-btn <?php echo empty($status_filter) ? 'active' : ''; ?>">Semua</a>
        <a href="<?php echo SITE_URL; ?>admin/orders/index.php?status=pending" class="filter-btn <?php echo $status_filter === 'pending' ? 'active' : ''; ?>">Menunggu Pembayaran</a>
        <a href="<?php echo SITE_URL; ?>admin/orders/index.php?status=processing" class="filter-btn <?php echo $status_filter === 'processing' ? 'active' : ''; ?>">Diproses</a>
        <a href="<?php echo SITE_URL; ?>admin/orders/index.php?status=shipped" class="filter-btn <?php echo $status_filter === 'shipped' ? 'active' : ''; ?>">Dikirim</a>
        <a href="<?php echo SITE_URL; ?>admin/orders/index.php?status=delivered" class="filter-btn <?php echo $status_filter === 'delivered' ? 'active' : ''; ?>">Terkirim</a>
        <a href="<?php echo SITE_URL; ?>admin/orders/index.php?status=cancelled" class="filter-btn <?php echo $status_filter === 'cancelled' ? 'active' : ''; ?>">Dibatalkan</a>
    </div>
</div>

<?php if (isset($success)): ?>
    <div class="success"><?php echo $success; ?></div>
<?php endif; ?>

<?php if (isset($error)): ?>
    <div class="error"><?php echo $error; ?></div>
<?php endif; ?>

<div class="admin-content-box">
    <div class="table-responsive">
        <table class="admin-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Pelanggan</th>
                    <th>Total</th>
                    <th>Status</th>
                    <th>Tanggal</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($orders)): ?>
                    <tr>
                        <td colspan="6" class="text-center">Belum ada pesanan</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($orders as $order): ?>
                        <tr>
                            <td>#<?php echo $order['order_id']; ?></td>
                            <td><?php echo $order['user_name'] ?? 'Pengguna Tidak Ditemukan'; ?></td>
                            <td>Rp <?php echo number_format($order['total_amount'], 0, ',', '.'); ?></td>
                            <td>
                                <div class="status-dropdown">
                                    <span class="status-badge status-<?php echo $order['status']; ?>">
                                        <?php
                                        switch($order['status']) {
                                            case 'pending': echo 'Menunggu Pembayaran'; break;
                                            case 'processing': echo 'Diproses'; break;
                                            case 'shipped': echo 'Dikirim'; break;
                                            case 'delivered': echo 'Terkirim'; break;
                                            case 'cancelled': echo 'Dibatalkan'; break;
                                            default: echo $order['status']; break;
                                        }
                                        ?>
                                    </span>
                                    <?php if ($order['needs_verification']): ?>
                                    <span class="verification-badge">
                                        <i class="fas fa-exclamation-circle"></i> Butuh Verifikasi
                                    </span>
                                    <?php endif; ?>
                                    <div class="status-actions">
                                        <a href="<?php echo SITE_URL; ?>admin/orders/index.php?update_status=1&order_id=<?php echo $order['order_id']; ?>&status=pending">Menunggu</a>
                                        <a href="<?php echo SITE_URL; ?>admin/orders/index.php?update_status=1&order_id=<?php echo $order['order_id']; ?>&status=processing">Diproses</a>
                                        <a href="<?php echo SITE_URL; ?>admin/orders/index.php?update_status=1&order_id=<?php echo $order['order_id']; ?>&status=shipped">Dikirim</a>
                                        <a href="<?php echo SITE_URL; ?>admin/orders/index.php?update_status=1&order_id=<?php echo $order['order_id']; ?>&status=delivered">Terkirim</a>
                                        <a href="<?php echo SITE_URL; ?>admin/orders/index.php?update_status=1&order_id=<?php echo $order['order_id']; ?>&status=cancelled">Dibatalkan</a>
                                    </div>
                                </div>
                            </td>
                            <td><?php echo date('d/m/Y H:i', strtotime($order['created_at'])); ?></td>
                            <td>
                                <a href="<?php echo SITE_URL; ?>admin/orders/detail.php?id=<?php echo $order['order_id']; ?>" class="action-btn view-btn" title="Detail">
                                    <i class="fas fa-eye"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php
            $queryParams = [];
            if (!empty($status_filter)) {
                $queryParams[] = "status=$status_filter";
            }
            $queryString = !empty($queryParams) ? '&' . implode('&', $queryParams) : '';
            ?>
            
            <?php if ($page > 1): ?>
                <a href="<?php echo SITE_URL; ?>admin/orders/index.php?page=<?php echo $page - 1; ?><?php echo $queryString; ?>" class="page-link">&laquo; Sebelumnya</a>
            <?php endif; ?>
            
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <a href="<?php echo SITE_URL; ?>admin/orders/index.php?page=<?php echo $i; ?><?php echo $queryString; ?>" class="page-link <?php echo ($page == $i) ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
            
            <?php if ($page < $totalPages): ?>
                <a href="<?php echo SITE_URL; ?>admin/orders/index.php?page=<?php echo $page + 1; ?><?php echo $queryString; ?>" class="page-link">Berikutnya &raquo;</a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<style>
    .filter-options {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-bottom: 20px;
    }
    
    .filter-btn {
        padding: 5px 15px;
        background-color: #f4f4f4;
        border-radius: 20px;
        color: #333;
        text-decoration: none;
        font-size: 14px;
    }
    
    .filter-btn.active {
        background-color: var(--primary-color);
        color: white;
    }
    
    .status-dropdown {
        position: relative;
        display: inline-block;
    }
    
    .status-dropdown:hover .status-actions {
        display: block;
    }
    
    .status-actions {
        display: none;
        position: absolute;
        background-color: white;
        min-width: 150px;
        box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
        z-index: 1;
        border-radius: 4px;
        left: 50%;
        transform: translateX(-50%);
    }
    
    .status-actions a {
        color: black;
        padding: 8px 12px;
        text-decoration: none;
        display: block;
        text-align: center;
        font-size: 14px;
    }
    
    .status-actions a:hover {
        background-color: #f1f1f1;
    }
    
    .verification-badge {
        display: block;
        margin-top: 5px;
        background-color: #ff9800;
        color: white;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
        text-align: center;
    }
    
    .verification-badge i {
        margin-right: 5px;
    }
</style>

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