<?php
require_once __DIR__ . '/../../includes/init.php';
middleware(['mr']);

$db  = getDBConnection();
$uid = (int)getSession('user_id');

// Filters
$filterType = in_array($_GET['type'] ?? '', ['solar','kcc','']) ? ($_GET['type'] ?? '') : '';
$filterDate = $_GET['date'] ?? '';

$where  = "WHERE r.user_id = ?";
$params = [$uid];
if ($filterType) { $where .= " AND r.reading_type = ?"; $params[] = $filterType; }
if ($filterDate) { $where .= " AND r.reading_date = ?"; $params[] = $filterDate; }

$readings = dbRows($db,
    "SELECT r.*, c.consumer_name, c.meter_number, c.connection_number
     FROM readings r
     JOIN consumers c ON c.id = r.consumer_id
     {$where}
     ORDER BY r.created_at DESC LIMIT 100",
    $params);

$totalSolar = (int)safeDbVal($db, "SELECT COUNT(*) FROM readings WHERE user_id=? AND reading_type='solar'", [$uid]);
$totalKcc   = (int)safeDbVal($db, "SELECT COUNT(*) FROM readings WHERE user_id=? AND reading_type='kcc'", [$uid]);

$pageTitle = 'My Readings';
include __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <h1><i class="bi bi-clock-history me-2 text-primary"></i>My Readings</h1>
    </div>
    <div class="d-flex gap-2">
        <span class="badge bg-warning text-dark p-2">Solar: <?= $totalSolar ?></span>
        <span class="badge bg-primary p-2">KCC: <?= $totalKcc ?></span>
    </div>
</div>

<!-- Filter form -->
<div class="erp-card mb-3">
    <form method="GET" class="row g-2 align-items-end">
        <div class="col-6 col-md-3">
            <label class="form-label" style="font-size:.82rem;">Type</label>
            <select name="type" class="form-select">
                <option value="">All Types</option>
                <option value="solar" <?= $filterType==='solar'?'selected':'' ?>>Solar</option>
                <option value="kcc"   <?= $filterType==='kcc'  ?'selected':'' ?>>KCC</option>
            </select>
        </div>
        <div class="col-6 col-md-3">
            <label class="form-label" style="font-size:.82rem;">Date</label>
            <input type="date" name="date" class="form-select" value="<?= h($filterDate) ?>">
        </div>
        <div class="col-auto">
            <button type="submit" class="btn btn-erp"><i class="bi bi-funnel me-1"></i>Filter</button>
        </div>
        <div class="col-auto">
            <a href="?" class="btn btn-outline-secondary"><i class="bi bi-x"></i></a>
        </div>
    </form>
</div>

<!-- Table -->
<div class="erp-card">
    <?php if (empty($readings)): ?>
    <div class="text-center py-5 text-muted">
        <i class="bi bi-clipboard-x" style="font-size:2.5rem;opacity:.3;"></i>
        <p class="mt-2">No readings found.</p>
        <a href="<?= BASE_URL ?>/modules/readings/add.php?type=solar" class="btn btn-erp btn-sm">Add Reading</a>
    </div>
    <?php else: ?>
    <div class="table-responsive">
        <table class="table table-hover" style="font-size:.84rem;">
            <thead class="table-light">
                <tr>
                    <th>#</th>
                    <th>Consumer</th>
                    <th>Type</th>
                    <th>Status</th>
                    <th>Photo</th>
                    <th>GPS</th>
                    <th>Date</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($readings as $i => $r): ?>
                <tr>
                    <td class="text-muted"><?= $i+1 ?></td>
                    <td>
                        <div class="fw-semibold"><?= h($r['consumer_name']) ?></div>
                        <small class="text-muted">Meter: <?= h($r['meter_number']) ?></small>
                    </td>
                    <td><?= typeBadge($r['reading_type']) ?></td>
                    <td><?= statusBadge($r['status']) ?></td>
                    <td>
                        <?php if ($r['image_path']): ?>
                        <a href="<?= imgUrl($r['image_path']) ?>" target="_blank" rel="noopener">
                            <img src="<?= imgUrl($r['image_path']) ?>"
                                 style="width:44px;height:44px;object-fit:cover;border-radius:6px;border:1px solid #e2e8f0;">
                        </a>
                        <?php else: ?>
                        <span class="text-muted">—</span>
                        <?php endif; ?>
                    </td>
                    <td style="font-size:.75rem;">
                        <?php if ($r['gps_lat']): ?>
                        <a href="https://maps.google.com/?q=<?= $r['gps_lat'] ?>,<?= $r['gps_lng'] ?>"
                           target="_blank" class="text-primary">
                            <i class="bi bi-geo-alt-fill"></i> View
                        </a>
                        <?php else: ?>
                        <span class="text-muted">—</span>
                        <?php endif; ?>
                    </td>
                    <td class="text-muted" style="font-size:.76rem;"><?= formatDt($r['created_at']) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<?php include __DIR__ . '/../../includes/footer.php'; ?>
