<?php
/**
 * Custom Pricing Manager Class
 * Handles custom pricing for specific package sizes
 */

class CustomPricingManager {
    private $conn;
    
    public function __construct($connection) {
        $this->conn = $connection;
    }
    
    /**
     * Add or update custom pricing
     */
    public function setCustomPricing($packageSize, $cost, $userRole, $networkType = 'all', $createdBy = null) {
        // Validate user role - only 'agent' is allowed
        if ($userRole !== 'agent') {
            return [
                'success' => false,
                'message' => 'Invalid user role. Only "agent" role is supported.'
            ];
        }
        
        // Convert package size to GB for consistent storage
        $packageSizeGb = $this->parsePackageSizeToGb($packageSize);
        
        // Check if pricing already exists
        $stmt = $this->conn->prepare("
            SELECT id FROM custom_pricing 
            WHERE package_size = ? AND network_type = ? AND user_role = ?
        ");
        $stmt->bind_param("sss", $packageSize, $networkType, $userRole);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            // Update existing pricing
            $row = $result->fetch_assoc();
            $stmt->close();
            
            $updateStmt = $this->conn->prepare("
                UPDATE custom_pricing 
                SET cost = ?, package_size_gb = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $updateStmt->bind_param("ddi", $cost, $packageSizeGb, $row['id']);
            $success = $updateStmt->execute();
            $updateStmt->close();
            
            return [
                'success' => $success,
                'action' => 'updated',
                'id' => $row['id']
            ];
        } else {
            // Insert new pricing
            $stmt->close();
            
            // Handle created_by field - exclude if null to avoid bind_param issues with foreign key
            if ($createdBy !== null) {
                $insertStmt = $this->conn->prepare("
                    INSERT INTO custom_pricing (package_size, package_size_gb, cost, network_type, user_role, created_by)
                    VALUES (?, ?, ?, ?, ?, ?)
                ");
                $insertStmt->bind_param("sddssi", $packageSize, $packageSizeGb, $cost, $networkType, $userRole, $createdBy);
            } else {
                $insertStmt = $this->conn->prepare("
                    INSERT INTO custom_pricing (package_size, package_size_gb, cost, network_type, user_role)
                    VALUES (?, ?, ?, ?, ?)
                ");
                $insertStmt->bind_param("sddss", $packageSize, $packageSizeGb, $cost, $networkType, $userRole);
            }
            
            if ($insertStmt->execute()) {
                $id = $this->conn->insert_id;
                $insertStmt->close();
                
                return [
                    'success' => true,
                    'action' => 'created',
                    'id' => $id
                ];
            } else {
                $insertStmt->close();
                return [
                    'success' => false,
                    'message' => 'Failed to create custom pricing'
                ];
            }
        }
    }
    
    /**
     * Get custom pricing for a specific package size
     */
    public function getCustomPricing($packageSize, $networkType = 'all', $userRole = 'all') {
        $stmt = $this->conn->prepare("
            SELECT * FROM custom_pricing 
            WHERE package_size = ? AND network_type = ? AND user_role = ?
        ");
        $stmt->bind_param("sss", $packageSize, $networkType, $userRole);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $pricing = $result->fetch_assoc();
            $stmt->close();
            return $pricing;
        }
        
        $stmt->close();
        return null;
    }
    
    /**
     * Get custom pricing by ID
     */
    public function getCustomPricingById($pricingId) {
        $stmt = $this->conn->prepare("
            SELECT * FROM custom_pricing 
            WHERE id = ?
        ");
        $stmt->bind_param("i", $pricingId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $pricing = $result->fetch_assoc();
            $stmt->close();
            return $pricing;
        }
        
        $stmt->close();
        return null;
    }
    
    /**
     * Get all custom pricing rules
     */
    public function getAllCustomPricing($networkType = null, $userRole = null) {
        $sql = "
            SELECT cp.*, a.username as created_by_username
            FROM custom_pricing cp
            LEFT JOIN agents a ON cp.created_by = a.id
            WHERE 1=1
        ";
        
        $params = [];
        $types = "";
        
        if ($networkType !== null) {
            $sql .= " AND cp.network_type = ?";
            $params[] = $networkType;
            $types .= "s";
        }
        
        if ($userRole !== null) {
            $sql .= " AND cp.user_role = ?";
            $params[] = $userRole;
            $types .= "s";
        }
        
        
        $sql .= " ORDER BY cp.package_size_gb ASC, cp.network_type, cp.user_role";
        
        $stmt = $this->conn->prepare($sql);
        if (!empty($params)) {
            $stmt->bind_param($types, ...$params);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        
        $pricing = [];
        while ($row = $result->fetch_assoc()) {
            $pricing[] = $row;
        }
        
        $stmt->close();
        return $pricing;
    }
    
    /**
     * Calculate price for a package size
     */
    public function calculatePrice($packageSize, $networkType = 'all', $userRole = 'all') {
        // First check for exact custom pricing match (specific package sizes)
        $customPricing = $this->getCustomPricing($packageSize, $networkType, $userRole);
        
        if ($customPricing) {
            return [
                'price' => $customPricing['cost'],
                'source' => 'custom',
                'pricing_id' => $customPricing['id']
            ];
        }
        
        // Check for role-specific custom pricing
        if ($userRole !== 'all') {
            $rolePricing = $this->getCustomPricing($packageSize, $networkType, $userRole);
            if ($rolePricing) {
                return [
                    'price' => $rolePricing['cost'],
                    'source' => 'role_custom',
                    'pricing_id' => $rolePricing['id']
                ];
            }
        }
        
        // Check for network-specific custom pricing
        if ($networkType !== 'all') {
            $networkPricing = $this->getCustomPricing($packageSize, $networkType, 'all');
            if ($networkPricing) {
                return [
                    'price' => $networkPricing['cost'],
                    'source' => 'network_custom',
                    'pricing_id' => $networkPricing['id']
                ];
            }
        }
        
        // No custom pricing found - return null to indicate no pricing available
        return [
            'price' => null,
            'source' => 'not_found',
            'pricing_id' => null
        ];
    }
    
    
    
    /**
     * Delete custom pricing
     */
    public function deleteCustomPricing($pricingId) {
        try {
            $stmt = $this->conn->prepare("DELETE FROM custom_pricing WHERE id = ?");
            if (!$stmt) {
                error_log("Failed to prepare delete statement: " . $this->conn->error);
                return false;
            }
            
            $stmt->bind_param("i", $pricingId);
            $success = $stmt->execute();
            
            if (!$success) {
                error_log("Failed to execute delete statement: " . $stmt->error);
            }
            
            $affectedRows = $stmt->affected_rows;
            $stmt->close();
            
            // Return true only if exactly one row was affected
            return $success && $affectedRows === 1;
        } catch (Exception $e) {
            error_log("Exception in deleteCustomPricing: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Parse package size to GB
     */
    public function parsePackageSizeToGb($packageSize) {
        $packageSize = trim($packageSize);
        
        // Handle MB
        if (stripos($packageSize, 'MB') !== false) {
            $num = floatval(preg_replace('/[^0-9.]/', '', $packageSize));
            return round($num / 1024, 4);
        }
        
        // Handle GB
        if (stripos($packageSize, 'GB') !== false) {
            $num = floatval(preg_replace('/[^0-9.]/', '', $packageSize));
            return round($num, 4);
        }
        
        // Handle plain numbers (assume GB)
        $num = floatval(preg_replace('/[^0-9.]/', '', $packageSize));
        return round($num, 4);
    }
    
    
    /**
     * Get pricing statistics
     */
    public function getPricingStats() {
        $stmt = $this->conn->prepare("
            SELECT 
                COUNT(*) as total_rules,
                COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_rules,
                COUNT(CASE WHEN network_type = 'all' THEN 1 END) as global_rules,
                COUNT(CASE WHEN user_role = 'all' THEN 1 END) as all_user_rules,
                AVG(cost) as avg_cost,
                MIN(cost) as min_cost,
                MAX(cost) as max_cost
            FROM custom_pricing
        ");
        
        $stmt->execute();
        $result = $stmt->get_result();
        $stats = $result->fetch_assoc();
        $stmt->close();
        
        return $stats;
    }
    
    /**
     * Bulk import pricing from array
     */
    public function bulkImportPricing($pricingData, $createdBy = null) {
        $successCount = 0;
        $errorCount = 0;
        $errors = [];
        
        foreach ($pricingData as $index => $data) {
            $packageSize = $data['package_size'] ?? '';
            $cost = floatval($data['cost'] ?? 0);
            $networkType = $data['network_type'] ?? 'all';
            $userRole = $data['user_role'] ?? 'all';
            
            if (empty($packageSize) || $cost <= 0) {
                $errorCount++;
                $errors[] = "Row " . ($index + 1) . ": Invalid package size or cost";
                continue;
            }
            
            $result = $this->setCustomPricing($packageSize, $cost, $networkType, $userRole, $createdBy);
            
            if ($result['success']) {
                $successCount++;
            } else {
                $errorCount++;
                $errors[] = "Row " . ($index + 1) . ": " . ($result['message'] ?? 'Unknown error');
            }
        }
        
        return [
            'success_count' => $successCount,
            'error_count' => $errorCount,
            'errors' => $errors
        ];
    }
}
?>


