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

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

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

$stmt = $pdo->prepare("
    SELECT * FROM meter_issues
    WHERE id = ? AND company_id = ?
");
$stmt->execute([$id, $company_id]);
$issue = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$issue) die("Not found");

/* COMMENT */
if (isset($_POST['comment'])) {
    logMeterEvent($pdo, $id, 'COMMENT', $_POST['comment']);
}

/* VENDOR TEST */
if (isset($_POST['vendor'])) {

    $stmt = $pdo->prepare("
        INSERT INTO meter_issue_vendor_tests
        (issue_id, vendor, result, notes, tested_by)
        VALUES (?, ?, ?, ?, ?)
    ");

    $stmt->execute([
        $id,
        $_POST['vendor'],
        $_POST['result'],
        $_POST['notes'],
        $_SESSION['user_id']
    ]);

    logMeterEvent($pdo, $id, 'VENDOR_TEST', $_POST['vendor'].' '.$_POST['result']);
}

/* LOAD LOGS */
$stmt = $pdo->prepare("SELECT * FROM meter_issue_logs WHERE issue_id = ? ORDER BY created_at DESC");
$stmt->execute([$id]);
$logs = $stmt->fetchAll();

require_once __DIR__ . '/../../includes/header.php';
require_once __DIR__ . '/../../includes/sidebar.php';
?>

<div class="content">

<h2>Meter: <?= $issue['meter_number'] ?></h2>

<hr>

<h3>Add Vendor Test</h3>

<form method="POST">
<input name="vendor" placeholder="Vendor">
<select name="result">
<option>WORKING</option>
<option>FAIL</option>
<option>INTERMITTENT</option>
</select>
<input name="notes" placeholder="Notes">
<button>Add</button>
</form>

<hr>

<h3>Add Comment</h3>

<form method="POST">
<textarea name="comment"></textarea>
<button>Add</button>
</form>

<hr>

<h3>Timeline</h3>

<ul>
<?php foreach ($logs as $l): ?>
<li><?= $l['message'] ?> - <?= $l['created_at'] ?></li>
<?php endforeach; ?>
</ul>

</div>

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