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

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

// 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;
}

// Handle Pembayaran
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bayar_id'])) {
    $id_tagihan = (int)$_POST['bayar_id'];
    $kirim_wa = isset($_POST['kirim_wa']) ? 1 : 0;
    
    try {
        $pdo->beginTransaction();
        
        // 1. Ambil data tagihan & pelanggan
        $stmt = $pdo->prepare("
            SELECT t.*, p.nama, p.no_hp, p.id_meteran 
            FROM tagihan t 
            JOIN pelanggan p ON t.id_pelanggan = p.id 
            WHERE t.id = ? AND t.status = 'belum_lunas'
        ");
        $stmt->execute([$id_tagihan]);
        $data = $stmt->fetch();
        
        if ($data) {
            // 2. Update status tagihan
            $pdo->prepare("UPDATE tagihan SET status = 'lunas', tgl_bayar = CURDATE() WHERE id = ?")->execute([$id_tagihan]);
            
            // 3. Catat ke Buku Kas
            $ket = "Pembayaran air {$data['nama']} ({$data['id_meteran']}) - Bulan " . date('F Y', mktime(0,0,0,$data['bulan'],1,$data['tahun']));
            $pdo->prepare("INSERT INTO buku_kas (tanggal, jenis, kategori, nominal, keterangan, id_user) VALUES (CURDATE(), 'masuk', 'Pembayaran Air', ?, ?, ?)")
                ->execute([$data['total'], $ket, $id_petugas]);
            
            // 4. Kirim WhatsApp jika dicentang
            if ($kirim_wa && !empty($data['no_hp'])) {
                // Baca format pesan dari website_settings.json
                $settings_file = __DIR__ . '/../website_settings.json';
                $format_pesan = "Halo {nama},\n\nPembayaran tagihan air bulan {bulan} {tahun} sebesar {total} telah kami terima dan catat dalam sistem.\n\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_lunas'])) {
                        $format_pesan = $decoded['format_pesan_lunas'];
                    }
                }

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

                // Ganti variabel di format pesan
                $pesan = str_replace(
                    ['{nama}', '{bulan}', '{tahun}', '{total}'],
                    [$data['nama'], $nama_bulan_teks, $data['tahun'], format_rupiah($data['total'])],
                    $format_pesan
                );

                kirim_wa_fonnte($data['no_hp'], $pesan);
            }
            
            $pdo->commit();
            $success_msg = "Pembayaran berhasil dicatat!" . ($kirim_wa ? " WhatsApp sedang dikirim." : "");
        } else {
            $pdo->rollBack();
            $error_msg = "Tagihan tidak ditemukan atau sudah lunas.";
        }
    } catch (Exception $e) {
        $pdo->rollBack();
        $error_msg = "Gagal memproses pembayaran: " . $e->getMessage();
    }
}

