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

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

$unit_id = (int)($_GET['id'] ?? 0);
$user_id = $_SESSION['user_id'] ?? 0;
$company_id = $_SESSION['company_id'] ?? null;

if (!$unit_id) {
    die("Invalid unit.");
}

/* Fetch unit */
$stmt = $pdo->prepare("
    SELECT * FROM inventory_units WHERE id = ?
");
$stmt->execute([$unit_id]);
$unit = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$unit) {
    die("Unit not found.");
}

/* Lock ACTIVE & REPLACED */
if (in_array($unit['status'], ['ACTIVE','REPLACED'])) {
    die("Movement locked for this unit.");
}

$error = "";

/* Allowed transitions */
$allowed_transitions = [
    'IN_STOCK' => ['WITH_DISTRIBUTOR','READY_FOR_INSTALL','FAULTY'],
    'WITH_DISTRIBUTOR' => ['IN_STOCK','READY_FOR_INSTALL','FAULTY'],
    'READY_FOR_INSTALL' => ['IN_STOCK','ACTIVE'],
    'FAULTY' => ['REPLACED','IN_STOCK']
];

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

    $new_status = $_POST['new_status'] ?? '';
    $notes = trim($_POST['notes'] ?? '');
    $activation_company_id = $_POST['activation_company_id'] ?? null;

    $current_status = $unit['status'];

    if (!isset($allowed_transitions[$current_status]) ||
        !in_array($new_status, $allowed_transitions[$current_status])) {

        $error = "Invalid movement transition.";

    } else {

        $pdo->beginTransaction();

        /* If activating → create operational meter */
if ($new_status === 'ACTIVE') {

    if (!$activation_company_id) {
        $pdo->rollBack();
        $error = "Company must be selected for activation.";
    } else {

        /* Create operational meter */
        $stmt = $pdo->prepare("
            INSERT INTO operational_meters
            (inventory_unit_id, company_id, meter_number,
             status, activated_at, created_by)
            VALUES (?, ?, ?, 'ACTIVE', NOW(), ?)
        ");

        $stmt->execute([
            $unit_id,
            $activation_company_id,
            $unit['meter_number'],
            $user_id
        ]);
    }
}

        if (!$error) {

            /* Update inventory unit */
            $stmt = $pdo->prepare("
                UPDATE inventory_units
                SET status = ?
                WHERE id = ?
            ");
            $stmt->execute([$new_status, $unit_id]);

            /* Log movement */
            $stmt = $pdo->prepare("
                INSERT INTO inventory_movements
                (unit_id, from_company_id, to_company_id,
                 previous_status, new_status,
                 movement_type, performed_by_user_id, notes)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");

            $movement_type = ($new_status === 'ACTIVE') ? 'ACTIVATION' : 'TRANSFER';

            $stmt->execute([
                $unit_id,
                $unit['current_holder_company_id'],
                $activation_company_id ?? $company_id,
                $current_status,
                $new_status,
                $movement_type,
                $user_id,
                $notes
            ]);

            $pdo->commit();
            header("Location: units.php");
            exit;
        }
    }
}

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

<div class="container">

    <div class="page-header">
        <h2>Move Unit</h2>
        <p class="page-subtitle">
            Change inventory lifecycle status.
        </p>
    </div>

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

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

    <form method="POST">

        <div class="form-group">
            <label>Current Status</label>
            <input type="text" value="<?= htmlspecialchars($unit['status']) ?>" disabled>
        </div>

        <div class="form-group">
            <label>New Status</label>
            <select name="new_status" id="statusSelect" required>
                <option value="">Select</option>
                <?php
                foreach ($allowed_transitions[$unit['status']] ?? [] as $s) {
                    echo "<option value='$s'>$s</option>";
                }
                ?>
            </select>
        </div>

        <div class="form-group" id="companyField" style="display:none;">
            <label>Assign To Company</label>
            <select name="activation_company_id">
                <option value="">Select Company</option>
                <?php
                $companies = $pdo->query("
                    SELECT id, company_name 
                    FROM companies 
                    ORDER BY company_name ASC
                ")->fetchAll(PDO::FETCH_ASSOC);

                foreach ($companies as $c) {
                    echo "<option value='{$c['id']}'>" .
                         htmlspecialchars($c['company_name']) .
                         "</option>";
                }
                ?>
            </select>
        </div>

        <div class="form-group">
            <label>Notes (optional)</label>
            <textarea name="notes"></textarea>
        </div>

        <button type="submit" class="btn">Confirm Movement</button>

    </form>

</div>

<script>
document.getElementById('statusSelect').addEventListener('change', function() {
    document.getElementById('companyField').style.display =
        this.value === 'ACTIVE' ? 'block' : 'none';
});
</script>

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