<?php
/**
 * Store Pricing Manager Class
 * Handles pricing management for individual stores
 */

class StorePricingManager {
    private $conn;
    
    public function __construct($connection) {
        $this->conn = $connection;
    }
    
    /**
     * Get all pricing rules for a store
     */
    public function getStorePricing($storeId, $networkType = null) {
        $sql = "
            SELECT * FROM store_pricing
            WHERE store_id = ?
        ";
        
        $params = [$storeId];
        $types = "i";
        
        if ($networkType !== null) {
            $sql .= " AND network_type = ?";
            $params[] = $networkType;
            $types .= "s";
        }
        
        $sql .= " ORDER BY network_type, min_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;
    }
    
    /**
     * Add or update store pricing rule
     */
    public function setStorePricing($storeId, $networkType, $minSizeGb, $maxSizeGb, $pricePerGb, $isActive = 1) {
        // Check if pricing rule exists
        $checkStmt = $this->conn->prepare("
            SELECT id FROM store_pricing 
            WHERE store_id = ? AND network_type = ? 
            AND min_size_gb = ? AND max_size_gb = ?
        ");
        $checkStmt->bind_param("isdd", $storeId, $networkType, $minSizeGb, $maxSizeGb);
        $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_pricing 
                SET price_per_gb = ?, is_active = ?
                WHERE id = ?
            ");
            $updateStmt->bind_param("dii", $pricePerGb, $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_pricing (store_id, network_type, min_size_gb, max_size_gb, price_per_gb, is_active)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $insertStmt->bind_param("isdddi", $storeId, $networkType, $minSizeGb, $maxSizeGb, $pricePerGb, $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 store pricing rule
     */
    public function deleteStorePricing($pricingId) {
        $stmt = $this->conn->prepare("DELETE FROM store_pricing WHERE id = ?");
        $stmt->bind_param("i", $pricingId);
        $success = $stmt->execute();
        $affected = $stmt->affected_rows;
        $stmt->close();
        
        return $success && $affected > 0;
    }
    
    /**
     * Calculate price for a package based on store pricing
     */
    public function calculatePrice($storeId, $packageSize, $networkType = 'mtn') {
        $packageSizeGb = $this->parsePackageSizeToGb($packageSize);
        
        // Check store pricing rules (tiered pricing only)
        $pricingStmt = $this->conn->prepare("
            SELECT price_per_gb FROM store_pricing
            WHERE store_id = ? AND network_type = ? 
            AND min_size_gb <= ? AND max_size_gb >= ?
            AND is_active = 1
            ORDER BY min_size_gb DESC
            LIMIT 1
        ");
        $pricingStmt->bind_param("isdd", $storeId, $networkType, $packageSizeGb, $packageSizeGb);
        $pricingStmt->execute();
        $pricingResult = $pricingStmt->get_result();
        
        if ($pricingResult->num_rows > 0) {
            $row = $pricingResult->fetch_assoc();
            $pricingStmt->close();
            $price = $row['price_per_gb'] * $packageSizeGb;
            return [
                'price' => round($price, 2),
                'source' => 'tiered',
                'package_size_gb' => $packageSizeGb,
                'price_per_gb' => $row['price_per_gb']
            ];
        }
        $pricingStmt->close();
        
        // No pricing found
        return [
            'price' => null,
            'source' => 'not_found',
            'package_size_gb' => $packageSizeGb
        ];
    }
    
    /**
     * Bulk update store pricing
     */
    public function bulkUpdatePricing($storeId, $pricingData) {
        $successCount = 0;
        $errorCount = 0;
        $errors = [];
        
        foreach ($pricingData as $index => $data) {
            $networkType = $data['network_type'] ?? 'mtn';
            $minSizeGb = floatval($data['min_size_gb'] ?? 0);
            $maxSizeGb = floatval($data['max_size_gb'] ?? 0);
            $pricePerGb = floatval($data['price_per_gb'] ?? 0);
            $isActive = isset($data['is_active']) ? (int)$data['is_active'] : 1;
            
            if ($minSizeGb <= 0 || $maxSizeGb <= 0 || $pricePerGb <= 0) {
                $errorCount++;
                $errors[] = "Row " . ($index + 1) . ": Invalid data";
                continue;
            }
            
            $result = $this->setStorePricing($storeId, $networkType, $minSizeGb, $maxSizeGb, $pricePerGb, $isActive);
            
            if ($result['success']) {
                $successCount++;
            } else {
                $errorCount++;
                $errors[] = "Row " . ($index + 1) . ": " . ($result['message'] ?? 'Unknown error');
            }
        }
        
        return [
            'success_count' => $successCount,
            'error_count' => $errorCount,
            'errors' => $errors
        ];
    }
    
    /**
     * Copy pricing from another store or default template
     */
    public function copyPricingFromTemplate($storeId, $templateStoreId = null) {
        if ($templateStoreId === null) {
            // Copy from default agent_pricing_rules
            $stmt = $this->conn->prepare("
                INSERT INTO store_pricing (store_id, network_type, min_size_gb, max_size_gb, price_per_gb, is_active)
                SELECT ?, network_type, min_size_gb, max_size_gb, price_per_gb, is_active
                FROM agent_pricing_rules
                WHERE role = 'agent' AND is_active = 1
                ON DUPLICATE KEY UPDATE price_per_gb = VALUES(price_per_gb)
            ");
            $stmt->bind_param("i", $storeId);
        } else {
            // Copy from another store
            $stmt = $this->conn->prepare("
                INSERT INTO store_pricing (store_id, network_type, min_size_gb, max_size_gb, price_per_gb, is_active)
                SELECT ?, network_type, min_size_gb, max_size_gb, price_per_gb, is_active
                FROM store_pricing
                WHERE store_id = ?
                ON DUPLICATE KEY UPDATE price_per_gb = VALUES(price_per_gb)
            ");
            $stmt->bind_param("ii", $storeId, $templateStoreId);
        }
        
        if ($stmt->execute()) {
            $affected = $stmt->affected_rows;
            $stmt->close();
            return [
                'success' => true,
                'rows_copied' => $affected
            ];
        } else {
            $error = $stmt->error;
            $stmt->close();
            return [
                'success' => false,
                'message' => 'Failed to copy pricing: ' . $error
            ];
        }
    }
    
    // ========== 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);
    }
}
?>



