<?php
/**
 * Update Store Pricing
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';
require_once '../app/classes/StorePricingManager.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();
}

$userId = $_SESSION['user_id'];
$storeId = intval($_POST['store_id'] ?? 0);
$pricingId = intval($_POST['pricing_id'] ?? 0);
$pricePerGb = floatval($_POST['price_per_gb'] ?? 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();
}

if ($pricePerGb <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid price']);
    exit();
}

// Update pricing
$stmt = $conn->prepare("UPDATE store_pricing SET price_per_gb = ? WHERE id = ? AND store_id = ?");
$stmt->bind_param("dii", $pricePerGb, $pricingId, $storeId);

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



