<?php
/**
 * ============================================================================
 * buyer/orders.php
 * Buyer Orders Management - View and track all purchase orders
 * ============================================================================
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/BuyerSystem.php';

// Check login
if (!isLoggedIn()) {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

// Check user type
if (getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/dashboard/');
    exit();
}

// Initialize
use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();
$buyerSystem = new BuyerSystem($database, $currentUserId);

// Handle order cancellation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'cancel_order') {
    try {
        $orderId = (int)$_POST['order_id'];
        
        // Verify order belongs to buyer
        $sql = "SELECT * FROM orders WHERE id = ? AND buyer_id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$orderId, $currentUserId]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$order) {
            throw new Exception('Order not found');
        }
        
        if (!in_array($order['status'], ['pending', 'confirmed'])) {
            throw new Exception('Order cannot be cancelled at this stage');
        }
        
        $db->beginTransaction();
        
        // Update order status
        $sql = "UPDATE orders SET status = 'cancelled', updated_at = NOW() WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$orderId]);
        
        // Restore product quantity
        $sql = "UPDATE products SET quantity = quantity + ?, status = 'available' WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$order['quantity'], $order['product_id']]);
        
        // Notify seller
        $sql = "INSERT INTO notifications (user_id, title, message, type, icon, link) 
                VALUES (?, 'Order Cancelled', ?, 'warning', 'x-circle', ?)";
        $stmt = $db->prepare($sql);
        $stmt->execute([
            $order['seller_id'],
            "Order #{$order['order_number']} was cancelled by the buyer",
            APP_URL . "/seller/orders.php?id={$orderId}"
        ]);
        
        $db->commit();
        
        $_SESSION['flash_message'] = 'Order cancelled successfully';
        $_SESSION['flash_type'] = 'success';
        
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        $_SESSION['flash_message'] = 'Error: ' . $e->getMessage();
        $_SESSION['flash_type'] = 'error';
    }
    
    header('Location: ' . APP_URL . '/buyer/orders.php');
    exit();
}

// Filter handling
$filters = [
    'status' => $_GET['status'] ?? '',
    'from_date' => $_GET['from_date'] ?? '',
    'to_date' => $_GET['to_date'] ?? '',
    'search' => $_GET['search'] ?? ''
];

// Get orders
$orders = $buyerSystem->getPurchaseOrders($filters);

// Get statistics
$sql = "SELECT 
            COUNT(*) as total,
            SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
            SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) as confirmed,
            SUM(CASE WHEN status = 'processing' THEN 1 ELSE 0 END) as processing,
            SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
            SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled,
            SUM(total_amount) as total_value
        FROM orders WHERE buyer_id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$orderStats = $stmt->fetch(PDO::FETCH_ASSOC);

$pageTitle = 'My Orders';
$breadcrumbs = [
    ['title' => 'Orders', 'url' => '']
];

require_once __DIR__ . '/includes/base.php';
renderBuyerHeader($pageTitle, $breadcrumbs);
?>

<style>
    .filter-card {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }
    
    .stats-card {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }
    
    .stat-item {
        text-align: center;
        padding: 1rem;
        border-right: 1px solid #e5e7eb;
    }
    
    .stat-item:last-child {
        border-right: none;
    }
    
    .stat-value {
        font-size: 1.75rem;
        font-weight: bold;
        color: var(--primary-color);
    }
    
    .stat-label {
        font-size: 0.875rem;
        color: #6b7280;
        margin-top: 0.25rem;
    }
    
    .order-card {
        background: white;
        border-radius: 12px;
        margin-bottom: 1rem;
        border: 1px solid #e5e7eb;
        transition: all 0.2s ease;
    }
    
    .order-card:hover {
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        border-color: var(--primary-color);
    }
    
    .order-header {
        padding: 1.25rem;
        border-bottom: 1px solid #e5e7eb;
        display: flex;
        justify-content: between;
        align-items: center;
    }
    
    .order-body {
        padding: 1.25rem;
    }
    
    .order-footer {
        padding: 1rem 1.25rem;
        background: #f9fafb;
        border-top: 1px solid #e5e7eb;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .order-number {
        font-size: 1.1rem;
        font-weight: bold;
        color: #1f2937;
    }
    
    .order-date {
        font-size: 0.875rem;
        color: #6b7280;
    }
    
    .product-info {
        display: flex;
        gap: 1rem;
        margin-bottom: 1rem;
    }
    
    .product-image {
        width: 80px;
        height: 80px;
        border-radius: 8px;
        object-fit: cover;
    }
    
    .filter-badge {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        background: var(--primary-color);
        color: white;
        border-radius: 20px;
        font-size: 0.75rem;
        margin-right: 0.5rem;
        margin-bottom: 0.5rem;
    }
</style>

<!-- Order Statistics -->
<div class="stats-card">
    <h5 class="mb-3"><i class="bi bi-graph-up me-2"></i>Order Statistics</h5>
    <div class="row">
        <div class="col-md-2 col-6">
            <div class="stat-item">
                <div class="stat-value"><?php echo number_format($orderStats['total']); ?></div>
                <div class="stat-label">Total Orders</div>
            </div>
        </div>
        <div class="col-md-2 col-6">
            <div class="stat-item">
                <div class="stat-value text-warning"><?php echo number_format($orderStats['pending']); ?></div>
                <div class="stat-label">Pending</div>
            </div>
        </div>
        <div class="col-md-2 col-6">
            <div class="stat-item">
                <div class="stat-value text-info"><?php echo number_format($orderStats['confirmed']); ?></div>
                <div class="stat-label">Confirmed</div>
            </div>
        </div>
        <div class="col-md-2 col-6">
            <div class="stat-item">
                <div class="stat-value text-primary"><?php echo number_format($orderStats['processing']); ?></div>
                <div class="stat-label">Processing</div>
            </div>
        </div>
        <div class="col-md-2 col-6">
            <div class="stat-item">
                <div class="stat-value text-success"><?php echo number_format($orderStats['completed']); ?></div>
                <div class="stat-label">Completed</div>
            </div>
        </div>
        <div class="col-md-2 col-6">
            <div class="stat-item">
                <div class="stat-value text-danger"><?php echo number_format($orderStats['cancelled']); ?></div>
                <div class="stat-label">Cancelled</div>
            </div>
        </div>
    </div>
    <div class="text-center mt-3 pt-3 border-top">
        <h4 class="mb-0 text-success">
            <i class="bi bi-cash me-2"></i><?php echo formatCurrency($orderStats['total_value'] ?? 0); ?>
        </h4>
        <small class="text-muted">Total Order Value</small>
    </div>
</div>

<!-- Filters -->
<div class="filter-card">
    <form method="GET" class="row g-3">
        <div class="col-md-3">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
                <option value="">All Statuses</option>
                <option value="pending" <?php echo $filters['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                <option value="confirmed" <?php echo $filters['status'] === 'confirmed' ? 'selected' : ''; ?>>Confirmed</option>
                <option value="processing" <?php echo $filters['status'] === 'processing' ? 'selected' : ''; ?>>Processing</option>
                <option value="completed" <?php echo $filters['status'] === 'completed' ? 'selected' : ''; ?>>Completed</option>
                <option value="cancelled" <?php echo $filters['status'] === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
            </select>
        </div>
        
        <div class="col-md-3">
            <label class="form-label">From Date</label>
            <input type="date" name="from_date" class="form-control" value="<?php echo htmlspecialchars($filters['from_date']); ?>">
        </div>
        
        <div class="col-md-3">
            <label class="form-label">To Date</label>
            <input type="date" name="to_date" class="form-control" value="<?php echo htmlspecialchars($filters['to_date']); ?>">
        </div>
        
        <div class="col-md-3">
            <label class="form-label">Search</label>
            <input type="text" name="search" class="form-control" placeholder="Order #, Product, Seller..." value="<?php echo htmlspecialchars($filters['search']); ?>">
        </div>
        
        <div class="col-12">
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-funnel me-2"></i>Apply Filters
            </button>
            <a href="<?php echo APP_URL; ?>/buyer/orders.php" class="btn btn-outline-secondary">
                <i class="bi bi-x-circle me-2"></i>Clear
            </a>
        </div>
    </form>
    
    <!-- Active Filters Display -->
    <?php if (!empty(array_filter($filters))): ?>
    <div class="mt-3">
        <strong>Active Filters:</strong>
        <?php if ($filters['status']): ?>
        <span class="filter-badge"><?php echo ucfirst($filters['status']); ?></span>
        <?php endif; ?>
        <?php if ($filters['from_date']): ?>
        <span class="filter-badge">From: <?php echo $filters['from_date']; ?></span>
        <?php endif; ?>
        <?php if ($filters['to_date']): ?>
        <span class="filter-badge">To: <?php echo $filters['to_date']; ?></span>
        <?php endif; ?>
        <?php if ($filters['search']): ?>
        <span class="filter-badge">Search: <?php echo htmlspecialchars($filters['search']); ?></span>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<!-- Orders List -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-0 py-3">
        <h5 class="mb-0"><i class="bi bi-cart-check me-2"></i>My Orders (<?php echo count($orders); ?>)</h5>
    </div>
    <div class="card-body">
        <?php if (empty($orders)): ?>
            <div class="text-center py-5">
                <i class="bi bi-inbox" style="font-size: 4rem; color: #d1d5db;"></i>
                <h5 class="mt-3 text-muted">No orders found</h5>
                <p class="text-muted">
                    <?php if (!empty(array_filter($filters))): ?>
                        Try adjusting your filters
                    <?php else: ?>
                        Start shopping in the marketplace
                    <?php endif; ?>
                </p>
                <a href="<?php echo APP_URL; ?>/marketplace/" class="btn btn-primary mt-2">
                    <i class="bi bi-shop me-2"></i>Browse Products
                </a>
            </div>
        <?php else: ?>
            <?php foreach ($orders as $order): ?>
            <div class="order-card">
                <div class="order-header">
                    <div class="flex-grow-1">
                        <div class="order-number">
                            <i class="bi bi-receipt me-2"></i><?php echo htmlspecialchars($order['order_number']); ?>
                        </div>
                        <div class="order-date">
                            <i class="bi bi-calendar me-1"></i><?php echo date('M j, Y', strtotime($order['created_at'])); ?>
                            <span class="ms-2"><i class="bi bi-clock me-1"></i><?php echo timeAgo($order['created_at']); ?></span>
                        </div>
                    </div>
                    <div>
                        <?php echo getOrderStatusBadge($order['status']); ?>
                        <?php echo getPaymentStatusBadge($order['payment_status']); ?>
                    </div>
                </div>
                
                <div class="order-body">
                    <div class="row">
                        <div class="col-md-8">
                            <h6 class="mb-2"><?php echo htmlspecialchars($order['product_name']); ?></h6>
                            <p class="text-muted small mb-2">
                                <i class="bi bi-person me-1"></i>
                                <strong>Seller:</strong> <?php echo htmlspecialchars($order['seller_name']); ?>
                                <?php if (!empty($order['seller_district'])): ?>
                                <span class="ms-2"><i class="bi bi-geo-alt me-1"></i><?php echo htmlspecialchars($order['seller_district']); ?></span>
                                <?php endif; ?>
                            </p>
                            <p class="text-muted small mb-2">
                                <i class="bi bi-box me-1"></i>
                                <strong>Quantity:</strong> <?php echo number_format($order['quantity'], 2); ?> <?php echo htmlspecialchars($order['unit'] ?? 'units'); ?>
                                <span class="ms-3"><i class="bi bi-cash me-1"></i>
                                <strong>Unit Price:</strong> <?php echo formatCurrency($order['unit_price']); ?></span>
                            </p>
                            <?php if (!empty($order['delivery_address'])): ?>
                            <p class="text-muted small mb-0">
                                <i class="bi bi-truck me-1"></i>
                                <strong>Delivery:</strong> <?php echo htmlspecialchars($order['delivery_address']); ?>
                            </p>
                            <?php endif; ?>
                        </div>
                        
                        <div class="col-md-4 text-md-end">
                            <h4 class="text-success mb-2"><?php echo formatCurrency($order['total_amount']); ?></h4>
                            <small class="text-muted d-block">Total Amount</small>
                            <?php if ($order['status'] === 'completed'): ?>
                            <small class="text-muted">
                                <i class="bi bi-check-circle-fill text-success me-1"></i>
                                Delivered <?php echo timeAgo($order['updated_at']); ?>
                            </small>
                            <?php elseif ($order['status'] === 'processing'): ?>
                            <small class="text-muted">
                                <i class="bi bi-truck text-primary me-1"></i>
                                In Transit
                            </small>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <div class="order-footer">
                    <div>
                        <a href="<?php echo APP_URL; ?>/buyer/order-details.php?id=<?php echo $order['id']; ?>" class="btn btn-sm btn-outline-primary">
                            <i class="bi bi-eye me-1"></i> View Details
                        </a>
                        <a href="<?php echo APP_URL; ?>/chat/?user=<?php echo $order['seller_id']; ?>" class="btn btn-sm btn-outline-info">
                            <i class="bi bi-chat-dots me-1"></i> Contact Seller
                        </a>
                    </div>
                    <div>
                        <?php if (canCancelOrder($order)): ?>
                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="cancelOrder(<?php echo $order['id']; ?>, '<?php echo htmlspecialchars($order['order_number']); ?>')">
                            <i class="bi bi-x-circle me-1"></i> Cancel Order
                        </button>
                        <?php endif; ?>
                        
                        <?php if (canReviewOrder($order)): ?>
                        <a href="<?php echo APP_URL; ?>/buyer/review-order.php?id=<?php echo $order['id']; ?>" class="btn btn-sm btn-outline-warning">
                            <i class="bi bi-star me-1"></i> Leave Review
                        </a>
                        <?php endif; ?>
                        
                        <?php if ($order['status'] === 'completed'): ?>
                        <a href="<?php echo APP_URL; ?>/buyer/reorder.php?id=<?php echo $order['id']; ?>" class="btn btn-sm btn-success">
                            <i class="bi bi-arrow-repeat me-1"></i> Reorder
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<!-- Cancel Order Form (Hidden) -->
<form id="cancelOrderForm" method="POST" style="display: none;">
    <input type="hidden" name="action" value="cancel_order">
    <input type="hidden" name="order_id" id="cancelOrderId">
</form>

<script>
function cancelOrder(orderId, orderNumber) {
    Swal.fire({
        title: 'Cancel Order?',
        html: `Are you sure you want to cancel order <strong>${orderNumber}</strong>?<br><small class="text-muted">This action cannot be undone.</small>`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, Cancel Order',
        cancelButtonText: 'No, Keep It'
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('cancelOrderId').value = orderId;
            document.getElementById('cancelOrderForm').submit();
        }
    });
}
</script>

<?php
renderBuyerFooter();
?>