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

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

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

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

// 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']);
    $exists_check->close();
    exit;
}
$exists_check->close();

// Delete the pricing rule
$stmt = $conn->prepare("DELETE FROM agent_pricing_rules WHERE id = ?");
$stmt->bind_param("i", $id);

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => 'Pricing rule deleted successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to delete pricing rule: ' . $stmt->error]);
}

$stmt->close();
?>


