<?php
/**
 * Buyer Helper Functions
 * File: buyer/includes/helpers.php
 * 
 * Note: This file contains buyer-specific helper functions only.
 * Common functions are in includes/functions.php
 */

// Ensure we don't redeclare functions that exist in the main functions.php
if (!function_exists('formatBuyerType')) {
    /**
     * Format buyer type for display
     */
    function formatBuyerType($type) {
        $types = [
            'individual' => 'Individual Buyer',
            'retailer' => 'Retailer',
            'wholesaler' => 'Wholesaler',
            'processor' => 'Processor/Manufacturer',
            'exporter' => 'Exporter'
        ];
        
        return $types[$type] ?? ucfirst($type);
    }
}

if (!function_exists('getOrderStatusBadge')) {
    /**
     * Get order status badge HTML
     */
    function getOrderStatusBadge($status) {
        $badges = [
            'pending' => '<span class="badge bg-warning">Pending</span>',
            'confirmed' => '<span class="badge bg-info">Confirmed</span>',
            'processing' => '<span class="badge bg-primary">Processing</span>',
            'completed' => '<span class="badge bg-success">Completed</span>',
            'cancelled' => '<span class="badge bg-danger">Cancelled</span>'
        ];
        
        return $badges[$status] ?? '<span class="badge bg-secondary">' . ucfirst($status) . '</span>';
    }
}

if (!function_exists('getPaymentStatusBadge')) {
    /**
     * Get payment status badge HTML
     */
    function getPaymentStatusBadge($status) {
        $badges = [
            'unpaid' => '<span class="badge bg-danger">Unpaid</span>',
            'partial' => '<span class="badge bg-warning">Partial</span>',
            'paid' => '<span class="badge bg-success">Paid</span>'
        ];
        
        return $badges[$status] ?? '<span class="badge bg-secondary">' . ucfirst($status) . '</span>';
    }
}

if (!function_exists('calculatePercentage')) {
    /**
     * Calculate percentage
     */
    function calculatePercentage($part, $total) {
        if ($total == 0) return 0;
        return round(($part / $total) * 100, 1);
    }
}

if (!function_exists('truncateText')) {
    /**
     * Truncate text to specified length
     */
    function truncateText($text, $length = 100, $suffix = '...') {
        if (strlen($text) <= $length) {
            return $text;
        }
        return substr($text, 0, $length) . $suffix;
    }
}

if (!function_exists('getCategoryIcon')) {
    /**
     * Get product category icon
     */
    function getCategoryIcon($category) {
        $icons = [
            'sugar_cane' => 'bi-droplet',
            'poultry' => 'bi-egg',
            'maize' => 'bi-flower1',
            'vegetables' => 'bi-basket',
            'coffee' => 'bi-cup-hot',
            'beans' => 'bi-circle',
            'cassava' => 'bi-disc',
            'bananas' => 'bi-banana',
            'dairy' => 'bi-cup-straw',
            'livestock' => 'bi-piggy-bank',
            'other' => 'bi-three-dots'
        ];
        
        return $icons[$category] ?? 'bi-box';
    }
}

if (!function_exists('getCapacityColor')) {
    /**
     * Get buyer capacity color
     */
    function getCapacityColor($capacity) {
        $colors = [
            'Small' => 'info',
            'Medium' => 'primary',
            'Large' => 'success'
        ];
        
        return $colors[$capacity] ?? 'secondary';
    }
}

if (!function_exists('validateQuantity')) {
    /**
     * Validate quantity
     */
    function validateQuantity($quantity, $available) {
        if ($quantity <= 0) {
            return 'Quantity must be greater than 0';
        }
        
        if ($quantity > $available) {
            return 'Requested quantity exceeds available stock';
        }
        
        return true;
    }
}

if (!function_exists('getRatingStars')) {
    /**
     * Get supplier rating stars
     */
    function getRatingStars($rating) {
        $rating = round($rating, 1);
        $fullStars = floor($rating);
        $halfStar = ($rating - $fullStars) >= 0.5 ? 1 : 0;
        $emptyStars = 5 - $fullStars - $halfStar;
        
        $html = '';
        
        // Full stars
        for ($i = 0; $i < $fullStars; $i++) {
            $html .= '<i class="bi bi-star-fill text-warning"></i>';
        }
        
        // Half star
        if ($halfStar) {
            $html .= '<i class="bi bi-star-half text-warning"></i>';
        }
        
        // Empty stars
        for ($i = 0; $i < $emptyStars; $i++) {
            $html .= '<i class="bi bi-star text-muted"></i>';
        }
        
        $html .= ' <span class="text-muted">(' . number_format($rating, 1) . ')</span>';
        
        return $html;
    }
}

