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

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

/* =========================================
   VALIDATE METER
========================================= */

if (!isset($_GET['id'])) {
    die("Meter ID missing.");
}

$meterId = (int)$_GET['id'];

$stmt = $pdo->prepare("SELECT * FROM meters WHERE id = ?");
$stmt->execute([$meterId]);
$meter = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$meter) {
    die("Meter not found.");
}

if ($meter['status'] !== 'WITH_DISTRIBUTOR') {
    die("Only meters with distributor can be returned.");
}

$errors = [];

/* =========================================
   HANDLE CONFIRMATION
========================================= */

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

    try {

        $pdo->beginTransaction();

        $update = $pdo->prepare("
            UPDATE meters
            SET current_holder_company_id = NULL,
                status = 'IN_STOCK'
            WHERE id = ?
        ");
        $update->execute([$meterId]);

        $movement = $pdo->prepare("
            INSERT INTO meter_movements
            (meter_id, movement_type, reason, moved_by_user_id)
            VALUES (?, 'RETURN', 'Returned to EDM warehouse', ?)
        ");
        $movement->execute([$meterId, $_SESSION['user_id']]);

        $audit = $pdo->prepare("
            INSERT INTO audit_logs
            (user_id, action)
            VALUES (?, ?)
        ");
        $audit->execute([
            $_SESSION['user_id'],
            "Returned meter ID {$meterId} to warehouse"
        ]);

        $pdo->commit();

        header("Location: inventory.php");
        exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        $errors[] = "Return failed. Please try again.";
    }
}

/* =========================================
   LOAD UNIVERSAL LAYOUT
========================================= */

$breadcrumb = "Return Meter";
require_once __DIR__ . '/../includes/layout.php';
?>

<div class="page-header">
    <h2>Return Meter</h2>
    <p class="page-subtitle">
        Confirm return of meter #<?= htmlspecialchars($meter['meter_number']) ?> to EDM warehouse.
    </p>
</div>

<div class="table-wrap">
    <div style="padding:25px; max-width:600px;">

        <?php if (!empty($errors)): ?>
            <div style="margin-bottom:15px; color:#dc2626;">
                <?php foreach ($errors as $error): ?>
                    <div><?= htmlspecialchars($error) ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <form method="POST">

            <div style="margin-bottom:20px; padding:15px; background:#fef3c7; border-radius:8px;">
                This meter is currently with a distributor.  
                Returning it will move it back to <strong>IN_STOCK</strong>.
            </div>

            <button type="submit" style="
                background:#dc2626;
                color:white;
                padding:10px 18px;
                border:none;
                border-radius:6px;
                cursor:pointer;
            ">
                Confirm Return
            </button>

        </form>

    </div>
</div>

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