<?php
// Disable error reporting to prevent HTML output
error_reporting(0);
ini_set('display_errors', 0);

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);
    header('Content-Type: application/json');
    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;
}

$id = intval($_POST['id']);

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

// Check if the table exists first
$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;
}

// Fetch pricing rule details
try {
    $stmt = $conn->prepare("SELECT * FROM agent_pricing_rules WHERE id = ?");
    if (!$stmt) {
        throw new Exception('Database prepare failed: ' . $conn->error);
    }
    
    $stmt->bind_param("i", $id);
    if (!$stmt->execute()) {
        throw new Exception('Database execute failed: ' . $stmt->error);
    }
    
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        echo json_encode(['success' => true, 'pricing_rule' => $row]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Pricing rule not found']);
    }
    
    $stmt->close();
} catch (Exception $e) {
    error_log('Error in get_pricing_rule_details.php: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error occurred']);
}
?>
