<?php
session_start();
header('Content-Type: application/json');
require_once("definitions.php");

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

// Validate POST inputs
$mailbox_numbers_raw = $_POST['mailbox_numbers'] ?? '';
$mailbox_attributes_key = trim($_POST['mailbox_size'] ?? '');  // mailbox_attributes_key directly
$mailbox_name = trim($_POST['mailboxName'] ?? '');
$mailbox_key = isset($_POST['mailbox_key']) ? intval($_POST['mailbox_key']) : 0;

if ($mailbox_name === '') {
    $mailbox_name = null;
}

if (empty($mailbox_numbers_raw)) {
    echo json_encode(['success' => false, 'message' => 'Mailbox numbers are required']);
    exit;
}

// Parse mailbox numbers input into an array of integers
function parseMailboxNumbers($input) {
    $result = [];

    // Split by commas
    $parts = explode(',', $input);

    foreach ($parts as $part) {
        $part = trim($part);
        if (preg_match('/^(\d+)-(\d+)$/', $part, $matches)) {
            $start = intval($matches[1]);
            $end = intval($matches[2]);
            if ($start > $end) {
                list($start, $end) = [$end, $start];
            }
            for ($i = $start; $i <= $end; $i++) {
                $result[] = $i;
            }
        } elseif (is_numeric($part)) {
            $result[] = intval($part);
        }
        // Ignore invalid parts silently
    }
    $result = array_unique($result);
    sort($result);
    return $result;
}

$mailbox_numbers = parseMailboxNumbers($mailbox_numbers_raw);
if (empty($mailbox_numbers)) {
    echo json_encode(['success' => false, 'message' => 'No valid mailbox numbers found']);
    exit;
}

// Validate mailbox_attributes_key
if ($mailbox_attributes_key === '') {
    $mailbox_attributes_key = null;
} else {
    if (!ctype_digit($mailbox_attributes_key)) {
        echo json_encode(['success' => false, 'message' => 'Invalid mailbox attribute key']);
        exit;
    }
    $mailbox_attributes_key = intval($mailbox_attributes_key);
}

// Connect to DB
$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 ($mailbox_key > 0) {
    // EDIT MODE: update single mailbox record
    // Validate only one mailbox number in input for editing
    if (count($mailbox_numbers) !== 1) {
        echo json_encode(['success' => false, 'message' => 'Editing supports only a single mailbox number.']);
        $conn->close();
        exit;
    }
    $mailbox_number = $mailbox_numbers[0];

    // Check if mailbox_key exists and belongs to store
    $stmt = $conn->prepare("SELECT mailboxnumber FROM mailboxes WHERE mailbox_key = ? AND store_key = ?");
    $stmt->bind_param("ii", $mailbox_key, $store_key);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows === 0) {
        $stmt->close();
        $conn->close();
        echo json_encode(['success' => false, 'message' => 'Mailbox not found or you do not have permission to edit it.']);
        exit;
    }
    $stmt->close();

    // Update mailbox entry
    $query = "UPDATE mailboxes SET mailbox_name = ?, mailbox_attributes_key = ? WHERE mailbox_key = ? AND store_key = ?";
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Prepare failed: ' . $conn->error]);
        $conn->close();
        exit;
    }

    if ($mailbox_attributes_key === null) {
        // Set mailbox_attributes_key to NULL
        $stmt = $conn->prepare("UPDATE mailboxes SET mailbox_name = ?, mailbox_attributes_key = NULL WHERE mailbox_key = ? AND store_key = ?");
        if (!$stmt) {
            echo json_encode(['success' => false, 'message' => 'Prepare failed: ' . $conn->error]);
            $conn->close();
            exit;
        }
        $stmt->bind_param("sii", $mailbox_name, $mailbox_key, $store_key);
    } else {
        $stmt->bind_param("siii", $mailbox_name, $mailbox_attributes_key, $mailbox_key, $store_key);
    }

    $success = $stmt->execute();
    if ($success) {
        echo json_encode(['success' => true, 'message' => 'Mailbox updated successfully.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update mailbox: ' . $stmt->error]);
    }
    $stmt->close();
    $conn->close();
    exit;
} else {
    // ADD MODE: add new mailboxes (same as before)

    // Check existing mailbox numbers for this store
    $placeholders = implode(',', array_fill(0, count($mailbox_numbers), '?'));
    $types = str_repeat('i', count($mailbox_numbers));
    $sql = "SELECT mailboxnumber FROM mailboxes WHERE store_key = ? AND mailboxnumber IN ($placeholders)";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Prepare failed: ' . $conn->error]);
        $conn->close();
        exit;
    }

    $params = array_merge([$store_key], $mailbox_numbers);
    $types_full = 'i' . $types;

    $refs = [];
    foreach ($params as $key => $value) {
        $refs[$key] = &$params[$key];
    }
    call_user_func_array([$stmt, 'bind_param'], array_merge([$types_full], $refs));

    $stmt->execute();
    $result = $stmt->get_result();

    $existing_numbers = [];
    while ($row = $result->fetch_assoc()) {
        $existing_numbers[] = intval($row['mailboxnumber']);
    }
    $stmt->close();

    $to_insert = array_diff($mailbox_numbers, $existing_numbers);

    if (empty($to_insert)) {
        echo json_encode(['success' => false, 'message' => 'All mailbox numbers already exist. No new mailboxes added.']);
        $conn->close();
        exit;
    }

    // Prepare insert statements once
    $insert_stmt_null_attr = $conn->prepare("INSERT INTO mailboxes (store_key, mailboxnumber, mailbox_attributes_key, mailbox_name) VALUES (?, ?, NULL, ?)");
    if (!$insert_stmt_null_attr) {
        echo json_encode(['success' => false, 'message' => 'Prepare insert (NULL attribute) failed: ' . $conn->error]);
        $conn->close();
        exit;
    }

    $insert_stmt_with_attr = null;
    if ($mailbox_attributes_key !== null) {
        $insert_stmt_with_attr = $conn->prepare("INSERT INTO mailboxes (store_key, mailboxnumber, mailbox_attributes_key, mailbox_name) VALUES (?, ?, ?, ?)");
        if (!$insert_stmt_with_attr) {
            echo json_encode(['success' => false, 'message' => 'Prepare insert (with attribute) failed: ' . $conn->error]);
            $insert_stmt_null_attr->close();
            $conn->close();
            exit;
        }
    }

    $inserted_count = 0;
    foreach ($to_insert as $number) {
        if ($mailbox_attributes_key === null) {
            $insert_stmt_null_attr->bind_param("iis", $store_key, $number, $mailbox_name);
            $success = $insert_stmt_null_attr->execute();
        } else {
            $insert_stmt_with_attr->bind_param("iiis", $store_key, $number, $mailbox_attributes_key, $mailbox_name);
            $success = $insert_stmt_with_attr->execute();
        }

        if ($success) {
            $inserted_count++;
        }
    }

    $insert_stmt_null_attr->close();
    if ($insert_stmt_with_attr) {
        $insert_stmt_with_attr->close();
    }

    $conn->close();

    echo json_encode([
        'success' => true,
        'message' => "Added $inserted_count new mailbox" . ($inserted_count !== 1 ? 'es' : '') . ".",
        'added_numbers' => array_values($to_insert)
    ]);
}