<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once("definitions.php");

// Create connection
$conn = new mysqli(PACKAGE_LOG_DB_SERVER, PACKAGE_LOG_DB_USER, PACKAGE_LOG_DB_PASS, PACKAGE_LOG_DB_NAME);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get store key from session
$storeKey = isset($_SESSION['storekey']) ? intval($_SESSION['storekey']) : 0;
// For local testing, $storeKey = 1; // remove or comment out in production

$mailboxSizes = [];
$mailboxData = null;
$isEdit = false;
$mailboxKey = isset($_GET['mailbox_key']) ? intval($_GET['mailbox_key']) : 0;

if ($storeKey) {
    // Fetch mailbox sizes
    $sql = "SELECT ms.mailbox_attributes_key, ms.name FROM mailbox_attributes ms WHERE store_key = ? ORDER BY ms.name ASC";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $storeKey);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $mailboxSizes[] = $row;
    }
    $stmt->close();

    if ($mailboxKey > 0) {
        // Editing: fetch mailbox data
        $sql = "SELECT mailboxnumber, mailbox_name, mailbox_attributes_key FROM mailboxes WHERE mailbox_key = ? AND store_key = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $mailboxKey, $storeKey);
        $stmt->execute();
        $result = $stmt->get_result();
        $mailboxData = $result->fetch_assoc();
        $stmt->close();

        if ($mailboxData) {
            $isEdit = true;
        } else {
            echo "Mailbox not found or you don't have permission to edit.";
            exit;
        }
    }
} else {
    echo 'No Store Key';
    exit;
}
?>

<form id="add-mailbox-form">
    <h5><?= $isEdit ? 'Edit Mailbox Entry' : 'Add New Mailbox Entry' ?></h5>
    <div class="mb-3">
        <label for="mailboxNumber" class="form-label">Mailbox Number</label>
        <input type="text" class="form-control" id="mailboxNumber" name="mailboxNumber" required
               value="<?= $isEdit ? htmlspecialchars($mailboxData['mailboxnumber']) : '' ?>"
               <?= $isEdit ? 'readonly' : '' ?>>
        <?php if ($isEdit): ?>
            <!-- Hidden input to store mailbox_key -->
            <input type="hidden" name="mailbox_key" value="<?= $mailboxKey ?>">
        <?php endif; ?>
        <?php if ($isEdit): ?>
            <small class="form-text text-muted">Mailbox number cannot be changed.</small>
        <?php endif; ?>
    </div>
    <div class="mb-3">
        <label for="mailboxName" class="form-label">Mailbox Name</label>
        <input type="text" class="form-control" id="mailboxName" name="mailboxName"
               value="<?= $isEdit ? htmlspecialchars($mailboxData['mailbox_name']) : '' ?>">
    </div>
    <div class="mb-3">
        <label for="mailboxSize" class="form-label">Mailbox Type</label>
        <select class="form-select" id="mailboxSize" name="mailboxSize" required>
            <option value="" disabled <?= !$isEdit ? 'selected' : '' ?>>Select a size</option>
            <?php foreach ($mailboxSizes as $size): ?>
                <option value="<?= htmlspecialchars($size['mailbox_attributes_key']) ?>"
                    <?= $isEdit && $mailboxData['mailbox_attributes_key'] == $size['mailbox_attributes_key'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($size['name']) ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <button type="submit" class="btn btn-primary me-2"><?= $isEdit ? 'Update' : 'Submit' ?></button>
    <button type="button" id="cancelAddEntry" class="btn btn-secondary">Cancel</button>
</form>