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

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

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

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

// 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 "<p>Database connection failed.</p>";
    exit;
}

// Initialize default values for new record
$packageSize = [
    'package_size_key' => 0,
    'store_key' => $store_key,
    'name' => '',
    'price_group' => 0,
    'order' => 0,
    'price_initial' => '0.00',
    'price_per_extra_days' => '0.00',
    'extra_days' => 0,
    'price_per_extra_months' => '0.00',
    'price_max' => '0.00',
    'active' => 1
];

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

// Fetch price groups for the store
$priceGroups = [];
$sqlGroups = "SELECT item_size_group_key, name FROM mailbox_item_size_price_group WHERE store_key = ? AND active = 1 ORDER BY `order` ASC, name ASC";
$stmtGroups = $conn->prepare($sqlGroups);
if ($stmtGroups) {
    $stmtGroups->bind_param("i", $store_key);
    $stmtGroups->execute();
    $resultGroups = $stmtGroups->get_result();
    while ($row = $resultGroups->fetch_assoc()) {
        $priceGroups[] = $row;
    }
    $stmtGroups->close();
} else {
    echo "<p>Failed to load price groups.</p>";
    $conn->close();
    exit;
}

$conn->close();
?>

<form id="edit-package-size-form" class="row g-3">
    <h5><?= $package_size_key > 0 ? 'Edit Package Size' : 'New Package Size' ?></h5>
    <input type="hidden" name="package_size_key" value="<?= h($packageSize['item_size_key']) ?>">
    <input type="hidden" name="store_key" value="<?= h($packageSize['store_key']) ?>">

    <div class="col-md-6">
        <label for="price_group" class="form-label">Price Group</label>
        <select id="price_group" name="price_group" class="form-select" required>
            <option value="">-- Select Price Group --</option>
            <?php foreach ($priceGroups as $group): ?>
                <option value="<?= h($group['item_size_group_key']) ?>"
                    <?= intval($packageSize['price_group']) === intval($group['item_size_group_key']) ? 'selected' : '' ?>>
                    <?= h($group['name']) ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>

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

    <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($packageSize['name']) ?>">
    </div>

    <div class="col-md-6">
        <label for="price_initial" class="form-label">Initial Price ($)</label>
        <input type="number" step="0.01" min="0" id="price_initial" name="price_initial" class="form-control" required value="<?= h($packageSize['price_initial']) ?>">
    </div>

    <div class="col-md-6">
        <label for="price_per_extra_days" class="form-label">Price Per Extra Days ($)</label>
        <input type="number" step="0.01" min="0" id="price_per_extra_days" name="price_per_extra_days" class="form-control" required value="<?= h($packageSize['price_per_extra_days']) ?>">
    </div>

    <div class="col-md-6">
        <label for="extra_days" class="form-label">Extra Days</label>
        <input type="number" min="0" id="extra_days" name="extra_days" class="form-control" required value="<?= h($packageSize['extra_days']) ?>">
    </div>

    <div class="col-md-6">
        <label for="price_per_extra_months" class="form-label">Price Per Extra Months ($)</label>
        <input type="number" step="0.01" min="0" id="price_per_extra_months" name="price_per_extra_months" class="form-control" value="<?= h($packageSize['price_per_extra_months']) ?>">
    </div>

    <div class="col-md-6">
        <label for="price_max" class="form-label">Price Max ($)</label>
        <input type="number" step="0.01" min="0" id="price_max" name="price_max" class="form-control" value="<?= h($packageSize['price_max']) ?>">
    </div>

    <hr class="my-3">

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

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