<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
header('Content-Type: application/json');

require_once("definitions.php");

// Validate inputs
if (
    !isset($_POST['mailbox_key']) || !is_numeric($_POST['mailbox_key']) ||
    !isset($_POST['mailboxName']) || empty(trim($_POST['mailboxName']))
) {
    echo json_encode(['success' => false, 'message' => 'Invalid input data']);
    exit;
}

$mailbox_key = intval($_POST['mailbox_key']);
$mailbox_name = trim($_POST['mailboxName']);

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

// Create DB 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;
}

// Use prepared statement to find the mailbox_attributes_key for the mailbox_name and store_key
$attrStmt = $conn->prepare("SELECT mailbox_attributes_key FROM mailbox_attributes WHERE store_key = ? AND name = ? LIMIT 1");
if (!$attrStmt) {
    echo json_encode(['success' => false, 'message' => 'Prepare statement failed for attributes']);
    $conn->close();
    exit;
}
$attrStmt->bind_param("is", $store_key, $mailbox_name);
$attrStmt->execute();
$attrResult = $attrStmt->get_result();

if ($attrResult->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Mailbox name not found in attributes for this store']);
    $attrStmt->close();
    $conn->close();
    exit;
}

$attrRow = $attrResult->fetch_assoc();
$mailbox_attributes_key = $attrRow['mailbox_attributes_key'];
$attrStmt->close();

// Update mailboxes table: only mailbox_attributes_key and mailbox_name, and only if store_key matches
$updateStmt = $conn->prepare("
    UPDATE mailboxes 
    SET mailbox_attributes_key = ?, mailbox_name = ? 
    WHERE mailbox_key = ? AND store_key = ?
");
if (!$updateStmt) {
    echo json_encode(['success' => false, 'message' => 'Prepare statement failed for update']);
    $conn->close();
    exit;
}

$updateStmt->bind_param("isii", $mailbox_attributes_key, $mailbox_name, $mailbox_key, $store_key);
$success = $updateStmt->execute();
$updateStmt->close();
$conn->close();

if ($success) {
    echo json_encode(['success' => true, 'message' => 'Mailbox updated successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to update mailbox']);
}