<?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 (in_array($meter['status'], ['INSTALLED', 'FAULTY'], true)) {
    die("This meter cannot be transferred.");
}

/* =========================================
   FETCH COMPANIES
========================================= */

$companies = $pdo->query("
    SELECT id, company_name 
    FROM companies 
    ORDER BY company_name ASC
")->fetchAll(PDO::FETCH_ASSOC);

$errors = [];

/* =========================================
   HANDLE FORM
========================================= */

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

    $companyId = (int)($_POST['company_id'] ?? 0);

    if (!$companyId) {
        $errors[] = "Please select a valid company.";
    }

    if (empty($errors)) {

        try {

            $pdo->beginTransaction();

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

            $log = $pdo->prepare("
                INSERT INTO meter_movements 
                (meter_id, movement_type, reason, moved_by_user_id)
                VALUES (?, 'TRANSFER', 'Transferred to distributor', ?)
            ");
            $log->execute([$meterId, $_SESSION['user_id']]);

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

            $pdo->commit();

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

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

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

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

<div class="page-header">
    <h2>Transfer Meter</h2>
    <p class="page-subtitle">
        Transfer meter #<?= htmlspecialchars($meter['meter_number']) ?> to a distributor.
    </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;">
                <label>Select Distributor</label>
                <select name="company_id" required>
                    <option value="">-- Select Company --</option>
                    <?php foreach ($companies as $company): ?>
                        <option value="<?= $company['id'] ?>">
                            <?= htmlspecialchars($company['company_name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <button type="submit" style="
                background:var(--edm-orange);
                color:white;
                padding:10px 18px;
                border:none;
                border-radius:6px;
                cursor:pointer;
            ">
                Confirm Transfer
            </button>

        </form>

    </div>
</div>

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