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

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

$company_id = $_SESSION['company_id'];

$stmt = $pdo->prepare("
    SELECT i.*, u.full_name AS assigned_name
    FROM meter_issues i
    LEFT JOIN users u ON u.id = i.assigned_to
    WHERE i.company_id = ?
    ORDER BY i.created_at DESC
");
$stmt->execute([$company_id]);
$issues = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<div class="content">

<h2>⚡ Meter Issues Tracker</h2>

<a href="create.php" class="btn-primary">+ Create Issue</a>

<table class="table">
<thead>
<tr>
<th>Meter</th>
<th>Title</th>
<th>Status</th>
<th>Assigned</th>
<th>Date</th>
<th></th>
</tr>
</thead>
<tbody>

<?php foreach ($issues as $i): ?>
<tr>
<td><?= htmlspecialchars($i['meter_number']) ?></td>
<td><?= htmlspecialchars($i['issue_title']) ?></td>
<td><?= $i['current_status'] ?></td>
<td><?= $i['assigned_name'] ?? '-' ?></td>
<td><?= date('Y-m-d', strtotime($i['created_at'])) ?></td>
<td><a href="view.php?id=<?= $i['id'] ?>">View</a></td>
</tr>
<?php endforeach; ?>

</tbody>
</table>

</div>

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