<?php
require_once __DIR__ . '/../../includes/init.php';
middleware(['je','sdo','exn','super_admin']);

$db      = getDBConnection();
$type    = in_array($_GET['type'] ?? '', ['solar','kcc','bills']) ? $_GET['type'] : 'solar';
$isBills = ($type === 'bills');

// ── Division filter for non-super_admin ──────────────────────
function getUserDivFilter($alias = 'c') {
    $role   = getSession('role');
    $rawDiv = getSession('division') ?? '';
    if ($role === 'super_admin' || !$rawDiv || $rawDiv === 'All') return ['', []];
    $decoded  = json_decode($rawDiv, true);
    $assigned = is_array($decoded) ? array_filter($decoded) : [trim($rawDiv)];
    if (empty($assigned)) return ['', []];
    $ph = implode(',', array_fill(0, count($assigned), '?'));
    return [" AND {$alias}.division IN ({$ph})", array_values($assigned)];
}

// ── Filters ───────────────────────────────────────────────────
$filterMR     = (int)($_GET['mr'] ?? 0);
$filterDate1  = $_GET['date_from'] ?? '';
$filterDate2  = $_GET['date_to']   ?? '';
$filterStatus = $_GET['status']    ?? '';

list($divSql, $divParams) = getUserDivFilter('c');

// ── CSV Export ────────────────────────────────────────────────
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    if (!$isBills) {
        $where  = "WHERE r.reading_type = ?";
        $params = [$type];
        if ($filterMR)     { $where .= " AND r.user_id = ?";      $params[] = $filterMR; }
        if ($filterDate1)  { $where .= " AND r.reading_date >= ?"; $params[] = $filterDate1; }
        if ($filterDate2)  { $where .= " AND r.reading_date <= ?"; $params[] = $filterDate2; }
        if ($filterStatus) { $where .= " AND r.status = ?";        $params[] = $filterStatus; }
        $where  .= $divSql;
        $params  = array_merge($params, $divParams);
        $rows = dbRows($db,
            "SELECT c.consumer_name, c.meter_number, c.connection_number, c.address, c.division,
                    r.status, r.gps_lat, r.gps_lng, u.full_name AS mr_name,
                    r.reading_date, r.remark, r.created_at
             FROM readings r
             JOIN consumers c ON c.id=r.consumer_id
             JOIN users u ON u.id=r.user_id
             {$where} ORDER BY r.created_at DESC", $params);
        $headers  = ['Consumer Name','Meter No','Connection No','Address','Division','Status','GPS Lat','GPS Lng','MR Name','Reading Date','Remark','Submitted At'];
        $filename = strtoupper($type) . '_readings_' . date('Ymd') . '.csv';
    } else {
        $where  = "WHERE 1=1";
        $params = [];
        if ($filterMR)    { $where .= " AND b.user_id = ?";           $params[] = $filterMR; }
        if ($filterDate1) { $where .= " AND DATE(b.created_at) >= ?"; $params[] = $filterDate1; }
        if ($filterDate2) { $where .= " AND DATE(b.created_at) <= ?"; $params[] = $filterDate2; }
        // bills division filter via consumer join
        $billDivSql = '';
        if (!empty($divParams)) {
            $ph = implode(',', array_fill(0, count($divParams), '?'));
            $billDivSql = " AND c.division IN ({$ph})";
        }
        $rows = dbRows($db,
            "SELECT b.consumer_name, b.meter_number, b.bill_type, b.delivery_remark,
                    b.other_remark, b.gps_lat, b.gps_lng, u.full_name AS mr_name, b.created_at
             FROM bills b
             JOIN users u ON u.id=b.user_id
             LEFT JOIN consumers c ON c.id=b.consumer_id
             {$where}{$billDivSql} ORDER BY b.created_at DESC",
            array_merge($params, $divParams));
        $headers  = ['Consumer Name','Meter No','Bill Type','Delivery Remark','Other Remark','GPS Lat','GPS Lng','MR Name','Submitted At'];
        $filename = 'bills_' . date('Ymd') . '.csv';
    }
    header('Content-Type: text/csv; charset=UTF-8');
    header("Content-Disposition: attachment; filename=\"{$filename}\"");
    header('Pragma: no-cache');
    $out = fopen('php://output', 'w');
    fputs($out, "\xEF\xBB\xBF");
    fputcsv($out, $headers);
    foreach ($rows as $row) { fputcsv($out, array_values($row)); }
    fclose($out);
    exit;
}

