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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once("definitions.php");

// Database connection
$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;
}

// Get POST data and sanitize
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$original_name = isset($_POST['original_name']) ? trim($_POST['original_name']) : '';
$length = isset($_POST['length']) ? floatval($_POST['length']) : null;
$width = isset($_POST['width']) ? floatval($_POST['width']) : null;
$virtualbox = isset($_POST['virtualbox']) ? 1 : 0;
$groupbox = isset($_POST['groupbox']) ? 1 : 0;
$ps1583 = isset($_POST['ps1583']) ? 1 : 0;
$webviewable = isset($_POST['webviewable']) ? 1 : 0;
$businesses = isset($_POST['businesses']) ? 1 : 0;

// Get store_key from session
$store_key = $_SESSION['storekey'] ?? 0;
if ($store_key <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid store key in session']);
    exit;
}

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

// Check if this is an update or insert
// If original_name is provided and different from name, it is an update of an existing record
$is_update = !empty($original_name);

// Check if name already exists (to avoid duplicates)
if ($is_update) {
    // For update: check if new name duplicates another record (excluding current original_name)
    $stmt = $conn->prepare("SELECT COUNT(*) FROM mailbox_attributes WHERE store_key = ? AND name = ? AND name != ?");
    $stmt->bind_param("iss", $store_key, $name, $original_name);
} else {
    // For insert: check if name already exists
    $stmt = $conn->prepare("SELECT COUNT(*) FROM mailbox_attributes WHERE store_key = ? AND name = ?");
    $stmt->bind_param("is", $store_key, $name);
}

$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();

if ($count > 0) {
    echo json_encode(['success' => false, 'message' => 'An attribute with this name already exists']);
    exit;
}

if ($is_update) {
    // Update existing record
    $updateStmt = $conn->prepare("UPDATE mailbox_attributes SET name = ?, length = ?, width = ?, virtualbox = ?, groupbox = ?, ps1583 = ?, webviewable = ?, businesses = ? WHERE store_key = ? AND name = ?");
    $updateStmt->bind_param("sddiiiiiss", $name, $length, $width, $virtualbox, $groupbox, $ps1583, $webviewable, $businesses, $store_key, $original_name);
    $success = $updateStmt->execute();
    $updateStmt->close();
} else {
    // Insert new record
    $insertStmt = $conn->prepare("
        INSERT INTO mailbox_attributes
        (store_key, name, length, width, virtualbox, groupbox, ps1583, webviewable, businesses)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $insertStmt->bind_param(
        "isddiiiii",
        $store_key,
        $name,
        $length,
        $width,
        $virtualbox,
        $groupbox,
        $ps1583,
        $webviewable,
        $businesses
    );
    $success = $insertStmt->execute();
    $insertStmt->close();
}

$conn->close();

if ($success) {
    echo json_encode(['success' => true, 'message' => $businesses]);
} else {
    echo json_encode(['success' => false, 'message' => 'Database error occurred']);
}