<?php
session_start();
require_once("definitions.php");

function h($str) {
    return htmlspecialchars($str, ENT_QUOTES);
}

$package_group_key = isset($_GET['package_group_key']) ? intval($_GET['package_group_key']) : 0;

$store_key = isset($_SESSION['storekey']) ? intval($_SESSION['storekey']) : 0;
if ($store_key === 0) {
    echo "<p>Invalid store key.</p>";
    exit;
}

$conn = new mysqli(PACKAGE_LOG_DB_SERVER, PACKAGE_LOG_DB_USER, PACKAGE_LOG_DB_PASS, PACKAGE_LOG_DB_NAME);
if ($conn->connect_error) {
    echo "<p>Database connection failed.</p>";
    exit;
}

$group = [
    'item_size_group_key' => 0,
    'store_key' => $store_key,
    'name' => '',
    'order' => 0,
    'active' => 1
];

if ($package_group_key > 0) {
    $sql = "SELECT * FROM mailbox_item_size_price_group WHERE item_size_group_key = ? AND store_key = ?";
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("ii", $package_group_key, $store_key);
        $stmt->execute();
        $result = $stmt->get_result();
        $data = $result->fetch_assoc();
        if ($data) {
            $group = $data;
        } else {
            echo "<p>Package group not found.</p>";
            $stmt->close();
            $conn->close();
            exit;
        }
        $stmt->close();
    } else {
        echo "<p>Failed to prepare statement.</p>";
        $conn->close();
        exit;
    }
}
$conn->close();
?>

<form id="edit-package-group-form" class="row g-3">
    <h5><?= $package_group_key > 0 ? 'Edit Package Group' : 'New Package Group' ?></h5>
    <input type="hidden" name="package_group_key" value="<?= h($group['item_size_group_key']) ?>">
    <input type="hidden" name="store_key" value="<?= h($group['store_key']) ?>">

    <div class="col-md-6">
        <label for="name" class="form-label">Name</label>
        <input type="text" maxlength="64" id="name" name="name" class="form-control" required value="<?= h($group['name']) ?>">
    </div>

    <div class="col-md-3">
        <label for="order" class="form-label">Order</label>
        <input type="number" min="0" id="order" name="order" class="form-control" value="<?= h($group['order']) ?>">
    </div>

    <div class="col-md-3">
        <label for="active" class="form-label">Active</label>
        <select id="active" name="active" class="form-select" required>
            <option value="1" <?= intval($group['active']) === 1 ? 'selected' : '' ?>>Yes</option>
            <option value="0" <?= intval($group['active']) === 0 ? 'selected' : '' ?>>No</option>
        </select>
    </div>

    <div class="col-12 mt-3">
        <button type="submit" class="btn btn-primary me-2"><?= $package_group_key > 0 ? 'Save Changes' : 'Add Group' ?></button>
        <button type="button" id="cancelEditPackageGroup" class="btn btn-secondary">Cancel</button>
    </div>
</form>