<?php
/**
 * Delete Store Customer Pricing
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';
require_once '../app/classes/StoreCustomerPricingManager.php';

header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

// CSRF Protection
function validateCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Check CSRF token (from header or POST)
$csrfToken = $_POST['csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
if (empty($csrfToken) || !validateCSRFToken($csrfToken)) {
    echo json_encode(['success' => false, 'message' => 'Invalid security token']);
    exit();
}

$userId = $_SESSION['user_id'];
$storeId = intval($_POST['store_id'] ?? 0);
$pricingId = intval($_POST['pricing_id'] ?? 0);

// Verify user owns this store
$storeManager = new StoreManager($conn);
$store = $storeManager->getStoreById($storeId);

if (!$store || $store['owner_id'] != $userId) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Verify the pricing belongs to this store
$checkStmt = $conn->prepare("SELECT id FROM store_customer_pricing WHERE id = ? AND store_id = ?");
$checkStmt->bind_param("ii", $pricingId, $storeId);
$checkStmt->execute();
$checkResult = $checkStmt->get_result();

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

// Delete pricing using the manager
$customerPricingManager = new StoreCustomerPricingManager($conn);
$success = $customerPricingManager->deleteCustomerPricing($pricingId);

if ($success) {
    echo json_encode(['success' => true, 'message' => 'Customer pricing deleted successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to delete pricing']);
}
?>

