<?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;
}

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['id']) || !isset($input['is_active'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

$id = intval($input['id']);
$is_active = $input['is_active'] === 'true' ? 1 : 0;

// Update pricing rule status
$stmt = $conn->prepare("UPDATE agent_pricing_rules SET is_active = ? WHERE id = ?");
$stmt->bind_param("ii", $is_active, $id);

if ($stmt->execute()) {
    $status_text = $is_active ? 'activated' : 'deactivated';
    echo json_encode(['success' => true, 'message' => "Pricing rule successfully {$status_text}"]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to update pricing rule status']);
}

$stmt->close();
?>
