<?php
/**
 * Get available packages for a store
 * Returns package sizes and prices based on store's pricing
 */

require_once 'config.php';
require_once 'app/classes/StorePricingManager.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

$storeId = intval($_POST['store_id'] ?? 0);
$network = $_POST['network'] ?? '';

if ($storeId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid store ID']);
    exit;
}

if ($network !== 'mtn') {
    echo json_encode(['success' => false, 'message' => 'Invalid network. Only MTN is supported.']);
    exit;
}

$pricingManager = new StorePricingManager($conn);

// Get custom pricing first (exact package prices)
$customPricing = $pricingManager->getStoreCustomPricing($storeId, null, $network);
$customPricingAll = $pricingManager->getStoreCustomPricing($storeId, null, 'all');

// Merge custom pricing
$allCustomPricing = array_merge($customPricing, $customPricingAll);

$packages = [];

// Add custom packages
foreach ($allCustomPricing as $pricing) {
    if ($pricing['is_active'] == 1) {
        $packages[] = [
            'size' => $pricing['package_size'],
            'price' => number_format($pricing['cost'], 2),
            'type' => 'custom'
        ];
    }
}

// If no custom packages, generate from pricing rules
if (empty($packages)) {
    // Common package sizes
    $commonSizes = [
        '500MB', '1GB', '2GB', '3GB', '5GB', '10GB', '15GB', '20GB', '30GB', '50GB', '100GB'
    ];
    
    foreach ($commonSizes as $size) {
        $priceInfo = $pricingManager->calculatePrice($storeId, $size, $network);
        
        if ($priceInfo['price'] !== null && $priceInfo['price'] > 0) {
            $packages[] = [
                'size' => $size,
                'price' => number_format($priceInfo['price'], 2),
                'type' => 'calculated'
            ];
        }
    }
}

// Remove duplicates based on size
$uniquePackages = [];
$seenSizes = [];

foreach ($packages as $package) {
    if (!in_array($package['size'], $seenSizes)) {
        $uniquePackages[] = $package;
        $seenSizes[] = $package['size'];
    }
}

// Sort by size
usort($uniquePackages, function($a, $b) {
    $sizeA = floatval(str_replace(['MB', 'GB'], '', $a['size']));
    $sizeB = floatval(str_replace(['MB', 'GB'], '', $b['size']));
    
    // Convert MB to GB for comparison
    if (stripos($a['size'], 'MB') !== false) $sizeA /= 1024;
    if (stripos($b['size'], 'MB') !== false) $sizeB /= 1024;
    
    return $sizeA <=> $sizeB;
});

echo json_encode([
    'success' => true,
    'packages' => $uniquePackages
]);
?>



