<?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
$id = intval($_POST['id']);
$network_type = trim($_POST['network_type']);
$role = trim($_POST['role']) ?? 'agent';
$min_size_gb = floatval($_POST['min_size_gb']);
$max_size_gb = floatval($_POST['max_size_gb']);
$price_per_gb = floatval($_POST['price_per_gb']);
$is_active = isset($_POST['is_active']) ? 1 : 0;


// 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 ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid pricing rule ID']);
    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' => 'Invalid size or price values']);
    exit;
}

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

// Check if the record exists
$exists_check = $conn->prepare("SELECT id FROM agent_pricing_rules WHERE id = ?");
$exists_check->bind_param("i", $id);
$exists_check->execute();
$exists_result = $exists_check->get_result();

if ($exists_result->num_rows == 0) {
    echo json_encode(['success' => false, 'message' => 'Pricing rule not found']);
    exit;
}
$exists_check->close();

// Check if pricing rule already exists for this network, role and size range (excluding current rule)
$check_stmt = $conn->prepare("SELECT id FROM agent_pricing_rules WHERE network_type = ? AND role = ? AND ((min_size_gb <= ? AND max_size_gb >= ?) OR (min_size_gb <= ? AND max_size_gb >= ?)) AND id != ?");
$check_stmt->bind_param("ssddddi", $network_type, $role, $min_size_gb, $min_size_gb, $max_size_gb, $max_size_gb, $id);
$check_stmt->execute();
$check_result = $check_stmt->get_result();

if ($check_result->num_rows > 0) {
    $duplicate_id = $check_result->fetch_assoc()['id'];
    echo json_encode(['success' => false, 'message' => 'Pricing rule already exists for this network and size range']);
    exit;
}
$check_stmt->close();

// Update pricing rule
$stmt = $conn->prepare("UPDATE agent_pricing_rules SET network_type = ?, role = ?, min_size_gb = ?, max_size_gb = ?, price_per_gb = ?, is_active = ? WHERE id = ?");
$stmt->bind_param("ssdddii", $network_type, $role, $min_size_gb, $max_size_gb, $price_per_gb, $is_active, $id);

if ($stmt->execute()) {
    $affected_rows = $stmt->affected_rows;
    if ($affected_rows > 0) {
        echo json_encode(['success' => true, 'message' => 'Pricing rule updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'No changes made to pricing rule']);
    }
} else {
    $error_message = $stmt->error;
    echo json_encode(['success' => false, 'message' => 'Failed to update pricing rule: ' . $error_message]);
}

$stmt->close();
?>