if (!function_exists('getDeliveryStatus')) {
    /**
     * Get delivery status
     */
    function getDeliveryStatus($order) {
        if ($order['status'] === 'completed') {
            return '<span class="badge bg-success"><i class="bi bi-check-circle"></i> Delivered</span>';
        } elseif ($order['status'] === 'processing') {
            return '<span class="badge bg-info"><i class="bi bi-truck"></i> In Transit</span>';
        } elseif ($order['status'] === 'confirmed') {
            return '<span class="badge bg-primary"><i class="bi bi-box-seam"></i> Preparing</span>';
        } else {
            return '<span class="badge bg-warning"><i class="bi bi-clock"></i> Pending</span>';
        }
    }
}

if (!function_exists('getEstimatedDelivery')) {
    /**
     * Calculate estimated delivery date
     */
    function getEstimatedDelivery($orderDate, $days = 3) {
        $timestamp = strtotime($orderDate);
        $deliveryDate = strtotime("+$days days", $timestamp);
        return date('M j, Y', $deliveryDate);
    }
}

if (!function_exists('getProductImage')) {
    /**
     * Get product image
     * Handles both JSON string and array formats
     */
    function getProductImage($images, $index = 0) {
        // Handle empty images
        if (empty($images)) {
            return APP_URL . '/assets/images/placeholder-product.jpg';
        }
        
        // If it's already an array, use it directly
        if (is_array($images)) {
            $imageArray = $images;
        } else {
            // Try to decode JSON string
            $imageArray = json_decode($images, true);
        }
        
        // Check if we have valid image data
        if (!empty($imageArray) && isset($imageArray[$index])) {
            $imagePath = $imageArray[$index];
            
            // If it's a full path starting with uploads/
            if (strpos($imagePath, 'uploads/') === 0) {
                return APP_URL . '/' . $imagePath;
            }
            
            // If it's just a filename
            $fullPath = UPLOAD_PATH . 'products/' . $imagePath;
            if (file_exists($fullPath)) {
                return APP_URL . '/uploads/products/' . $imagePath;
            }
            
            // Try the path as-is with APP_URL
            return APP_URL . '/' . $imagePath;
        }
        
        // Return placeholder if nothing works
        return APP_URL . '/assets/images/placeholder-product.jpg';
    }
}

if (!function_exists('getProductImages')) {
    /**
     * Get all product images as an array
     */
    function getProductImages($images) {
        // Handle empty images
        if (empty($images)) {
            return [APP_URL . '/assets/images/placeholder-product.jpg'];
        }
        
        // If it's already an array, use it directly
        if (is_array($images)) {
            $imageArray = $images;
        } else {
            // Try to decode JSON string
            $imageArray = json_decode($images, true);
        }
        
        // Process each image
        $processedImages = [];
        if (!empty($imageArray)) {
            foreach ($imageArray as $image) {
                // If it's a full path starting with uploads/
                if (strpos($image, 'uploads/') === 0) {
                    $processedImages[] = APP_URL . '/' . $image;
                } else {
                    // Try as filename in products folder
                    $processedImages[] = APP_URL . '/uploads/products/' . $image;
                }
            }
        }
        
        // Return placeholder if no valid images
        return !empty($processedImages) ? $processedImages : [APP_URL . '/assets/images/placeholder-product.jpg'];
    }
}

if (!function_exists('hasProductImage')) {
    /**
     * Check if product has images
     */
    function hasProductImage($images) {
        if (empty($images)) {
            return false;
        }
        
        if (is_array($images)) {
            return !empty($images);
        }
        
        $imageArray = json_decode($images, true);
        return !empty($imageArray);
    }
}

if (!function_exists('getProductImageCount')) {
    /**
     * Get count of product images
     */
    function getProductImageCount($images) {
        if (empty($images)) {
            return 0;
        }
        
        if (is_array($images)) {
            return count($images);
        }
        
        $imageArray = json_decode($images, true);
        return is_array($imageArray) ? count($imageArray) : 0;
    }
}

if (!function_exists('formatCurrency')) {
    /**
     * Format currency (UGX)
     * Fallback if not defined in main functions.php
     */
    function formatCurrency($amount, $decimals = 0) {
        return 'UGX ' . number_format($amount, $decimals, '.', ',');
    }
}

if (!function_exists('timeAgo')) {
    /**
     * Time ago function
     * Fallback if not defined in main functions.php
     */
    function timeAgo($datetime) {
        if (empty($datetime)) return 'N/A';
        
        $timestamp = strtotime($datetime);
        $diff = time() - $timestamp;
        
        if ($diff < 60) {
            return 'Just now';
        } elseif ($diff < 3600) {
            $mins = floor($diff / 60);
            return $mins . ' min' . ($mins > 1 ? 's' : '') . ' ago';
        } elseif ($diff < 86400) {
            $hours = floor($diff / 3600);
            return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
        } elseif ($diff < 604800) {
            $days = floor($diff / 86400);
            return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
        } elseif ($diff < 2592000) {
            $weeks = floor($diff / 604800);
            return $weeks . ' week' . ($weeks > 1 ? 's' : '') . ' ago';
        } else {
            return date('d M Y', $timestamp);
        }
    }
}

