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

$adminAuth = new AdminAuth($conn);
$pricingManager = new \App\classes\ExternalAPIPricingManager($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 (only external pricing is allowed)
$id = intval($_POST['id'] ?? 0);
$network_type = trim($_POST['network_type'] ?? 'mtn');
$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);
// Checkbox: if checked, sends "on" or value; if unchecked, doesn't send anything
$is_active = isset($_POST['is_active']) && ($_POST['is_active'] === 'on' || $_POST['is_active'] === '1' || $_POST['is_active'] === 1) ? 1 : 0;

// Validate input
if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid pricing range ID']);
    exit;
}

if ($network_type !== 'mtn') {
    echo json_encode(['success' => false, 'message' => 'Only MTN network is supported']);
    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;
}

// Update external pricing range
$result = $pricingManager->updateExternalPriceRange($id, $network_type, $min_size_gb, $max_size_gb, $price_per_gb, $is_active);

if ($result) {
    echo json_encode(['success' => true, 'message' => 'External API pricing range updated successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to update pricing range. It may overlap with an existing range.']);
}

