<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once("definitions.php");

$storeKey = isset($_SESSION['storekey']) ? intval($_SESSION['storekey']) : 0;

if ($storeKey === 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: " . htmlspecialchars($conn->connect_error) . "</p>";
    exit;
}

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

// Fetch package groups from package_size_price_group table
$sql = "SELECT package_group_key, name, `order`, active FROM package_size_price_group WHERE store_key = ? ORDER BY `order` ASC, name ASC";
$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo "<p>Failed to prepare statement: " . htmlspecialchars($conn->error) . "</p>";
    $conn->close();
    exit;
}

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

$groups = [];
while ($row = $result->fetch_assoc()) {
    $groups[] = $row;
}

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

<div class="d-flex justify-content-between align-items-center mb-3">
    <h5>Package Groups</h5>
    <div>
        <button type="button" id="addNewPackageGroupBtn" class="btn btn-primary">Add New Group</button>
        <button type="button" id="closePackageGroupsManager" class="btn btn-secondary ms-2">Close</button>
    </div>
</div>

<table class="table table-bordered text-nowrap" id="package-groups-table">
    <thead class="table-light">
        <tr>
            <th>Name</th>
            <th>Order</th>
            <th>Active</th>
            <th style="width: 60px;">Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php if (count($groups) === 0): ?>
            <tr><td colspan="4" class="text-center">No package groups found.</td></tr>
        <?php else: ?>
            <?php foreach ($groups as $group): ?>
                <tr>
                    <td><?= h($group['name']) ?></td>
                    <td><?= intval($group['order']) ?></td>
                    <td><?= intval($group['active']) === 1 ? 'Yes' : 'No' ?></td>
                    <td>
                        <button type="button" class="btn btn-sm btn-info editPackageGroupBtn" data-package-group-key="<?= intval($group['package_group_key']) ?>" title="Edit">
                            <i class="ri-edit-line"></i>
                        </button>
                    </td>
                </tr>
            <?php endforeach; ?>
        <?php endif; ?>
    </tbody>
</table>