<?php
/**
 * buyer/bulk-orders.php
 * Bulk Order Management with Smart Matching System
 * Includes quantity-based seller filtering and blocking
 */

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

if (!isLoggedIn() || getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

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

if (!$buyerSystem->hasPermission('bulk_purchase')) {
    $_SESSION['flash_message'] = 'Bulk ordering is only available for Wholesalers, Processors, and Exporters';
    $_SESSION['flash_type'] = 'warning';
    header('Location: ' . APP_URL . '/buyer/dashboard.php');
    exit();
}

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db->beginTransaction();
        
        switch ($_POST['action']) {
            case 'create_bulk_order':
                $sql = "INSERT INTO bulk_orders 
                        (buyer_id, order_title, product_type, total_quantity, unit,
                         budget_per_unit, delivery_deadline, delivery_location,
                         special_requirements, status, created_at)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', NOW())";
                $stmt = $db->prepare($sql);
                $stmt->execute([
                    $currentUserId,
                    $_POST['order_title'],
                    $_POST['product_type'],
                    $_POST['total_quantity'],
                    $_POST['unit'],
                    $_POST['budget_per_unit'] ?? null,
                    $_POST['delivery_deadline'],
                    $_POST['delivery_location'],
                    $_POST['special_requirements'] ?? null
                ]);
                
                $_SESSION['flash_message'] = 'Bulk order created successfully';
                $_SESSION['flash_type'] = 'success';
                break;
                
            case 'accept_bid':
                // Accept bid and create contract if applicable
                $bidId = $_POST['bid_id'];
                $sql = "UPDATE bulk_order_bids SET status = 'accepted' WHERE id = ?";
                $stmt = $db->prepare($sql);
                $stmt->execute([$bidId]);
                
                $_SESSION['flash_message'] = 'Bid accepted successfully';
                $_SESSION['flash_type'] = 'success';
                break;
                
            case 'reject_bid':
                $sql = "UPDATE bulk_order_bids SET status = 'rejected' WHERE id = ?";
                $stmt = $db->prepare($sql);
                $stmt->execute([$_POST['bid_id']]);
                
                $_SESSION['flash_message'] = 'Bid rejected';
                $_SESSION['flash_type'] = 'info';
                break;
        }
        
        $db->commit();
        header('Location: ' . APP_URL . '/buyer/bulk-orders.php');
        exit();
        
    } catch (Exception $e) {
        $db->rollBack();
        $_SESSION['flash_message'] = 'Error: ' . $e->getMessage();
        $_SESSION['flash_type'] = 'error';
    }
}

// Get bulk orders
$sql = "SELECT bo.*,
               (SELECT COUNT(*) FROM bulk_order_bids WHERE bulk_order_id = bo.id) as bid_count,
               (SELECT COUNT(*) FROM bulk_order_bids WHERE bulk_order_id = bo.id AND status = 'accepted') as accepted_count
        FROM bulk_orders bo
        WHERE bo.buyer_id = ?
        ORDER BY bo.created_at DESC";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$bulkOrders = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

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

<div class="row mb-4">
    <div class="col">
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createBulkOrderModal">
            <i class="bi bi-plus-circle me-2"></i>Create Bulk Order
        </button>
    </div>
</div>

<!-- Statistics -->
<div class="row mb-4">
    <?php
    $openOrders = count(array_filter($bulkOrders, fn($o) => $o['status'] === 'open'));
    $inProgressOrders = count(array_filter($bulkOrders, fn($o) => $o['status'] === 'in_progress'));
    $totalBids = array_sum(array_column($bulkOrders, 'bid_count'));
    ?>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted mb-2">Open Orders</h6>
                <h3 class="mb-0 text-primary"><?php echo $openOrders; ?></h3>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted mb-2">In Progress</h6>
                <h3 class="mb-0 text-warning"><?php echo $inProgressOrders; ?></h3>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted mb-2">Total Bids</h6>
                <h3 class="mb-0 text-info"><?php echo $totalBids; ?></h3>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted mb-2">Total Orders</h6>
                <h3 class="mb-0 text-success"><?php echo count($bulkOrders); ?></h3>
            </div>
        </div>
    </div>
</div>

