<?php
require_once 'config.php';

$storeId = 20;

echo "=== ALL PRICING RULES FOR STORE ID $storeId ===\n\n";

// Check all rules including inactive ones
$allStmt = $conn->prepare("
    SELECT id, network_type, min_size_gb, max_size_gb, price_per_gb, is_active 
    FROM store_pricing 
    WHERE store_id = ? AND network_type = 'mtn' 
    ORDER BY min_size_gb
");
$allStmt->bind_param("i", $storeId);
$allStmt->execute();
$allResult = $allStmt->get_result();

$activeRules = [];
$inactiveRules = [];

while ($row = $allResult->fetch_assoc()) {
    if ($row['is_active']) {
        $activeRules[] = $row;
    } else {
        $inactiveRules[] = $row;
    }
}
$allStmt->close();

echo "--- ACTIVE RULES ---\n";
foreach ($activeRules as $rule) {
    echo "Rule ID: {$rule['id']} | Range: {$rule['min_size_gb']}-{$rule['max_size_gb']} GB | Price: GH₵ {$rule['price_per_gb']}/GB\n";
}

if (count($inactiveRules) > 0) {
    echo "\n--- INACTIVE RULES ---\n";
    foreach ($inactiveRules as $rule) {
        echo "Rule ID: {$rule['id']} | Range: {$rule['min_size_gb']}-{$rule['max_size_gb']} GB | Price: GH₵ {$rule['price_per_gb']}/GB\n";
    }
}

// Check specifically for Rule 20
echo "\n--- CHECKING FOR RULE ID 20 ---\n";
$rule20Stmt = $conn->prepare("
    SELECT id, network_type, min_size_gb, max_size_gb, price_per_gb, is_active 
    FROM store_pricing 
    WHERE id = 20 AND store_id = ?
");
$rule20Stmt->bind_param("i", $storeId);
$rule20Stmt->execute();
$rule20Result = $rule20Stmt->get_result();

if ($rule20Row = $rule20Result->fetch_assoc()) {
    echo "Rule 20 EXISTS:\n";
    echo "  Range: {$rule20Row['min_size_gb']}-{$rule20Row['max_size_gb']} GB\n";
    echo "  Price: GH₵ {$rule20Row['price_per_gb']}/GB\n";
    echo "  Active: " . ($rule20Row['is_active'] ? 'Yes' : 'No') . "\n";
    
    // If it's still overlapping (0.1 to 9.9), fix it
    if ($rule20Row['min_size_gb'] == 0.1 && $rule20Row['max_size_gb'] >= 9.0 && $rule20Row['is_active']) {
        echo "\n  → Rule 20 needs to be fixed (overlaps with Rule 105)\n";
        echo "  → Updating min_size_gb from 0.1 to 5.0...\n";
        
        $fixStmt = $conn->prepare("
            UPDATE store_pricing 
            SET min_size_gb = 5.0 
            WHERE id = 20 AND store_id = ?
        ");
        $fixStmt->bind_param("i", $storeId);
        
        if ($fixStmt->execute()) {
            echo "  ✓ Fixed! Rule 20 now starts at 5.0 GB\n";
        } else {
            echo "  ✗ Error: " . $fixStmt->error . "\n";
        }
        $fixStmt->close();
    }
} else {
    echo "Rule 20 does not exist for this store.\n";
}
$rule20Stmt->close();

$conn->close();
?>


