<?php
/**
 * ============================================================================
 * buyer/BuyerSystem.php
 * Buyer System Core - Handles buyer operations, permissions, and business logic
 * ============================================================================
 */

class BuyerSystem {
    private $db;
    private $userId;
    private $buyerProfile;
    private $permissions;
    
    public function __construct($database, $userId) {
        $this->db = $database->getConnection();
        $this->userId = $userId;
        $this->loadBuyerProfile();
        $this->loadPermissions();
    }
    
    /**
     * Load buyer profile with extended details
     */
    private function loadBuyerProfile() {
        $sql = "SELECT 
                    bp.*,
                    u.full_name,
                    u.phone_number,
                    u.email,
                    u.is_verified,
                    u.approval_status,
                    r.region_name,
                    d.district_name
                FROM buyer_profiles bp
                INNER JOIN users u ON bp.user_id = u.id
                LEFT JOIN regions r ON u.region_id = r.id
                LEFT JOIN districts d ON u.district_id = d.id
                WHERE bp.user_id = ?";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$this->userId]);
        $this->buyerProfile = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    /**
     * Load buyer permissions based on buyer type and verification status
     */
    private function loadPermissions() {
        $this->permissions = [
            // Basic permissions
            'view_products' => true,
            'view_prices' => true,
            'contact_sellers' => true,
            
            // Buyer-specific permissions
            'place_orders' => $this->isVerified(),
            'request_quotes' => $this->isVerified(),
            'bulk_purchase' => in_array($this->getBuyerType(), ['wholesaler', 'processor', 'exporter']),
            'contract_farming' => in_array($this->getBuyerType(), ['processor', 'exporter']),
            'advance_payment' => $this->isVerified() && in_array($this->getBuyerType(), ['processor', 'exporter']),
            
            // Business permissions
            'create_purchase_orders' => $this->isVerified(),
            'manage_suppliers' => $this->isVerified(),
            'view_analytics' => $this->isVerified(),
            'export_reports' => $this->isVerified() && in_array($this->getBuyerType(), ['wholesaler', 'processor', 'exporter']),
            
            // Advanced permissions for manufacturers/processors
            'quality_specifications' => in_array($this->getBuyerType(), ['processor', 'exporter']),
            'delivery_scheduling' => in_array($this->getBuyerType(), ['wholesaler', 'processor', 'exporter']),
            'price_negotiations' => $this->isVerified(),
        ];
    }
    
    /**
     * Check if user has a specific permission
     */
    public function hasPermission($permission) {
        return isset($this->permissions[$permission]) && $this->permissions[$permission];
    }
    
    /**
     * Get buyer profile
     */
    public function getProfile() {
        return $this->buyerProfile;
    }
    
    /**
     * Get buyer type
     */
    public function getBuyerType() {
        return $this->buyerProfile['buyer_type'] ?? 'individual';
    }
    
    /**
     * Check if buyer is verified
     */
    public function isVerified() {
        return $this->buyerProfile && $this->buyerProfile['is_verified'] == 1;
    }
    
    /**
     * Check if buyer has complete profile
     */
    public function hasCompleteProfile() {
        if (!$this->buyerProfile) {
            return false;
        }
        
        $required = ['business_name', 'business_phone', 'buyer_type'];
        
        foreach ($required as $field) {
            if (empty($this->buyerProfile[$field])) {
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * Get buyer statistics
     */
    public function getStatistics() {
        $stats = [];
        
        // Total orders
        $sql = "SELECT COUNT(*) as total FROM orders WHERE buyer_id = ?";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$this->userId]);
        $stats['total_orders'] = $stmt->fetch()['total'] ?? 0;
        
        // Pending orders
        $sql = "SELECT COUNT(*) as total FROM orders WHERE buyer_id = ? AND status IN ('pending', 'confirmed', 'processing')";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$this->userId]);
        $stats['pending_orders'] = $stmt->fetch()['total'] ?? 0;
        
        // Completed orders
        $sql = "SELECT COUNT(*) as total FROM orders WHERE buyer_id = ? AND status = 'completed'";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$this->userId]);
        $stats['completed_orders'] = $stmt->fetch()['total'] ?? 0;
        
        // Total spent
        $sql = "SELECT COALESCE(SUM(total_amount), 0) as total FROM orders WHERE buyer_id = ? AND status != 'cancelled'";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$this->userId]);
        $stats['total_spent'] = $stmt->fetch()['total'] ?? 0;
        
        // Active suppliers
        $sql = "SELECT COUNT(DISTINCT seller_id) as total FROM orders WHERE buyer_id = ? AND status != 'cancelled'";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$this->userId]);
        $stats['active_suppliers'] = $stmt->fetch()['total'] ?? 0;
        
        // Favorite products
        $sql = "SELECT COUNT(*) as total FROM favorites WHERE user_id = ?";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$this->userId]);
        $stats['favorites'] = $stmt->fetch()['total'] ?? 0;
        
        // Average order value
        if ($stats['total_orders'] > 0) {
            $stats['avg_order_value'] = $stats['total_spent'] / $stats['total_orders'];
        } else {
            $stats['avg_order_value'] = 0;
        }
        
        return $stats;
    }
    
    /**
     * Get purchase orders
     */
    public function getPurchaseOrders($filters = []) {
        $sql = "SELECT 
                    o.*,
                    p.product_name,
                    p.category,
                    u.full_name as seller_name,
                    u.phone_number as seller_phone,
                    d.district_name as seller_district
                FROM orders o
                INNER JOIN products p ON o.product_id = p.id
                INNER JOIN users u ON o.seller_id = u.id
                LEFT JOIN districts d ON u.district_id = d.id
                WHERE o.buyer_id = ?";
        
        $params = [$this->userId];
        
        // Add filters
        if (!empty($filters['status'])) {
            $sql .= " AND o.status = ?";
            $params[] = $filters['status'];
        }
        
        if (!empty($filters['from_date'])) {
            $sql .= " AND o.created_at >= ?";
            $params[] = $filters['from_date'];
        }
        
        if (!empty($filters['to_date'])) {
            $sql .= " AND o.created_at <= ?";
            $params[] = $filters['to_date'];
        }
        
        $sql .= " ORDER BY o.created_at DESC";
        
        if (!empty($filters['limit'])) {
            $sql .= " LIMIT " . (int)$filters['limit'];
        }
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * Get supplier list with order history
     */
    public function getSuppliers() {
        $sql = "SELECT 
                    u.id,
                    u.full_name,
                    u.phone_number,
                    u.email,
                    d.district_name,
                    s.subcounty_name,
                    COUNT(DISTINCT o.id) as total_orders,
                    COALESCE(SUM(o.total_amount), 0) as total_spent,
                    MAX(o.created_at) as last_order_date,
                    COALESCE(AVG(r.rating), 0) as avg_rating
                FROM users u
                INNER JOIN orders o ON u.id = o.seller_id
                LEFT JOIN districts d ON u.district_id = d.id
                LEFT JOIN subcounties s ON u.subcounty_id = s.id
                LEFT JOIN reviews r ON u.id = r.reviewed_user_id
                WHERE o.buyer_id = ?
                GROUP BY u.id
                ORDER BY total_spent DESC";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$this->userId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * Place a purchase order
     */
    public function placeOrder($productId, $quantity, $deliveryAddress, $notes = '') {
        if (!$this->hasPermission('place_orders')) {
            return [
                'success' => false,
                'message' => 'You do not have permission to place orders. Please complete your profile and get verified.'
            ];
        }
        
        try {
            $this->db->beginTransaction();
            
            // Get product details
            $sql = "SELECT * FROM products WHERE id = ? AND status = 'available'";
            $stmt = $this->db->prepare($sql);
            $stmt->execute([$productId]);
            $product = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$product) {
                throw new Exception('Product not available');
            }
            
            if ($product['quantity'] < $quantity) {
                throw new Exception('Insufficient stock. Available: ' . $product['quantity'] . ' ' . $product['unit']);
            }
            
            // Calculate total
            $unitPrice = $product['price_per_unit'];
            $totalAmount = $unitPrice * $quantity;
            
            // Generate order number
            $orderNumber = 'ORD-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
            
            // Create order
            $sql = "INSERT INTO orders (
                        order_number, product_id, buyer_id, seller_id, 
                        quantity, unit_price, total_amount, delivery_address, 
                        notes, status, payment_status, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'unpaid', NOW())";
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute([
                $orderNumber,
                $productId,
                $this->userId,
                $product['seller_id'],
                $quantity,
                $unitPrice,
                $totalAmount,
                $deliveryAddress,
                $notes
            ]);
            
            $orderId = $this->db->lastInsertId();
            
            // Update product quantity
            $sql = "UPDATE products SET quantity = quantity - ? WHERE id = ?";
            $stmt = $this->db->prepare($sql);
            $stmt->execute([$quantity, $productId]);
            
            // Check if product is out of stock
            if ($product['quantity'] - $quantity <= 0) {
                $sql = "UPDATE products SET status = 'sold' WHERE id = ?";
                $stmt = $this->db->prepare($sql);
                $stmt->execute([$productId]);
            }
            
            $this->db->commit();
            
            return [
                'success' => true,
                'message' => 'Order placed successfully',
                'order_id' => $orderId,
                'order_number' => $orderNumber
            ];
            
        } catch (Exception $e) {
            $this->db->rollBack();
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * Request a quote for bulk purchase
     */
    public function requestQuote($productType, $quantity, $specifications, $deliveryDate) {
        if (!$this->hasPermission('request_quotes')) {
            return [
                'success' => false,
                'message' => 'You do not have permission to request quotes'
            ];
        }
        
        try {
            $sql = "INSERT INTO purchase_requests (
                        buyer_id, product_type, quantity, specifications,
                        required_delivery_date, status, created_at
                    ) VALUES (?, ?, ?, ?, ?, 'pending', NOW())";
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute([
                $this->userId,
                $productType,
                $quantity,
                $specifications,
                $deliveryDate
            ]);
            
            return [
                'success' => true,
                'message' => 'Quote request submitted successfully',
                'request_id' => $this->db->lastInsertId()
            ];
            
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => 'Failed to submit quote request: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Get buyer type badge HTML
     */
    public function getBuyerTypeBadge() {
        $badges = [
            'individual' => '<span class="badge bg-info">Individual</span>',
            'retailer' => '<span class="badge bg-primary">Retailer</span>',
            'wholesaler' => '<span class="badge bg-success">Wholesaler</span>',
            'processor' => '<span class="badge bg-warning text-dark">Processor</span>',
            'exporter' => '<span class="badge bg-danger">Exporter</span>'
        ];
        
        return $badges[$this->getBuyerType()] ?? $badges['individual'];
    }
    
    /**
     * Get buying capacity level
     */
    public function getBuyingCapacity() {
        return $this->buyerProfile['buying_capacity'] ?? 'Small';
    }
    
    /**
     * Get preferred products
     */
    public function getPreferredProducts() {
        $preferred = $this->buyerProfile['preferred_products'] ?? '[]';
        return json_decode($preferred, true) ?? [];
    }
    
    /**
     * Update buyer profile
     */
    public function updateProfile($data) {
        try {
            $sql = "UPDATE buyer_profiles SET
                        business_name = ?,
                        buyer_type = ?,
                        business_phone = ?,
                        business_email = ?,
                        business_address = ?,
                        buying_capacity = ?,
                        preferred_products = ?,
                        updated_at = NOW()
                    WHERE user_id = ?";
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute([
                $data['business_name'],
                $data['buyer_type'],
                $data['business_phone'],
                $data['business_email'],
                $data['business_address'],
                $data['buying_capacity'],
                json_encode($data['preferred_products'] ?? []),
                $this->userId
            ]);
            
            // Reload profile
            $this->loadBuyerProfile();
            
            return [
                'success' => true,
                'message' => 'Profile updated successfully'
            ];
            
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => 'Failed to update profile: ' . $e->getMessage()
            ];
        }
    }
}