// ── Main query ────────────────────────────────────────────────
$page    = max(1, (int)($_GET['page'] ?? 1));
$perPage = 25;
$offset  = ($page - 1) * $perPage;

if (!$isBills) {
    $where  = "WHERE r.reading_type = ?";
    $params = [$type];
    if ($filterMR)     { $where .= " AND r.user_id = ?";      $params[] = $filterMR; }
    if ($filterDate1)  { $where .= " AND r.reading_date >= ?"; $params[] = $filterDate1; }
    if ($filterDate2)  { $where .= " AND r.reading_date <= ?"; $params[] = $filterDate2; }
    if ($filterStatus) { $where .= " AND r.status = ?";        $params[] = $filterStatus; }
    $where  .= $divSql;
    $params  = array_merge($params, $divParams);

    $total = (int)dbVal($db, "SELECT COUNT(*) FROM readings r JOIN consumers c ON c.id=r.consumer_id {$where}", $params);
    $rows  = dbRows($db,
        "SELECT r.*, c.consumer_name, c.meter_number, c.connection_number, c.address, c.division,
                u.full_name AS mr_name
         FROM readings r
         JOIN consumers c ON c.id=r.consumer_id
         JOIN users u ON u.id=r.user_id
         {$where} ORDER BY r.created_at DESC LIMIT {$perPage} OFFSET {$offset}", $params);
} else {
    $where  = "WHERE 1=1";
    $params = [];
    if ($filterMR)    { $where .= " AND b.user_id = ?";           $params[] = $filterMR; }
    if ($filterDate1) { $where .= " AND DATE(b.created_at) >= ?"; $params[] = $filterDate1; }
    if ($filterDate2) { $where .= " AND DATE(b.created_at) <= ?"; $params[] = $filterDate2; }
    $billDivSql = '';
    if (!empty($divParams)) {
        $ph = implode(',', array_fill(0, count($divParams), '?'));
        $billDivSql = " AND c.division IN ({$ph})";
    }
    $total = (int)dbVal($db,
        "SELECT COUNT(*) FROM bills b LEFT JOIN consumers c ON c.id=b.consumer_id {$where}{$billDivSql}",
        array_merge($params, $divParams));
    $rows  = dbRows($db,
        "SELECT b.*, u.full_name AS mr_name
         FROM bills b
         JOIN users u ON u.id=b.user_id
         LEFT JOIN consumers c ON c.id=b.consumer_id
         {$where}{$billDivSql} ORDER BY b.created_at DESC LIMIT {$perPage} OFFSET {$offset}",
        array_merge($params, $divParams));
}

$totalPages = (int)ceil($total / $perPage);
$mrs = dbRows($db, "SELECT id,full_name FROM users WHERE role='mr' AND is_active=1 ORDER BY full_name");

if ($type === 'solar')      $typeLabelFull = 'Solar Readings';
elseif ($type === 'kcc')    $typeLabelFull = 'KCC Readings';
else                        $typeLabelFull = 'Bill Distribution';

$pageTitle = $typeLabelFull . ' Report';
include __DIR__ . '/../../includes/header.php';
?>

<!-- Type switcher -->
<div class="d-flex gap-2 mb-3 flex-wrap">
    <a href="?type=solar" class="btn btn-sm <?= $type==='solar'?'btn-warning':'btn-outline-secondary' ?>"><i class="bi bi-sun-fill me-1"></i>Solar</a>
    <a href="?type=kcc"   class="btn btn-sm <?= $type==='kcc'  ?'btn-primary':'btn-outline-secondary' ?>"><i class="bi bi-lightning-fill me-1"></i>KCC</a>
    <a href="?type=bills" class="btn btn-sm <?= $type==='bills'?'btn-success':'btn-outline-secondary' ?>"><i class="bi bi-receipt-cutoff me-1"></i>Bills</a>
    <?php if (!empty($divParams)): ?>
    <span class="badge bg-info d-flex align-items-center" style="font-size:.75rem;">
        <i class="bi bi-funnel me-1"></i>Division filtered
    </span>
    <?php endif; ?>
</div>

<!-- Filters -->
<div class="erp-card mb-3">
    <form method="GET" class="row g-2 align-items-end">
        <input type="hidden" name="type" value="<?= h($type) ?>">
        <div class="col-6 col-md-3">
            <label class="form-label" style="font-size:.82rem;">Meter Reader</label>
            <select name="mr" class="form-select">
                <option value="">All MRs</option>
                <?php foreach ($mrs as $m): ?>
                <option value="<?= $m['id'] ?>" <?= $filterMR==$m['id']?'selected':'' ?>><?= h($m['full_name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-6 col-md-2">
            <label class="form-label" style="font-size:.82rem;">From Date</label>
            <input type="date" name="date_from" class="form-control" value="<?= h($filterDate1) ?>">
        </div>
        <div class="col-6 col-md-2">
            <label class="form-label" style="font-size:.82rem;">To Date</label>
            <input type="date" name="date_to" class="form-control" value="<?= h($filterDate2) ?>">
        </div>
        <?php if (!$isBills): ?>
        <div class="col-6 col-md-2">
            <label class="form-label" style="font-size:.82rem;">Status</label>
            <select name="status" class="form-select">
                <option value="">All Status</option>
                <option value="mri_done"             <?= $filterStatus==='mri_done'?'selected':'' ?>>MRI Done</option>
                <option value="smart_meter"          <?= $filterStatus==='smart_meter'?'selected':'' ?>>Smart Meter</option>
                <option value="meter_port_defective" <?= $filterStatus==='meter_port_defective'?'selected':'' ?>>Port Defective</option>
            </select>
        </div>
        <?php endif; ?>
        <div class="col-auto d-flex gap-1">
            <button type="submit" class="btn btn-erp"><i class="bi bi-funnel me-1"></i>Filter</button>
            <a href="?type=<?= $type ?>" class="btn btn-outline-secondary"><i class="bi bi-x"></i></a>
        </div>
    </form>
</div>

<!-- Summary + Export -->
<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
    <span class="text-muted" style="font-size:.85rem;">
        <strong><?= count($rows) ?></strong> of <strong><?= $total ?></strong> records
    </span>
    <a href="?type=<?= $type ?>&mr=<?= $filterMR ?>&date_from=<?= h($filterDate1) ?>&date_to=<?= h($filterDate2) ?>&status=<?= h($filterStatus) ?>&export=csv"
       class="btn btn-success btn-sm">
        <i class="bi bi-file-earmark-spreadsheet me-1"></i>Export CSV
    </a>
</div>

<!-- Data Table -->
<div class="erp-card">
    <?php if (empty($rows)): ?>
    <div class="text-center py-5 text-muted">
        <i class="bi bi-search" style="font-size:2.5rem;opacity:.3;"></i>
        <p class="mt-2">No records found.</p>
    </div>
    <?php elseif (!$isBills): ?>
    <div class="table-responsive">
        <table class="table table-hover" style="font-size:.83rem;">
            <thead class="table-dark">
                <tr>
                    <th>#</th><th>Consumer</th><th>Meter No</th><th>Division</th>
                    <th>Status</th><th>MR</th><th>Photo</th><th>GPS</th><th>Date</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $i => $r): ?>
                <tr>
                    <td class="text-muted"><?= $offset+$i+1 ?></td>
                    <td class="fw-semibold"><?= h($r['consumer_name']) ?></td>
                    <td><?= h($r['meter_number']) ?></td>
                    <td class="text-muted" style="font-size:.78rem;"><?= h($r['division'] ?? '—') ?></td>
                    <td><?= statusBadge($r['status']) ?></td>
                    <td><?= h($r['mr_name']) ?></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:48px;height:48px;object-fit:cover;border-radius:6px;border:1px solid #e2e8f0;">
                        </a>
                        <?php else: ?>—<?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: ?>—<?php endif; ?>
                    </td>
                    <td class="text-muted" style="font-size:.76rem;">
                        <?= $r['reading_date'] ? date('d M Y', strtotime($r['reading_date'])) : formatDt($r['created_at']) ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="table-responsive">
        <table class="table table-hover" style="font-size:.83rem;">
            <thead class="table-dark">
                <tr>
                    <th>#</th><th>Consumer</th><th>Meter No</th>
                    <th>Bill Type</th><th>Delivery</th><th>MR</th>
                    <th>Photo</th><th>GPS</th><th>Date</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $i => $b): ?>
                <tr>
                    <td class="text-muted"><?= $offset+$i+1 ?></td>
                    <td class="fw-semibold"><?= h($b['consumer_name'] ?? '—') ?></td>
                    <td><?= h($b['meter_number'] ?? '—') ?></td>
                    <td><?= billTypeBadge($b['bill_type']) ?></td>
                    <td style="font-size:.8rem;"><?= h(remarkLabel($b['delivery_remark'])) ?></td>
                    <td><?= h($b['mr_name']) ?></td>
                    <td>
                        <?php if ($b['image_path']): ?>
                        <a href="<?= imgUrl($b['image_path']) ?>" target="_blank" rel="noopener">
                            <img src="<?= imgUrl($b['image_path']) ?>"
                                 style="width:48px;height:48px;object-fit:cover;border-radius:6px;border:1px solid #e2e8f0;">
                        </a>
                        <?php else: ?>—<?php endif; ?>
                    </td>
                    <td style="font-size:.75rem;">
                        <?php if ($b['gps_lat']): ?>
                        <a href="https://maps.google.com/?q=<?= $b['gps_lat'] ?>,<?= $b['gps_lng'] ?>" target="_blank" class="text-primary">
                            <i class="bi bi-geo-alt-fill"></i> View
                        </a>
                        <?php else: ?>—<?php endif; ?>
                    </td>
                    <td class="text-muted" style="font-size:.76rem;"><?= formatDt($b['created_at']) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>

    <?php if ($totalPages > 1): ?>
    <div class="d-flex align-items-center justify-content-between mt-3 flex-wrap gap-2">
        <span class="text-muted" style="font-size:.82rem;">Page <strong><?= $page ?></strong> of <strong><?= $totalPages ?></strong></span>
        <nav>
            <ul class="pagination pagination-sm mb-0">
                <li class="page-item <?= $page<=1?'disabled':'' ?>">
                    <a class="page-link" href="?type=<?= $type ?>&mr=<?= $filterMR ?>&date_from=<?= h($filterDate1) ?>&date_to=<?= h($filterDate2) ?>&status=<?= h($filterStatus) ?>&page=<?= $page-1 ?>"><i class="bi bi-chevron-left"></i></a>
                </li>
                <?php
                $start = max(1,$page-2); $end = min($totalPages,$page+2);
                $bu = "?type={$type}&mr={$filterMR}&date_from=".h($filterDate1)."&date_to=".h($filterDate2)."&status=".h($filterStatus)."&page=";
                if($start>1): ?><li class="page-item"><a class="page-link" href="<?= $bu ?>1">1</a></li><?php if($start>2): ?><li class="page-item disabled"><span class="page-link">…</span></li><?php endif; endif;
                for($p=$start;$p<=$end;$p++): ?>
                <li class="page-item <?= $p==$page?'active':'' ?>"><a class="page-link" href="<?= $bu ?><?= $p ?>"><?= $p ?></a></li>
                <?php endfor;
                if($end<$totalPages): if($end<$totalPages-1): ?><li class="page-item disabled"><span class="page-link">…</span></li><?php endif; ?><li class="page-item"><a class="page-link" href="<?= $bu ?><?= $totalPages ?>"><?= $totalPages ?></a></li><?php endif; ?>
                <li class="page-item <?= $page>=$totalPages?'disabled':'' ?>">
                    <a class="page-link" href="<?= $bu ?><?= $page+1 ?>"><i class="bi bi-chevron-right"></i></a>
                </li>
            </ul>
        </nav>
    </div>
    <?php endif; ?>
</div>

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