<?php
include 'db.php';
include 'auth.php';
require_right('Item List');

// Handle add/edit/delete for UOM Groups
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['group_action'])) {
    if ($_POST['group_action'] === 'add') {
        $code = trim($_POST['code']);
        $name = trim($_POST['name']);
        if ($code && $name) {
            $stmt = $conn->prepare("INSERT INTO uom_groups (code, name) VALUES (?, ?)");
            $stmt->bind_param("ss", $code, $name);
            $stmt->execute();
            $stmt->close();
        }
    } elseif ($_POST['group_action'] === 'delete') {
        $id = (int)$_POST['id'];
        if ($id) {
            $conn->query("DELETE FROM uom_groups WHERE id=$id");
        }
    }
}

// Handle add/edit/delete for UOMs
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['uom_action'])) {
    if ($_POST['uom_action'] === 'add') {
        $name = trim($_POST['name']);
        $symbol = trim($_POST['symbol']);
        $group_id = (int)$_POST['group_id'];
        $base_quantity = floatval($_POST['base_quantity']);
        $is_base = isset($_POST['is_base']) ? 1 : 0;
        if ($name && $symbol && $group_id) {
            if ($is_base) {
                $conn->query("UPDATE uoms SET is_base=0 WHERE group_id=$group_id");
            }
            $stmt = $conn->prepare("INSERT INTO uoms (name, symbol, group_id, base_quantity, is_base) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("ssidi", $name, $symbol, $group_id, $base_quantity, $is_base);
            $stmt->execute();
            $stmt->close();
        }
    } elseif ($_POST['uom_action'] === 'delete') {
        $id = (int)$_POST['id'];
        if ($id) {
            $conn->query("DELETE FROM uoms WHERE id=$id");
        }
    }
}

$groups = $conn->query("SELECT * FROM uom_groups ORDER BY name");
$uoms = $conn->query("SELECT uoms.*, uom_groups.name AS group_name FROM uoms JOIN uom_groups ON uoms.group_id = uom_groups.id ORDER BY uom_groups.name, uoms.name");

include 'layout.php';
?>
<div class="page-wrapper">
    <div class="content">
        <div class="page-header"><div class="page-title"><h4>Unit of Measurement (UOM) Management</h4></div></div>
        <div class="alert alert-info mb-4">
            <b>How to use:</b> <br>
            <ol class="mb-0">
                <li><b>Create UOM Groups</b> (e.g. Weight, Volume, Count) below. Each group is a family of related units.</li>
                <li><b>Add Units</b> to each group (e.g. Gram, Kilogram for Weight). Mark one as the <b>Base Unit</b> (the smallest or standard unit for that group).</li>
                <li>Set the <b>Conversion Factor</b> for each unit (e.g. 1 Kilogram = 1000 Gram, so factor is 1000).</li>
            </ol>
        </div>
        <div class="alert alert-warning mb-4">
    <b>What is a Base Unit?</b><br>
    The <b>base unit</b> is the main or standard unit for a group. All other units in the group are defined in terms of this unit.<br>
    <b>What is a Factor?</b><br>
    The <b>factor</b> is how many base units are in one of this unit.<br>
    <br>
    <b>Example (Weight):</b>
    <table class="table table-bordered table-sm w-auto mt-2 mb-0">
        <thead><tr><th>Unit</th><th>Is Base?</th><th>Factor</th><th>Meaning</th></tr></thead>
        <tbody>
            <tr><td>Gram (g)</td><td>Yes</td><td>1</td><td>1 gram = 1 gram (base unit)</td></tr>
            <tr><td>Kilogram (kg)</td><td>No</td><td>1000</td><td>1 kilogram = 1000 grams</td></tr>
            <tr><td>Milligram (mg)</td><td>No</td><td>0.001</td><td>1 milligram = 0.001 grams</td></tr>
        </tbody>
    </table>
    <b>Example (Volume):</b>
    <table class="table table-bordered table-sm w-auto mt-2 mb-0">
        <thead><tr><th>Unit</th><th>Is Base?</th><th>Factor</th><th>Meaning</th></tr></thead>
        <tbody>
            <tr><td>Milliliter (ml)</td><td>Yes</td><td>1</td><td>1 milliliter = 1 milliliter (base unit)</td></tr>
            <tr><td>Liter (l)</td><td>No</td><td>1000</td><td>1 liter = 1000 milliliters</td></tr>
        </tbody>
    </table>
    <div class="mt-2"><b>Tip:</b> Always pick the smallest practical unit as the base (e.g. gram, milliliter, piece). All other units are defined by how many of the base unit they contain.</div>
</div>
        <div class="row">
            <div class="col-md-5">
                <h5>Step 1: UOM Groups</h5>
                <form method="POST" class="mb-3">
                    <input type="hidden" name="group_action" value="add">
                    <div class="input-group mb-2">
                        <input type="text" name="code" class="form-control" placeholder="Short Code (e.g. WGT)" required>
                        <input type="text" name="name" class="form-control" placeholder="Group Name (e.g. Weight)" required>
                        <button class="btn btn-primary" type="submit">Add Group</button>
                    </div>
                </form>
                <table class="table table-bordered table-sm">
                    <thead><tr><th>Code</th><th>Name</th><th>Delete</th></tr></thead>
                    <tbody>
                        <?php foreach ($groups as $g): ?>
                        <tr>
                            <td><?= htmlspecialchars($g['code']) ?></td>
                            <td><?= htmlspecialchars($g['name']) ?></td>
                            <td>
                                <form method="POST" style="display:inline;">
                                    <input type="hidden" name="group_action" value="delete">
                                    <input type="hidden" name="id" value="<?= $g['id'] ?>">
                                    <button class="btn btn-sm btn-danger" onclick="return confirm('Delete this group?')">Delete</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div class="col-md-7">
                <h5>Step 2: Units in Each Group</h5>
                <form method="POST" class="mb-3">
                    <input type="hidden" name="uom_action" value="add">
                    <div class="row g-2 mb-2">
                        <div class="col-md-3">
                            <input type="text" name="name" class="form-control" placeholder="Unit Name (e.g. Kilogram)" required>
                        </div>
                        <div class="col-md-2">
                            <input type="text" name="symbol" class="form-control" placeholder="Symbol (e.g. kg)" required>
                        </div>
                        <div class="col-md-3">
                            <select name="group_id" class="form-control" required>
                                <option value="">Group</option>
                                <?php foreach ($groups as $g): ?>
                                <option value="<?= $g['id'] ?>"><?= htmlspecialchars($g['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <input type="number" step="0.0001" name="base_quantity" class="form-control" placeholder="Factor" value="1" required>
                            <small class="text-muted">How many base units?</small>
                        </div>
                        <div class="col-md-2">
                            <label><input type="checkbox" name="is_base"> Base Unit</label>
                            <span class="text-muted" data-bs-toggle="tooltip" title="The base unit is the standard for this group. All other units convert to this."><i class="fa fa-info-circle"></i></span>
                        </div>
                    </div>
                    <button class="btn btn-primary" type="submit">Add Unit</button>
                </form>
                <table class="table table-bordered table-sm">
                    <thead><tr><th>Unit</th><th>Symbol</th><th>Group</th><th>Factor</th><th>Base?</th><th>Delete</th></tr></thead>
                    <tbody>
                        <?php foreach ($uoms as $u): ?>
                        <tr>
                            <td><?= htmlspecialchars($u['name']) ?></td>
                            <td><?= htmlspecialchars($u['symbol']) ?></td>
                            <td><?= htmlspecialchars($u['group_name']) ?></td>
                            <td><?= $u['base_quantity'] ?></td>
                            <td><?= $u['is_base'] ? '<span class="badge bg-success">Yes</span>' : '' ?></td>
                            <td>
                                <form method="POST" style="display:inline;">
                                    <input type="hidden" name="uom_action" value="delete">
                                    <input type="hidden" name="id" value="<?= $u['id'] ?>">
                                    <button class="btn btn-sm btn-danger" onclick="return confirm('Delete this unit?')">Delete</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <div class="alert alert-secondary mt-3">
                    <b>Base Unit:</b> The standard unit for the group (e.g. Gram for Weight).<br>
                    <b>Factor:</b> How many base units in this unit (e.g. 1 Kilogram = 1000 Gram, so factor is 1000).
                </div>
            </div>
        </div>
    </div>
</div> 