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

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

require_once("definitions.php");

// Get store key from session
$store_key = $_SESSION['storekey'] ?? 0;
if ($store_key <= 0) {
    echo json_encode([
        'data' => [],
        'error' => '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([
        'data' => [],
        'error' => 'Database connection failed: ' . $conn->connect_error
    ]);
    exit;
}

$conn->set_charset("utf8mb4");

// Optional: You can implement server-side processing here by reading DataTables parameters (start, length, search, order) from $_GET
// For simplicity, this example returns all rows for the store without pagination or filtering

$sql = "SELECT mailbox_attributes_key, name, length, width, virtualbox, groupbox, ps1583, webviewable, businesses 
        FROM mailbox_attributes 
        WHERE store_key = ? 
        ORDER BY name ASC";

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

$stmt->bind_param("i", $store_key);
$stmt->execute();
$result = $stmt->get_result();

$data = [];

while ($row = $result->fetch_assoc()) {
    $data[] = [
        'mailbox_attributes_key' => (int)$row['mailbox_attributes_key'],
        'name' => $row['name'],
        'length' => $row['length'],
        'width' => $row['width'],
        'virtualbox' => (int)$row['virtualbox'],
        'groupbox' => (int)$row['groupbox'],
        'ps1583' => (int)$row['ps1583'],
        'webviewable' => (int)$row['webviewable'],
        'businesses' => $row['businesses'] ? 'Yes' : 'No'
    ];
}

$stmt->close();
$conn->close();

// Output JSON for DataTables
echo json_encode([
    "data" => $data
]);