<?php
session_start();
require_once 'config.php';
require_once 'app/classes/CustomPricingManager.php';
require_once 'app/classes/StorePricingManager.php';

header('Content-Type: application/json; charset=utf-8');

// Get parameters
$networkType = $_POST['network_type'] ?? $_GET['network_type'] ?? 'mtn';
$userRole = $_POST['user_role'] ?? $_GET['user_role'] ?? 'all';
$userId = $_SESSION['user_id'] ?? null;

try {
    $formattedPackages = [];
    
    // Check if user belongs to a store
    $storeId = null;
    if ($userId) {
        $userStmt = $conn->prepare("SELECT store_id FROM agents WHERE id = ?");
        $userStmt->bind_param("i", $userId);
        $userStmt->execute();
        $userResult = $userStmt->get_result();
        if ($userResult->num_rows > 0) {
            $userData = $userResult->fetch_assoc();
            $storeId = $userData['store_id'];
        }
        $userStmt->close();
    }
    
    // USE STORE PRICING if agent belongs to a store
    if ($storeId) {
        $storePricingManager = new StorePricingManager($conn);
        
        // Get custom pricing for exact packages
        $customPricing = $storePricingManager->getStoreCustomPricing($storeId, null, $networkType);
        
        foreach ($customPricing as $package) {
            if ($package['is_active'] == 1) {
                $formattedPackages[] = [
                    'id' => $package['id'],
                    'package_size' => $package['package_size'],
                    'package_size_gb' => floatval($package['package_size_gb']),
                    'cost' => floatval($package['cost']),
                    'network_type' => $package['network_type'],
                    'display_text' => $package['package_size'] . ' - GHS ' . number_format($package['cost'], 2),
                    'source' => 'store_custom'
                ];
            }
        }
        
        // If no custom packages, generate from store's pricing rules
        if (empty($formattedPackages)) {
            $commonSizes = ['500MB', '1GB', '2GB', '3GB', '5GB', '10GB', '15GB', '20GB', '30GB', '50GB'];
            
            foreach ($commonSizes as $size) {
                $priceInfo = $storePricingManager->calculatePrice($storeId, $size, $networkType);
                
                if ($priceInfo['price'] !== null && $priceInfo['price'] > 0) {
                    $formattedPackages[] = [
                        'id' => 0,
                        'package_size' => $size,
                        'package_size_gb' => $priceInfo['package_size_gb'],
                        'cost' => floatval($priceInfo['price']),
                        'network_type' => $networkType,
                        'display_text' => $size . ' - GHS ' . number_format($priceInfo['price'], 2),
                        'source' => 'store_calculated'
                    ];
                }
            }
        }
    } else {
        // Fallback to old pricing system (role-based) if no store
        $pricingManager = new CustomPricingManager($conn);
        $packages = $pricingManager->getAllCustomPricing($networkType, $userRole);
        
        foreach ($packages as $package) {
            $formattedPackages[] = [
                'id' => $package['id'],
                'package_size' => $package['package_size'],
                'package_size_gb' => floatval($package['package_size_gb']),
                'cost' => floatval($package['cost']),
                'network_type' => $package['network_type'],
                'user_role' => $package['user_role'],
                'display_text' => $package['package_size'] . ' - GHS ' . number_format($package['cost'], 2),
                'source' => 'role_based'
            ];
        }
    }
    
    // Sort by package size (GB)
    usort($formattedPackages, function($a, $b) {
        return $a['package_size_gb'] <=> $b['package_size_gb'];
    });
    
    echo json_encode([
        'success' => true,
        'packages' => $formattedPackages,
        'network_type' => $networkType,
        'store_id' => $storeId,
        'using_store_pricing' => $storeId !== null
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error retrieving packages: ' . $e->getMessage()
    ]);
}
?>