if (!function_exists('canCancelOrder')) {
    /**
     * Check if order can be cancelled
     */
    function canCancelOrder($order) {
        $allowedStatuses = ['pending', 'confirmed'];
        return in_array($order['status'], $allowedStatuses);
    }
}

if (!function_exists('canReviewOrder')) {
    /**
     * Check if order can be reviewed
     */
    function canReviewOrder($order) {
        return $order['status'] === 'completed';
    }
}

if (!function_exists('getBusinessTypes')) {
    /**
     * Get business types
     */
    function getBusinessTypes() {
        return [
            'individual' => 'Individual/Personal Use',
            'retailer' => 'Retailer (Small Shop/Store)',
            'wholesaler' => 'Wholesaler (Bulk Reseller)',
            'processor' => 'Processor/Manufacturer',
            'exporter' => 'Exporter (International Trade)'
        ];
    }
}

if (!function_exists('getBuyingCapacities')) {
    /**
     * Get buying capacities
     */
    function getBuyingCapacities() {
        return [
            'Small' => 'Small (< 1 ton/month)',
            'Medium' => 'Medium (1-10 tons/month)',
            'Large' => 'Large (> 10 tons/month)'
        ];
    }
}

if (!function_exists('getProductCategories')) {
    /**
     * Get product categories
     */
    function getProductCategories() {
        return [
            'sugar_cane' => 'Sugar Cane',
            'poultry' => 'Poultry Products',
            'maize' => 'Maize/Corn',
            'vegetables' => 'Vegetables',
            'coffee' => 'Coffee',
            'beans' => 'Beans',
            'cassava' => 'Cassava',
            'bananas' => 'Bananas',
            'dairy' => 'Dairy Products',
            'livestock' => 'Livestock',
            'other' => 'Other'
        ];
    }
}

if (!function_exists('getBuyerPermissions')) {
    /**
     * Get buyer permissions based on type
     */
    function getBuyerPermissions($buyerType, $isVerified) {
        $permissions = [
            // Basic permissions for all
            'view_products' => true,
            'view_prices' => true,
            'contact_sellers' => true,
            
            // Verified buyer permissions
            'place_orders' => $isVerified,
            'request_quotes' => $isVerified,
            'manage_suppliers' => $isVerified,
            'view_analytics' => $isVerified,
            
            // Type-specific permissions
            'bulk_purchase' => in_array($buyerType, ['wholesaler', 'processor', 'exporter']),
            'contract_farming' => in_array($buyerType, ['processor', 'exporter']),
            'advance_payment' => $isVerified && in_array($buyerType, ['processor', 'exporter']),
            'quality_specifications' => in_array($buyerType, ['processor', 'exporter']),
            'delivery_scheduling' => in_array($buyerType, ['wholesaler', 'processor', 'exporter']),
            'export_reports' => $isVerified && in_array($buyerType, ['wholesaler', 'processor', 'exporter']),
            'price_negotiations' => $isVerified,
        ];
        
        return $permissions;
    }
}

if (!function_exists('formatOrderNumber')) {
    /**
     * Format order number for display
     */
    function formatOrderNumber($orderNumber) {
        return '<code class="text-primary">' . htmlspecialchars($orderNumber) . '</code>';
    }
}

if (!function_exists('getOrderProgressPercentage')) {
    /**
     * Get order progress percentage
     */
    function getOrderProgressPercentage($status) {
        $progress = [
            'pending' => 20,
            'confirmed' => 40,
            'processing' => 70,
            'completed' => 100,
            'cancelled' => 0
        ];
        
        return $progress[$status] ?? 0;
    }
}

if (!function_exists('formatSupplierDistance')) {
    /**
     * Format distance from supplier
     */
    function formatSupplierDistance($distance) {
        if ($distance < 1) {
            return round($distance * 1000) . ' m';
        }
        return round($distance, 1) . ' km';
    }
}

if (!function_exists('getPaymentMethodIcon')) {
    /**
     * Get payment method icon
     */
    function getPaymentMethodIcon($method) {
        $icons = [
            'mobile_money' => 'bi-phone',
            'bank_transfer' => 'bi-bank',
            'cash' => 'bi-cash-stack',
            'credit' => 'bi-credit-card'
        ];
        
        return $icons[$method] ?? 'bi-wallet2';
    }
}

