<?php
require_once __DIR__ . '/../../includes/auth.php';
requireLogin();
requirePermission('inventory.manage');

require_once __DIR__ . '/../../config/database.php';

$company_id = $_SESSION['company_id'] ?? 0;
$role = $_SESSION['role_name'] ?? '';

$error = "";
$success = "";

/* Fetch products */
$stmt = $pdo->query("SELECT id, brand, model FROM inventory_products ORDER BY brand, model");
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $product_id   = $_POST['product_id'] ?? '';
    $meter_number = trim($_POST['meter_number'] ?? '');
    $serial       = trim($_POST['serial_number'] ?? '');

    if (!$product_id || !$meter_number) {
        $error = "Product and Meter Number are required.";
    } else {

        $stmt = $pdo->prepare("
            INSERT INTO inventory_units
            (company_id, product_id, meter_number, serial_number)
            VALUES (?, ?, ?, ?)
        ");

        try {
            $stmt->execute([$company_id, $product_id, $meter_number, $serial]);
            $success = "Unit created successfully.";
        } catch (PDOException $e) {
            $error = "Meter already exists for this company.";
        }
    }
}

$breadcrumb = "Add Unit";
require_once __DIR__ . '/../../includes/layout.php';
?>

<div class="container">

    <div class="page-header">
        <h2>Add Inventory Unit</h2>
        <p class="page-subtitle">
            Register physical meter into stock.
        </p>
    </div>

    <div class="topbar">
        <a class="btn secondary" href="units.php">← Back to Units</a>
    </div>

    <?php if ($error): ?>
        <div class="alert error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="alert success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <form method="POST">

        <div class="form-group">
            <label>Product</label>
            <select name="product_id" required>
                <option value="">Select Product</option>
                <?php foreach ($products as $p): ?>
                    <option value="<?= $p['id'] ?>">
                        <?= htmlspecialchars($p['brand'] . ' ' . $p['model']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-group">
            <label>Meter Number</label>
            <input type="text" name="meter_number" required>
        </div>

        <div class="form-group">
            <label>Serial Number (optional)</label>
            <input type="text" name="serial_number">
        </div>

        <button type="submit" class="btn">Save Unit</button>

    </form>

</div>

<?php require_once __DIR__ . '/../../includes/layout_footer.php'; ?>