<?php
require_once 'config.php';
$page_title = 'Cek Tagihan - SPAM Desa Gemuruh';

$hasil = null;
$error_msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['id_meteran'])) {
    $id_meteran = trim($_POST['id_meteran']);
    
    $stmt = $pdo->prepare("
        SELECT p.nama, p.id_meteran, p.no_hp, 
               t.total, t.status, t.bulan, t.tahun, t.tgl_tagihan, t.tgl_bayar,
               m.pemakaian, m.meter_awal, m.meter_akhir
        FROM pelanggan p
        LEFT JOIN tagihan t ON p.id = t.id_pelanggan
        LEFT JOIN meteran m ON t.id_meteran = m.id
        WHERE p.id_meteran = ?
        ORDER BY t.tahun DESC, t.bulan DESC
        LIMIT 1
    ");
    $stmt->execute([$id_meteran]);
    $hasil = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$hasil) {
        $error_msg = "ID Meteran tidak ditemukan atau belum memiliki tagihan.";
    }
}

$nama_bulan = ['','Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?= $page_title ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://unpkg.com/html5-qrcode"></script>
    <style>
        :root { --primary-sage: #3A7CA5; --dark-sage: #2C5F7D; }
        body { background: #f4f7fe; font-family: 'Segoe UI', sans-serif; color: #2f3440; }
        .hero-check {
            background: linear-gradient(135deg, var(--primary-sage) 0%, var(--dark-sage) 100%);
            color: white;
            padding: 40px 20px 60px;
            border-bottom-left-radius: 40px;
            border-bottom-right-radius: 40px;
            text-align: center;
        }
        .card-soft {
            background: white; border: none; border-radius: 20px;
            box-shadow: 0 6px 20px rgba(0,0,0,0.05); padding: 20px; margin-top: -30px;
        }
        .form-control { border-radius: 12px; padding: 12px 15px; border: 1px solid #e0e0e0; }
        .form-control:focus { border-color: var(--primary-sage); box-shadow: 0 0 0 0.25rem rgba(58, 124, 165, 0.25); }
        .btn-sage { background: var(--primary-sage); color: white; border: none; border-radius: 12px; padding: 12px; font-weight: 700; width: 100%; }
        .btn-sage:hover { background: var(--dark-sage); color: white; }
        .btn-scan-input {
            background: #f8f9fa; border: 1px solid #e0e0e0; border-left: none;
            border-radius: 0 12px 12px 0; color: var(--primary-sage);
        }
        .status-lunas { background: #d4edda; color: #155724; padding: 5px 12px; border-radius: 20px; font-weight: 700; font-size: 0.85rem; }
        .status-belum { background: #fff3cd; color: #856404; padding: 5px 12px; border-radius: 20px; font-weight: 700; font-size: 0.85rem; }
        .detail-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px dashed #e0e0e0; }
        .detail-row:last-child { border-bottom: none; }
        .detail-label { color: #7a8190; font-size: 0.9rem; }
        .detail-value { font-weight: 700; color: #2f3440; font-size: 0.95rem; }
        .total-box { background: #f0f7ff; border-radius: 12px; padding: 15px; text-align: center; margin-top: 15px; }
        .total-label { font-size: 0.85rem; color: #5a6270; }
        .total-value { font-size: 1.8rem; font-weight: 800; color: var(--primary-sage); }
    </style>
</head>
<body>

<div class="hero-check">
    <div class="container">
        <i class="fa-solid fa-file-invoice-dollar fa-3x mb-3"></i>
        <h3 class="fw-bold">Cek Tagihan Air</h3>
        <p class="mb-0 opacity-75">Masukkan ID Meteran atau scan barcode untuk melihat tagihan.</p>
    </div>
</div>

<div class="container pb-5">
    <div class="card-soft">
        <form method="POST" id="formCekTagihan" class="mb-4">
            <div class="mb-3">
                <label class="form-label fw-bold small text-muted">ID Meteran</label>
                <div class="input-group">
                    <span class="input-group-text bg-light border-end-0" style="border-radius: 12px 0 0 12px; border-color: #e0e0e0;">
                        <i class="fa-solid fa-droplet text-muted"></i>
                    </span>
                    <input type="text" name="id_meteran" id="id_meteran_input" class="form-control border-start-0 ps-0" 
                           placeholder="Contoh: MTR-0001" required 
                           value="<?= isset($_POST['id_meteran']) ? htmlspecialchars($_POST['id_meteran']) : '' ?>">
                    <button class="btn btn-scan-input" type="button" onclick="openScanner()" title="Scan Barcode">
                        <i class="fa-solid fa-qrcode fa-lg"></i>
                    </button>
                </div>
            </div>
            <button type="submit" class="btn btn-sage">
                <i class="fa-solid fa-magnifying-glass me-2"></i> Cari Tagihan
            </button>
        </form>

        <?php if ($error_msg): ?>
            <div class="alert alert-warning text-center" style="border-radius: 12px; font-size: 0.9rem;">
                <i class="fa-solid fa-circle-exclamation me-1"></i> <?= htmlspecialchars($error_msg) ?>
            </div>
        <?php elseif ($hasil): ?>
            <div class="text-center mb-3">
                <h5 class="fw-bold mb-1"><?= htmlspecialchars($hasil['nama']) ?></h5>
                <span class="text-muted small">ID: <?= htmlspecialchars($hasil['id_meteran']) ?></span>
            </div>

            <div class="total-box mb-3">
                <div class="total-label">Total Tagihan Bulan <?= $nama_bulan[$hasil['bulan']] ?> <?= $hasil['tahun'] ?></div>
                <div class="total-value"><?= format_rupiah($hasil['total']) ?></div>
                <div class="mt-2">
                    <?php if ($hasil['status'] === 'lunas'): ?>
                        <span class="status-lunas"><i class="fa-solid fa-check-circle me-1"></i> LUNAS</span>
                        <div class="small text-muted mt-1">Dibayar: <?= date('d/m/Y', strtotime($hasil['tgl_bayar'])) ?></div>
                    <?php else: ?>
                        <span class="status-belum"><i class="fa-solid fa-clock me-1"></i> BELUM LUNAS</span>
                        <div class="small text-muted mt-1">Silakan lakukan pembayaran ke petugas.</div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="px-2">
                <div class="detail-row">
                    <span class="detail-label">Meter Awal</span>
                    <span class="detail-value"><?= number_format($hasil['meter_awal'], 3) ?> m³</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Meter Akhir</span>
                    <span class="detail-value"><?= number_format($hasil['meter_akhir'], 3) ?> m³</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Pemakaian</span>
                    <span class="detail-value text-primary"><?= number_format($hasil['pemakaian'], 3) ?> m³</span>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <div class="text-center mt-4">
        <a href="index.php" class="text-decoration-none small text-muted">
            <i class="fa-solid fa-arrow-left me-1"></i> Kembali ke Beranda
        </a>
    </div>
</div>

<!-- Modal Scanner -->
<div class="modal fade" id="scanModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen">
        <div class="modal-content bg-dark">
            <div class="modal-header border-0">
                <h5 class="modal-title text-white">Scan Barcode Meteran</h5>
                <button type="button" class="btn-close btn-close-white" onclick="stopScanner()"></button>
            </div>
            <div class="modal-body">
                <div id="reader" style="width: 100%;"></div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
let html5Qr;
function openScanner() {
    let modal = new bootstrap.Modal(document.getElementById('scanModal'));
    modal.show();
    html5Qr = new Html5Qrcode("reader");
    html5Qr.start(
        { facingMode: "environment" },
        { fps: 10, qrbox: 250, aspectRatio: 1 },
        (decodedText) => {
            html5Qr.stop().then(() => {
                html5Qr.clear();
                let modal = bootstrap.Modal.getInstance(document.getElementById('scanModal'));
                modal.hide();
                
                // Isi input dan otomatis submit
                document.getElementById('id_meteran_input').value = decodedText;
                document.getElementById('formCekTagihan').submit();
            });
        }
    );
}

function stopScanner() {
    if (html5Qr) {
        html5Qr.stop().then(() => { html5Qr.clear(); }).catch(err => {});
    }
    let modal = bootstrap.Modal.getInstance(document.getElementById('scanModal'));
    if (modal) modal.hide();
}
</script>
</body>
</html>