if (!function_exists('calculateOrderTotal')) {
    /**
     * Calculate order total with breakdown
     */
    function calculateOrderTotal($quantity, $unitPrice, $deliveryFee = 0, $taxRate = 0) {
        $subtotal = $quantity * $unitPrice;
        $tax = $subtotal * ($taxRate / 100);
        $total = $subtotal + $deliveryFee + $tax;
        
        return [
            'subtotal' => $subtotal,
            'delivery_fee' => $deliveryFee,
            'tax' => $tax,
            'total' => $total
        ];
    }
}

if (!function_exists('getBuyerTypeRequirements')) {
    /**
     * Get verification requirements for buyer types
     */
    function getBuyerTypeRequirements($buyerType) {
        $requirements = [
            'individual' => [
                'documents' => [],
                'verification_needed' => false
            ],
            'retailer' => [
                'documents' => ['Business License'],
                'verification_needed' => false
            ],
            'wholesaler' => [
                'documents' => ['Business License', 'Tax Certificate'],
                'verification_needed' => true
            ],
            'processor' => [
                'documents' => ['Business License', 'Tax Certificate', 'Processing License'],
                'verification_needed' => true
            ],
            'exporter' => [
                'documents' => ['Business License', 'Tax Certificate', 'Export License'],
                'verification_needed' => true
            ]
        ];
        
        return $requirements[$buyerType] ?? $requirements['individual'];
    }
}

if (!function_exists('formatBuyerStats')) {
    /**
     * Format buyer statistics for display
     */
    function formatBuyerStats($stats) {
        return [
            'total_orders' => number_format($stats['total_orders'] ?? 0),
            'pending_orders' => number_format($stats['pending_orders'] ?? 0),
            'completed_orders' => number_format($stats['completed_orders'] ?? 0),
            'total_spent' => formatCurrency($stats['total_spent'] ?? 0),
            'avg_order_value' => formatCurrency($stats['avg_order_value'] ?? 0),
            'active_suppliers' => number_format($stats['active_suppliers'] ?? 0),
            'favorites' => number_format($stats['favorites'] ?? 0)
        ];
    }
}

if (!function_exists('getOrderTimeline')) {
    /**
     * Get order timeline events
     */
    function getOrderTimeline($order) {
        $timeline = [];
        
        $timeline[] = [
            'status' => 'Order Placed',
            'date' => $order['created_at'],
            'icon' => 'bi-cart-check',
            'color' => 'primary',
            'completed' => true
        ];
        
        if ($order['status'] !== 'cancelled') {
            $timeline[] = [
                'status' => 'Order Confirmed',
                'date' => $order['updated_at'],
                'icon' => 'bi-check-circle',
                'color' => 'info',
                'completed' => in_array($order['status'], ['confirmed', 'processing', 'completed'])
            ];
            
            $timeline[] = [
                'status' => 'Processing',
                'date' => null,
                'icon' => 'bi-box-seam',
                'color' => 'warning',
                'completed' => in_array($order['status'], ['processing', 'completed'])
            ];
            
            $timeline[] = [
                'status' => 'Delivered',
                'date' => null,
                'icon' => 'bi-truck',
                'color' => 'success',
                'completed' => $order['status'] === 'completed'
            ];
        } else {
            $timeline[] = [
                'status' => 'Cancelled',
                'date' => $order['updated_at'],
                'icon' => 'bi-x-circle',
                'color' => 'danger',
                'completed' => true
            ];
        }
        
        return $timeline;
    }
}

if (!function_exists('isOrderExpiringSoon')) {
    /**
     * Check if order is expiring soon (pending for too long)
     */
    function isOrderExpiringSoon($orderDate, $maxDays = 7) {
        $orderTimestamp = strtotime($orderDate);
        $daysPassed = (time() - $orderTimestamp) / 86400;
        
        return $daysPassed >= ($maxDays - 2);
    }
}

if (!function_exists('getRecommendedProducts')) {
    /**
     * Get recommended products based on buyer's history
     */
    function getRecommendedProducts($userId, $limit = 5) {
        try {
            $db = \App\Database::getInstance()->getConnection();
            
            $sql = "SELECT DISTINCT p.*, u.full_name as seller_name
                    FROM products p
                    INNER JOIN users u ON p.seller_id = u.id
                    WHERE p.category IN (
                        SELECT DISTINCT p2.category
                        FROM orders o
                        INNER JOIN products p2 ON o.product_id = p2.id
                        WHERE o.buyer_id = ?
                        LIMIT 3
                    )
                    AND p.status = 'available'
                    AND p.id NOT IN (
                        SELECT product_id FROM favorites WHERE user_id = ?
                    )
                    ORDER BY p.views DESC, p.created_at DESC
                    LIMIT ?";
            
            $stmt = $db->prepare($sql);
            $stmt->execute([$userId, $userId, $limit]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            return [];
        }
    }
}