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

$adminAuth = new AdminAuth($conn);

// Check admin authentication
if (!$adminAuth->isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

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

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

// Get form data
$network_type = trim($_POST['network_type'] ?? '');
$role = trim($_POST['role'] ?? 'agent');
$min_size_gb = floatval($_POST['min_size_gb'] ?? 0);
$max_size_gb = floatval($_POST['max_size_gb'] ?? 0);
$price_per_gb = floatval($_POST['price_per_gb'] ?? 0);
$is_active = isset($_POST['is_active']) ? intval($_POST['is_active']) : 1; // Default to active if not specified


// Check if the table exists
$table_check = mysqli_query($conn, "SHOW TABLES LIKE 'agent_pricing_rules'");
if (mysqli_num_rows($table_check) == 0) {
    echo json_encode(['success' => false, 'message' => 'Table agent_pricing_rules does not exist']);
    exit;
}

// Validate input
if (empty($network_type)) {
    echo json_encode(['success' => false, 'message' => 'Network type is required']);
    exit;
}

if (!in_array($network_type, ['mtn', 'telecel', 'airtel_tigo'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid network type']);
    exit;
}

if ($role !== 'agent') {
    echo json_encode(['success' => false, 'message' => 'Invalid role']);
    exit;
}

if ($min_size_gb <= 0 || $max_size_gb <= 0 || $price_per_gb <= 0) {
    echo json_encode(['success' => false, 'message' => 'All values must be greater than 0']);
    exit;
}

if ($min_size_gb >= $max_size_gb) {
    echo json_encode(['success' => false, 'message' => 'Minimum size must be less than maximum size']);
    exit;
}

// First, let's check what rules actually exist for this network
$existing_check = $conn->prepare("SELECT id, min_size_gb, max_size_gb FROM agent_pricing_rules WHERE network_type = ? ORDER BY min_size_gb");
$existing_check->bind_param("s", $network_type);
$existing_check->execute();
$existing_result = $existing_check->get_result();
$existing_rules = [];
while ($row = $existing_result->fetch_assoc()) {
    $existing_rules[] = $row;
}
$existing_check->close();

// Check if pricing rule already exists for this network, role and size range
// A range overlaps if: new_min < existing_max AND new_max > existing_min
$check_stmt = $conn->prepare("SELECT id, min_size_gb, max_size_gb FROM agent_pricing_rules WHERE network_type = ? AND role = ? AND ? < max_size_gb AND ? > min_size_gb");
$check_stmt->bind_param("ssdd", $network_type, $role, $min_size_gb, $max_size_gb);
$check_stmt->execute();
$check_result = $check_stmt->get_result();

if ($check_result->num_rows > 0) {
    $duplicate_rule = $check_result->fetch_assoc();
    
    // Use the existing rules we already fetched
    $existing_ranges = [];
    foreach ($existing_rules as $rule) {
        $existing_ranges[] = $rule['min_size_gb'] . '-' . $rule['max_size_gb'] . 'GB';
    }
    
    $ranges_text = implode(', ', $existing_ranges);
    echo json_encode(['success' => false, 'message' => "Pricing rule overlaps with existing rule (Range: {$duplicate_rule['min_size_gb']}-{$duplicate_rule['max_size_gb']}GB). Existing ranges for {$network_type}: {$ranges_text}"]);
    exit;
}
$check_stmt->close();

// Insert new pricing rule
$stmt = $conn->prepare("INSERT INTO agent_pricing_rules (network_type, role, min_size_gb, max_size_gb, price_per_gb, is_active, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
$stmt->bind_param("ssdddi", $network_type, $role, $min_size_gb, $max_size_gb, $price_per_gb, $is_active);

if ($stmt->execute()) {
    $new_id = $conn->insert_id;
    echo json_encode(['success' => true, 'message' => 'Pricing rule added successfully', 'id' => $new_id]);
} else {
    $error_message = $stmt->error;
    error_log('Error adding pricing rule: ' . $error_message);
    echo json_encode(['success' => false, 'message' => 'Failed to add pricing rule: ' . $error_message]);
}

$stmt->close();
?>
