<?php
session_start();
require_once '../config.php';
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'petugas') {
    header("Location: ../login.php");
    exit;
}

// ==========================================
// FUNGSI KIRIM WHATSAPP VIA FONNTE
// ==========================================
function kirim_wa_fonnte($nomor, $pesan) {
    $token = defined('FONNTE_TOKEN') ? FONNTE_TOKEN : '';
    if (empty($token) || empty($nomor)) return false;
    
    $nomor = preg_replace('/^0/', '62', $nomor);
    $nomor = preg_replace('/\+/', '', $nomor);
    
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.fonnte.com/send",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => array(
            'target' => $nomor,
            'message' => $pesan,
            'countryCode' => '62'
        ),
        CURLOPT_HTTPHEADER => array("Authorization: $token"),
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

$bulan_ini = (int)date('m');
$tahun_ini = (int)date('Y');
$id_petugas = $_SESSION['id'];
$success_msg = '';
$error_msg = '';

// Handle Simpan Data Meteran
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['simpan_meteran'])) {
    $id_pelanggan = (int)$_POST['id_pelanggan'];
    $meter_awal = str_replace(',', '.', $_POST['meter_awal']);
    $meter_akhir = str_replace(',', '.', $_POST['meter_akhir']);
    
    if ($meter_akhir < $meter_awal) {
        $error_msg = "Meteran akhir tidak boleh lebih kecil dari meteran awal!";
    } else {
        $pemakaian = $meter_akhir - $meter_awal;
        
        // Ambil Tarif Terkini
        $tarif = $pdo->query("SELECT * FROM tarif ORDER BY id DESC LIMIT 1")->fetch();
        $biaya_pemakaian = $pemakaian * $tarif['harga_m3'];
        $biaya_abonemen = $tarif['biaya_abonemen'];
        $total_tagihan = $biaya_pemakaian + $biaya_abonemen;
        
        try {
            $pdo->beginTransaction();
            
            // 1. Simpan/Catat Data Meteran
            $stmt_meter = $pdo->prepare("INSERT INTO meteran (id_pelanggan, bulan, tahun, meter_awal, meter_akhir, pemakaian, id_petugas) VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE meter_awal=?, meter_akhir=?, pemakaian=?, id_petugas=?");
            $stmt_meter->execute([$id_pelanggan, $bulan_ini, $tahun_ini, $meter_awal, $meter_akhir, $pemakaian, $id_petugas, $meter_awal, $meter_akhir, $pemakaian, $id_petugas]);
            $id_meteran_baru = $pdo->lastInsertId();
            
            // 2. Buat/Update Tagihan
            $stmt_tagih = $pdo->prepare("INSERT INTO tagihan (id_pelanggan, id_meteran, bulan, tahun, biaya_pemakaian, biaya_abonemen, total, status, tgl_tagihan) VALUES (?, ?, ?, ?, ?, ?, ?, 'belum_lunas', CURDATE()) ON DUPLICATE KEY UPDATE id_meteran=?, biaya_pemakaian=?, biaya_abonemen=?, total=?, status='belum_lunas'");
            $stmt_tagih->execute([$id_pelanggan, $id_meteran_baru, $bulan_ini, $tahun_ini, $biaya_pemakaian, $biaya_abonemen, $total_tagihan, $id_meteran_baru, $biaya_pemakaian, $biaya_abonemen, $total_tagihan]);
            
            $pdo->commit();
            $success_msg = "Meteran berhasil dicatat dan tagihan dibuat!";

            // ==========================================
            // 3. KIRIM NOTIFIKASI WHATSAPP OTOMATIS
            // ==========================================
            $stmt_pel = $pdo->prepare("SELECT nama, no_hp FROM pelanggan WHERE id = ?");
            $stmt_pel->execute([$id_pelanggan]);
            $data_pel = $stmt_pel->fetch();

            if ($data_pel && !empty($data_pel['no_hp'])) {
                // Baca format pesan dari website_settings.json
                $settings_file = __DIR__ . '/../website_settings.json';
                $format_pesan = "Halo {nama},\n\nTagihan air bulan {bulan} {tahun}:\n- Pemakaian air: {pemakaian} m³\n- Abonemen: {abonemen}\nTotal yang harus dibayar: {total}\n\nSegera bayar sebelum tgl 10 bulan berikutnya untuk menghindari denda.\nKunjungi spam.desagemuruh.id untuk informasi tagihan, riwayat pemakaian dan pembayaran, serta laporan keuangan.\n\nTerima kasih,\nSPAM Tirtha Kedawung Desa Gemuruh";
                
                if (file_exists($settings_file)) {
                    $raw = @file_get_contents($settings_file);
                    $decoded = json_decode($raw, true);
                    if (isset($decoded['format_pesan_tagihan'])) {
                        $format_pesan = $decoded['format_pesan_tagihan'];
                    }
                }

                $nama_bulan_arr = ['','Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
                $nama_bulan_teks = $nama_bulan_arr[$bulan_ini] ?? $bulan_ini;

                // Ganti variabel di format pesan (TAMBAHAN: {abonemen})
                $pesan = str_replace(
                    ['{nama}', '{bulan}', '{tahun}', '{pemakaian}', '{abonemen}', '{total}'],
                    [
                        $data_pel['nama'], 
                        $nama_bulan_teks, 
                        $tahun_ini, 
                        number_format($pemakaian, 3), 
                        format_rupiah($biaya_abonemen),
                        format_rupiah($total_tagihan)
                    ],
                    $format_pesan
                );

                // Kirim via Fonnte
                kirim_wa_fonnte($data_pel['no_hp'], $pesan);
                $success_msg .= " Notifikasi WhatsApp sedang dikirim ke pelanggan.";
            }

        } catch (Exception $e) {
            $pdo->rollBack();
            $error_msg = "Gagal menyimpan data: " . $e->getMessage();
        }
    }
}

// Ambil Data Pelanggan & Status Pencatatan Bulan Ini
$query = "
    SELECT p.*, 
    m.id AS id_meteran_bulan_ini, 
    m.meter_akhir AS meter_terakhir,
    m.pemakaian AS pemakaian_bulan_ini,
    t.status AS status_tagihan,
    t.total AS total_tagihan
    FROM pelanggan p
    LEFT JOIN meteran m ON p.id = m.id_pelanggan AND m.bulan = ? AND m.tahun = ?
    LEFT JOIN tagihan t ON p.id = t.id_pelanggan AND t.bulan = ? AND t.tahun = ?
    WHERE p.status = 'aktif'
    ORDER BY p.nama ASC
";
$stmt = $pdo->prepare($query);
$stmt->execute([$bulan_ini, $tahun_ini, $bulan_ini, $tahun_ini]);
$pelanggans = $stmt->fetchAll(PDO::FETCH_ASSOC);

$jumlah_semua = count($pelanggans);
$jumlah_sudah = 0;
$jumlah_belum = 0;

foreach ($pelanggans as &$p) {
    if ($p['id_meteran_bulan_ini']) {
        $p['sudah_catat'] = true;
        $jumlah_sudah++;
    } else {
        $p['sudah_catat'] = false;
        $jumlah_belum++;
    }
}
unset($p);
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Catat Meteran - SPAM</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>
body { background:#f8f9fa; font-family:'Segoe UI'; }
.bg-header{
    background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%);
    color:white;
    padding:18px;
    border-bottom-left-radius:20px;
    border-bottom-right-radius:20px;
}
.card-pelanggan{
    border:none;
    border-radius:15px;
    box-shadow:0 2px 10px rgba(0,0,0,0.05);
    margin-bottom:12px;
    position:relative;
}
.btn-catat{
    border-radius:20px;
    border:1px solid #3A7CA5;
    color:#3A7CA5;
    font-size:13px;
    padding:5px 15px;
    text-decoration:none;
    background: white;
}
.search-sticky{
    position:sticky;
    top:0;
    background:#f8f9fa;
    z-index:100;
    padding-bottom:10px;
}
.search-wa{
    background:#f0f2f5;
    border-radius:25px;
    padding:10px 15px;
    display:flex;
    align-items:center;
}
.search-wa i{color:#667781;}
.search-wa input{
    border:none;
    background:transparent;
    width:100%;
    outline:none;
    font-size:15px;
    margin-left:8px;
}
.btn-scan{
    border:none;
    background:transparent;
    color:#3A7CA5;
    font-size:20px;
    margin-left:8px;
}
.filter-scroll{
    overflow-x:auto;
    overflow-y:hidden;
    -webkit-overflow-scrolling:touch;
    scrollbar-width:none;
    margin-top:10px;
    padding-bottom:2px;
}
.filter-scroll::-webkit-scrollbar{ display:none; }
.filter-bar{ display:flex; gap:8px; flex-wrap:nowrap; width:max-content; min-width:100%; }
.filter-btn{
    border:none;
    background:#e9edef;
    padding:6px 14px;
    border-radius:20px;
    font-size:13px;
    white-space:nowrap;
    flex:0 0 auto;
}
.filter-btn.active{ background:#3A7CA5; color:white; }
.badge-sudah{
    position:absolute;
    top:10px;
    right:12px;
    background:#2ECC71;
    color:white;
    font-size:11px;
    padding:4px 8px;
    border-radius:12px;
    font-weight:600;
}
.form-control-meter {
    font-size: 1.5rem;
    text-align: center;
    letter-spacing: 2px;
    font-weight: bold;
}
</style>
</head>
<body>

<div class="bg-header shadow-sm">
    <div class="container d-flex justify-content-between align-items-center">
        <a href="dashboard.php" class="text-white"><i class="fa fa-arrow-left"></i></a>
        <h5 class="mb-0 fw-bold">Catat Meteran</h5>
        <div style="width: 20px;"></div>
    </div>
</div>

<div class="container pb-5">
    <?php if ($success_msg): ?>
        <div class="alert alert-success alert-dismissible fade show mt-3" style="font-size:0.85rem; border-radius:10px;">
            <i class="fa fa-check-circle me-1"></i> <?= $success_msg ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    <?php if ($error_msg): ?>
        <div class="alert alert-danger alert-dismissible fade show mt-3" style="font-size:0.85rem; border-radius:10px;">
            <i class="fa fa-exclamation-circle me-1"></i> <?= $error_msg ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="search-sticky">
        <div class="search-wa">
            <i class="fa fa-search"></i>
            <input type="text" id="smartSearch" placeholder="Cari nama atau ID meteran..." autocomplete="off">
            <button class="btn-scan" onclick="openScanner()" title="Scan Barcode Meteran">
                <i class="fa fa-qrcode"></i>
            </button>
        </div>
        <div class="filter-scroll">
            <div class="filter-bar">
                <button class="filter-btn active" data-filter="semua">Semua (<?= $jumlah_semua ?>)</button>
                <button class="filter-btn" data-filter="belum">Belum Dicatat (<?= $jumlah_belum ?>)</button>
                <button class="filter-btn" data-filter="sudah">Sudah Dicatat (<?= $jumlah_sudah ?>)</button>
            </div>
        </div>
    </div>

    <div class="row mt-3" id="hasilPelanggan">
        <?php foreach($pelanggans as $p): ?>
        <div class="col-12 pelanggan-item"
             data-nama="<?= strtolower(htmlspecialchars($p['nama'], ENT_QUOTES)) ?>"
             data-meteran="<?= strtolower(htmlspecialchars($p['id_meteran'], ENT_QUOTES)) ?>"
             data-status="<?= $p['sudah_catat'] ? 'sudah' : 'belum' ?>">
            
            <div class="card card-pelanggan">
                <div class="card-body">
                    <?php if($p['sudah_catat']): ?>
                        <div class="badge-sudah">SUDAH DICATAT</div>
                    <?php endif; ?>
                    
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="fw-bold mb-1"><?= strtoupper(htmlspecialchars($p['nama'])) ?></h6>
                            <small class="text-muted d-block mb-1">
                                <i class="fa fa-droplet text-primary"></i> <?= htmlspecialchars($p['id_meteran']) ?> 
                                | <i class="fa fa-phone text-success"></i> <?= htmlspecialchars($p['no_hp'] ?: '-') ?>
                            </small>
                            <div class="small text-secondary">
                                <i class="fa fa-location-dot text-danger"></i> <?= htmlspecialchars($p['alamat']) ?>
                            </div>
                            <?php if($p['sudah_catat']): ?>
                                <div class="mt-2 small text-success fw-bold">
                                    <i class="fa fa-gauge-high"></i> Pemakaian: <?= number_format($p['pemakaian_bulan_ini'], 3) ?> m³
                                    <br>Tagihan: <?= format_rupiah($p['total_tagihan'] ?? 0) ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="d-flex justify-content-end mt-2">
                        <button class="btn-catat" 
                                onclick="openModalCatat(<?= $p['id'] ?>, '<?= addslashes($p['nama']) ?>', '<?= $p['id_meteran'] ?>', <?= $p['meter_terakhir'] ?? 0 ?>)">
                            <i class="fa fa-pen-to-square me-1"></i> Catat Meteran
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Modal Input Meteran -->
<div class="modal fade" id="modalCatat" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0" style="border-radius:20px;">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold">Input Angka Meteran</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="POST">
                    <input type="hidden" name="simpan_meteran" value="1">
                    <input type="hidden" name="id_pelanggan" id="modal_id_pelanggan">
                    
                    <div class="text-center mb-3">
                        <div class="fw-bold" id="modal_nama_pelanggan"></div>
                        <div class="text-muted small" id="modal_id_meteran"></div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small text-muted">Meteran Awal (Otomatis)</label>
                        <input type="text" class="form-control form-control-meter bg-light" id="modal_meter_awal" name="meter_awal" readonly>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small text-muted fw-bold">Meteran Akhir (Format: 0000,000)</label>
                        <input type="text" class="form-control form-control-meter" id="modal_meter_akhir" name="meter_akhir" 
                               placeholder="0000,000" required maxlength="8" inputmode="decimal">
                        <div class="form-text text-center">4 digit kubikasi, 3 digit desimal</div>
                    </div>

                    <div class="d-grid">
                        <button type="submit" class="btn btn-sage py-2 fw-bold" style="background:#3A7CA5; color:white; border-radius:12px;">
                            <i class="fa fa-save me-2"></i> Simpan & Hitung Tagihan
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Modal Scanner -->
<div class="modal fade" id="scanModal">
    <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"></div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
const inputMeterAkhir = document.getElementById('modal_meter_akhir');
inputMeterAkhir.addEventListener('input', function (e) {
    let val = e.target.value.replace(/[^0-9]/g, '');
    if (val.length > 7) val = val.substring(0, 7);
    let formatted = '';
    if (val.length <= 4) { formatted = val; } 
    else { formatted = val.substring(0, 4) + ',' + val.substring(4); }
    e.target.value = formatted;
});
inputMeterAkhir.addEventListener('blur', function (e) {
    let val = e.target.value.replace(/[^0-9]/g, '');
    if (val.length > 7) val = val.substring(0, 7);
    let pad = val.padStart(7, '0');
    e.target.value = pad.substring(0, 4) + ',' + pad.substring(4, 7);
});

function openModalCatat(id, nama, meteran, meter_terakhir) {
    document.getElementById('modal_id_pelanggan').value = id;
    document.getElementById('modal_nama_pelanggan').innerText = nama;
    document.getElementById('modal_id_meteran').innerText = 'ID: ' + meteran;
    let mt = parseFloat(meter_terakhir).toFixed(3).replace('.', ',');
    document.getElementById('modal_meter_awal').value = mt;
    document.getElementById('modal_meter_akhir').value = '';
    new bootstrap.Modal(document.getElementById('modalCatat')).show();
    setTimeout(() => { document.getElementById('modal_meter_akhir').focus(); }, 500);
}

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();
                document.getElementById('smartSearch').value = decodedText;
                document.getElementById('smartSearch').dispatchEvent(new Event("keyup"));
                setTimeout(() => {
                    let visibleItems = document.querySelectorAll('.pelanggan-item[style*="block"]');
                    if (visibleItems.length === 1) {
                        let btn = visibleItems[0].querySelector('.btn-catat');
                        if (btn) btn.click();
                    }
                }, 300);
            });
        }
    );
}

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

const search = document.getElementById("smartSearch");
const items = document.querySelectorAll(".pelanggan-item");
let filter = "semua";

document.querySelectorAll(".filter-btn").forEach(btn => {
    btn.onclick = function() {
        document.querySelectorAll(".filter-btn").forEach(b => b.classList.remove("active"));
        this.classList.add("active");
        filter = this.dataset.filter;
        filterData();
    };
});

search.addEventListener("keyup", filterData);

function filterData() {
    let keyword = search.value.toLowerCase();
    items.forEach(el => {
        let nama = el.dataset.nama;
        let meteran = el.dataset.meteran;
        let status = el.dataset.status;
        let cocok = nama.includes(keyword) || meteran.includes(keyword);
        let cocokFilter = (filter == "semua") || (filter == status);
        el.style.display = (cocok && cocokFilter) ? "block" : "none";
    });
}
</script>
</body>
</html>