// Ambil Tagihan Belum Lunas Bulan Ini
$stmt = $pdo->prepare("
    SELECT t.id, t.total, t.bulan, t.tahun, p.nama, p.id_meteran, p.no_hp
    FROM tagihan t
    JOIN pelanggan p ON t.id_pelanggan = p.id
    WHERE t.bulan = ? AND t.tahun = ? AND t.status = 'belum_lunas'
    ORDER BY p.nama ASC
");
$stmt->execute([$bulan_ini, $tahun_ini]);
$tagihan_belum_lunas = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Terima Pembayaran - 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">
<style>
body { background:#f4f7fe; 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-tagihan{
    border:none;
    border-radius:15px;
    box-shadow:0 2px 10px rgba(0,0,0,0.05);
    margin-bottom:12px;
    background: white;
}
.btn-bayar{
    border-radius:20px;
    border:none;
    background:#2ECC71;
    color:white;
    font-size:13px;
    padding:6px 18px;
    font-weight: 600;
}
.empty-state { text-align: center; padding: 40px 20px; color: #7a8190; }
.form-check-input:checked { background-color: #3A7CA5; border-color: #3A7CA5; }
</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">Terima Pembayaran</h5>
        <div style="width: 20px;"></div>
    </div>
</div>

<div class="container pb-5 mt-3">
    <?php if ($success_msg): ?>
        <div class="alert alert-success alert-dismissible fade show" 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" 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="d-flex justify-content-between align-items-center mb-3 px-1">
        <h6 class="fw-bold mb-0 text-muted">Tagihan Belum Lunas (<?= count($tagihan_belum_lunas) ?>)</h6>
        <span class="badge bg-danger rounded-pill">Bulan <?= date('F', mktime(0,0,0,$bulan_ini,1)) ?></span>
    </div>

    <?php if (empty($tagihan_belum_lunas)): ?>
        <div class="card-tagihan empty-state">
            <i class="fa fa-check-circle fa-3x text-success mb-3"></i>
            <h5 class="fw-bold">Semua Lunas!</h5>
            <p class="small">Tidak ada tagihan yang belum dibayar untuk bulan ini.</p>
        </div>
    <?php else: ?>
        <?php foreach($tagihan_belum_lunas as $t): ?>
        <div class="card card-tagihan">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div>
                        <h6 class="fw-bold mb-1"><?= strtoupper(htmlspecialchars($t['nama'])) ?></h6>
                        <small class="text-muted"><i class="fa fa-droplet text-primary"></i> <?= htmlspecialchars($t['id_meteran']) ?></small>
                    </div>
                    <div class="text-end">
                        <div class="fw-bold text-danger" style="font-size:1.1rem;"><?= format_rupiah($t['total']) ?></div>
                        <small class="text-muted">Tagihan</small>
                    </div>
                </div>
                
                <div class="d-flex justify-content-between align-items-center mt-3 pt-2 border-top">
                    <small class="text-muted"><i class="fa fa-phone me-1"></i> <?= htmlspecialchars($t['no_hp'] ?: 'Tidak ada nomor') ?></small>
                    <button class="btn-bayar" onclick="openModalBayar(<?= $t['id'] ?>, '<?= addslashes($t['nama']) ?>', '<?= format_rupiah($t['total']) ?>', '<?= $t['no_hp'] ?>')">
                        <i class="fa fa-hand-holding-dollar me-1"></i> Terima Bayar
                    </button>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- Modal Konfirmasi Pembayaran -->
<div class="modal fade" id="modalBayar" 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">Konfirmasi Pembayaran</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="POST">
                    <input type="hidden" name="bayar_id" id="modal_id_tagihan">
                    
                    <div class="text-center mb-4">
                        <div class="text-muted small">Total Pembayaran</div>
                        <div class="fw-bold text-success" style="font-size:1.8rem;" id="modal_nominal"></div>
                        <div class="small text-muted mt-1" id="modal_nama"></div>
                    </div>

                    <div class="form-check mb-4">
                        <input class="form-check-input" type="checkbox" name="kirim_wa" id="kirimWa" checked value="1">
                        <label class="form-check-label small" for="kirimWa">
                            Kirim bukti pembayaran via WhatsApp <span class="text-muted">(Otomatis)</span>
                        </label>
                    </div>

                    <div class="d-grid">
                        <button type="submit" class="btn py-2 fw-bold text-white" style="background:#2ECC71; border-radius:12px;">
                            <i class="fa fa-check me-2"></i> Proses Pembayaran
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function openModalBayar(id, nama, nominal, no_hp) {
    document.getElementById('modal_id_tagihan').value = id;
    document.getElementById('modal_nama').innerText = nama;
    document.getElementById('modal_nominal').innerText = nominal;
    
    const chkWa = document.getElementById('kirimWa');
    if (!no_hp || no_hp === '') {
        chkWa.checked = false;
        chkWa.disabled = true;
    } else {
        chkWa.disabled = false;
    }

    new bootstrap.Modal(document.getElementById('modalBayar')).show();
}
</script>
</body>
</html>