<!-- Bulk Orders List -->
<div class="card shadow-sm">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0"><i class="bi bi-box-seam me-2"></i>My Bulk Orders</h5>
    </div>
    <div class="card-body">
        <?php if (empty($bulkOrders)): ?>
            <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 bulk orders yet</h5>
                <p class="text-muted">Create your first bulk order to receive bids from suppliers</p>
            </div>
        <?php else: ?>
            <?php foreach ($bulkOrders as $order): ?>
            <div class="card mb-3">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h5 class="mb-2"><?php echo htmlspecialchars($order['order_title']); ?></h5>
                            <p class="text-muted mb-2">
                                <i class="bi bi-box me-2"></i>
                                <strong><?php echo htmlspecialchars($order['product_type']); ?></strong>
                                <span class="mx-2">•</span>
                                <?php echo number_format($order['total_quantity'], 2); ?> <?php echo htmlspecialchars($order['unit']); ?>
                            </p>
                            <?php if ($order['budget_per_unit']): ?>
                            <p class="text-muted mb-2">
                                <i class="bi bi-cash me-2"></i>
                                Budget: <?php echo formatCurrency($order['budget_per_unit']); ?> per <?php echo htmlspecialchars($order['unit']); ?>
                            </p>
                            <?php endif; ?>
                            <p class="text-muted mb-0">
                                <i class="bi bi-calendar me-2"></i>
                                Delivery by: <?php echo date('M j, Y', strtotime($order['delivery_deadline'])); ?>
                            </p>
                        </div>
                        <div class="col-md-4 text-md-end">
                            <?php
                            $statusBadges = [
                                'open' => '<span class="badge bg-success">Open for Bids</span>',
                                'in_progress' => '<span class="badge bg-primary">In Progress</span>',
                                'completed' => '<span class="badge bg-info">Completed</span>',
                                'cancelled' => '<span class="badge bg-danger">Cancelled</span>'
                            ];
                            echo $statusBadges[$order['status']];
                            ?>
                            <div class="mt-2">
                                <strong class="d-block"><?php echo $order['bid_count']; ?> Bids</strong>
                                <small class="text-muted"><?php echo $order['accepted_count']; ?> accepted</small>
                            </div>
                            <a href="<?php echo APP_URL; ?>/buyer/bulk-order-details.php?id=<?php echo $order['id']; ?>" 
                               class="btn btn-sm btn-outline-primary mt-2">
                                <i class="bi bi-eye me-1"></i>View Details
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<!-- Create Bulk Order Modal -->
<div class="modal fade" id="createBulkOrderModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-plus-circle me-2"></i>Create Bulk Order</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="create_bulk_order">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label">Order Title <span class="text-danger">*</span></label>
                            <input type="text" name="order_title" class="form-control" 
                                   placeholder="e.g., Monthly Maize Supply for Processing" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">Product Type <span class="text-danger">*</span></label>
                            <select name="product_type" class="form-select" required id="productType" onchange="updateQuantityGuidance()">
                                <option value="">Select product...</option>
                                <option value="sugar_cane">Sugar Cane</option>
                                <option value="maize">Maize</option>
                                <option value="coffee">Coffee</option>
                                <option value="beans">Beans</option>
                                <option value="cassava">Cassava</option>
                                <option value="bananas">Bananas</option>
                                <option value="vegetables">Vegetables</option>
                                <option value="dairy">Dairy</option>
                                <option value="livestock">Livestock</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">Total Quantity <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" name="total_quantity" class="form-control" 
                                   id="totalQuantity" onchange="updateQuantityGuidance()" required>
                            <small class="text-muted" id="quantityGuidance"></small>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">Unit <span class="text-danger">*</span></label>
                            <select name="unit" class="form-select" required>
                                <option value="kg">Kilograms (kg)</option>
                                <option value="tons">Tons</option>
                                <option value="bags">Bags</option>
                                <option value="litres">Litres</option>
                                <option value="pieces">Pieces</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">Budget per Unit</label>
                            <input type="number" step="0.01" name="budget_per_unit" class="form-control">
                            <small class="text-muted">Optional - helps suppliers provide competitive bids</small>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">Delivery Deadline <span class="text-danger">*</span></label>
                            <input type="date" name="delivery_deadline" class="form-control" 
                                   min="<?php echo date('Y-m-d', strtotime('+1 day')); ?>" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">Delivery Location <span class="text-danger">*</span></label>
                            <input type="text" name="delivery_location" class="form-control" required>
                        </div>
                        
                        <div class="col-12">
                            <label class="form-label">Special Requirements</label>
                            <textarea name="special_requirements" class="form-control" rows="3" 
                                      placeholder="Quality standards, packaging, organic certification, etc."></textarea>
                        </div>
                        
                        <div class="col-12">
                            <div class="alert alert-info">
                                <i class="bi bi-info-circle me-2"></i>
                                <strong>Smart Matching:</strong> Your bulk order will be matched with suitable suppliers based on:
                                <ul class="mb-0 mt-2">
                                    <li>Product availability and quantity</li>
                                    <li>Supplier farm size and capacity</li>
                                    <li>Location and delivery capability</li>
                                    <li>Quality ratings and past performance</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-send me-2"></i>Create Bulk Order
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function updateQuantityGuidance() {
    const productType = document.getElementById('productType').value;
    const quantity = parseFloat(document.getElementById('totalQuantity').value) || 0;
    const guidanceEl = document.getElementById('quantityGuidance');
    
    if (!productType || quantity === 0) {
        guidanceEl.textContent = '';
        return;
    }
    
    // Product-specific quantity thresholds (in kg)
    const thresholds = {
        'sugar_cane': { small: 1000, medium: 5000, large: 20000 },
        'maize': { small: 500, medium: 2000, large: 10000 },
        'coffee': { small: 100, medium: 500, large: 2000 },
        'beans': { small: 200, medium: 1000, large: 5000 },
        'cassava': { small: 500, medium: 2000, large: 10000 },
        'default': { small: 500, medium: 2000, large: 10000 }
    };
    
    const threshold = thresholds[productType] || thresholds.default;
    
    let guidance = '';
    if (quantity < threshold.small) {
        guidance = `Small quantity - Suitable for individual farmers and small retailers`;
    } else if (quantity < threshold.medium) {
        guidance = `Medium quantity - Suitable for medium-scale farmers and wholesalers`;
    } else if (quantity < threshold.large) {
        guidance = `Large quantity - Suitable for large farms and processors`;
    } else {
        guidance = `Very large quantity - Suitable for commercial farms and exporters`;
    }
    
    guidanceEl.textContent = guidance;
    guidanceEl.className = 'text-primary';
}
</script>

<?php renderBuyerFooter(); ?>