<?php
session_start();
require_once("definitions.php");

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

$store_key = isset($_SESSION['storekey']) ? intval($_SESSION['storekey']) : 0;
if ($store_key === 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid store key']);
    exit;
}

$package_group_key = isset($_POST['package_group_key']) ? intval($_POST['package_group_key']) : 0;
$name = trim($_POST['name'] ?? '');
$order = isset($_POST['order']) ? intval($_POST['order']) : 0;
$active = isset($_POST['active']) ? intval($_POST['active']) : 0;

if ($name === '') {
    echo json_encode(['success' => false, 'message' => 'Name is required']);
    exit;
}

$conn = new mysqli(PACKAGE_LOG_DB_SERVER, PACKAGE_LOG_DB_USER, PACKAGE_LOG_DB_PASS, PACKAGE_LOG_DB_NAME);
if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

if ($package_group_key > 0) {
    // Update existing group
    $sql = "UPDATE mailbox_item_size_price_group SET 
        store_key = ?,
        name = ?,
        `order` = ?,
        active = ?
        WHERE item_size_group_key = ? AND store_key = ?";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Prepare failed: ' . $conn->error]);
        $conn->close();
        exit;
    }

    $stmt->bind_param("isiiii", $store_key, $name, $order, $active, $package_group_key, $store_key);

    if ($stmt->execute()) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Execute failed: ' . $stmt->error]);
    }
    $stmt->close();
} else {
    // Insert new group
    $sql = "INSERT INTO mailbox_item_size_price_group (store_key, name, `order`, active) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Prepare failed: ' . $conn->error]);
        $conn->close();
        exit;
    }

    $stmt->bind_param("isii", $store_key, $name, $order, $active);

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'package_group_key' => $stmt->insert_id]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Execute failed: ' . $stmt->error]);
    }
    $stmt->close();
}

$conn->close();