<?php
/**
 * Store Customer Pricing Manager Class
 * Handles package-specific pricing for regular customers (not agents)
 * Different from StorePricingManager which handles range-based pricing for agents
 */

class StoreCustomerPricingManager {
    private $conn;
    
    public function __construct($connection) {
        $this->conn = $connection;
    }
    
    /**
     * Get all customer pricing rules for a store
     */
    public function getStoreCustomerPricing($storeId, $networkType = null) {
        $sql = "
            SELECT * FROM store_customer_pricing
            WHERE store_id = ?
        ";
        
        $params = [$storeId];
        $types = "i";
        
        if ($networkType !== null) {
            $sql .= " AND network_type = ?";
            $params[] = $networkType;
            $types .= "s";
        }
        
        $sql .= " ORDER BY network_type, package_size_gb";
        
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $pricing = [];
        while ($row = $result->fetch_assoc()) {
            $pricing[] = $row;
        }
        
        $stmt->close();
        return $pricing;
    }
    
    /**
     * Get price for a specific package (package-specific pricing)
     */
    public function getPriceForPackage($storeId, $packageSize, $networkType = 'mtn') {
        $packageSizeGb = $this->parsePackageSizeToGb($packageSize);
        
        // Look for exact match first
        $stmt = $this->conn->prepare("
            SELECT price FROM store_customer_pricing
            WHERE store_id = ? AND network_type = ?
            AND ABS(package_size_gb - ?) < 0.001
            AND is_active = 1
            LIMIT 1
        ");
        $stmt->bind_param("isd", $storeId, $networkType, $packageSizeGb);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $stmt->close();
            return [
                'price' => floatval($row['price']),
                'source' => 'customer_pricing',
                'package_size_gb' => $packageSizeGb
            ];
        }
        $stmt->close();
        
        // No pricing found
        return [
            'price' => null,
            'source' => 'not_found',
            'package_size_gb' => $packageSizeGb
        ];
    }
    
    /**
     * Add or update customer pricing rule
     */
    public function setCustomerPricing($storeId, $networkType, $packageSizeGb, $packageLabel, $price, $isActive = 1) {
        // Check if pricing exists
        $checkStmt = $this->conn->prepare("
            SELECT id FROM store_customer_pricing 
            WHERE store_id = ? AND network_type = ? 
            AND ABS(package_size_gb - ?) < 0.001
        ");
        $checkStmt->bind_param("isd", $storeId, $networkType, $packageSizeGb);
        $checkStmt->execute();
        $checkResult = $checkStmt->get_result();
        
        if ($checkResult->num_rows > 0) {
            // Update existing
            $row = $checkResult->fetch_assoc();
            $checkStmt->close();
            
            $updateStmt = $this->conn->prepare("
                UPDATE store_customer_pricing 
                SET price = ?, package_label = ?, is_active = ?
                WHERE id = ?
            ");
            $updateStmt->bind_param("dsii", $price, $packageLabel, $isActive, $row['id']);
            $success = $updateStmt->execute();
            $updateStmt->close();
            
            return [
                'success' => $success,
                'action' => 'updated',
                'id' => $row['id']
            ];
        } else {
            // Insert new
            $checkStmt->close();
            
            $insertStmt = $this->conn->prepare("
                INSERT INTO store_customer_pricing (store_id, network_type, package_size_gb, package_label, price, is_active)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $insertStmt->bind_param("isdsdi", $storeId, $networkType, $packageSizeGb, $packageLabel, $price, $isActive);
            
            if ($insertStmt->execute()) {
                $id = $this->conn->insert_id;
                $insertStmt->close();
                return [
                    'success' => true,
                    'action' => 'created',
                    'id' => $id
                ];
            } else {
                $error = $insertStmt->error;
                $insertStmt->close();
                return [
                    'success' => false,
                    'message' => 'Failed to create pricing: ' . $error
                ];
            }
        }
    }
    
    /**
     * Delete customer pricing rule
     */
    public function deleteCustomerPricing($pricingId) {
        $stmt = $this->conn->prepare("DELETE FROM store_customer_pricing WHERE id = ?");
        $stmt->bind_param("i", $pricingId);
        $success = $stmt->execute();
        $affected = $stmt->affected_rows;
        $stmt->close();
        
        return $success && $affected > 0;
    }
    
    /**
     * Get maximum package size from admin pricing rules (for validation)
     */
    public function getMaxAdminPackageSize($networkType = 'mtn') {
        $stmt = $this->conn->prepare("
            SELECT MAX(max_size_gb) as max_size 
            FROM agent_pricing_rules 
            WHERE network_type = ? AND role = 'agent' AND is_active = 1
        ");
        $stmt->bind_param("s", $networkType);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $stmt->close();
        
        return $row ? floatval($row['max_size']) : null;
    }
    
    /**
     * Bulk update customer pricing
     */
    public function bulkUpdatePricing($storeId, $pricingData) {
        $successCount = 0;
        $errorCount = 0;
        $errors = [];
        
        foreach ($pricingData as $index => $data) {
            $networkType = $data['network_type'] ?? 'mtn';
            $packageSizeGb = floatval($data['package_size_gb'] ?? 0);
            $packageLabel = $data['package_label'] ?? '';
            $price = floatval($data['price'] ?? 0);
            $isActive = isset($data['is_active']) ? (int)$data['is_active'] : 1;
            
            if ($packageSizeGb <= 0 || $price <= 0) {
                $errorCount++;
                $errors[] = "Row " . ($index + 1) . ": Invalid data";
                continue;
            }
            
            if (empty($packageLabel)) {
                $packageLabel = $packageSizeGb . 'GB';
            }
            
            $result = $this->setCustomerPricing($storeId, $networkType, $packageSizeGb, $packageLabel, $price, $isActive);
            
            if ($result['success']) {
                $successCount++;
            } else {
                $errorCount++;
                $errors[] = "Row " . ($index + 1) . ": " . ($result['message'] ?? 'Unknown error');
            }
        }
        
        return [
            'success_count' => $successCount,
            'error_count' => $errorCount,
            'errors' => $errors
        ];
    }
    
    // ========== PRIVATE HELPER METHODS ==========
    
    /**
     * Parse package size to GB
     */
    private 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);
    }
}
?>

