<?php
/*
 * Billing Payment Instructions - Payment instructions page for customer portal
 */

session_start();

date_default_timezone_set('Asia/Jakarta');

require_once(__DIR__ . '/../include/db_config.php');
require_once(__DIR__ . '/../lib/BillingService.class.php');
require_once(__DIR__ . '/../lib/ActivityNotifier.class.php');

if (!isset($_SESSION['billing_portal_customer_id']) || (int)$_SESSION['billing_portal_customer_id'] <= 0) {
    header('Location: billing_login.php');
    exit;
}

// Check if we have payment info
if (!isset($_SESSION['billing_payment_info'])) {
    header('Location: billing_portal.php');
    exit;
}

$payment_info = $_SESSION['billing_payment_info'];
$activeCustomerId = (int)$_SESSION['billing_portal_customer_id'];

try {
    $billingService = new BillingService();
    $customer = $billingService->getCustomerById($activeCustomerId);
    
    if (!$customer) {
        unset($_SESSION['billing_payment_info']);
        $_SESSION['billing_portal_flash_error'] = 'Data pelanggan tidak ditemukan.';
        header('Location: billing_portal.php');
        exit;
    }
    
    $invoice = $billingService->getInvoiceById((int)$payment_info['invoice_id']);
    if (!$invoice || (int)$invoice['customer_id'] !== $activeCustomerId) {
        unset($_SESSION['billing_payment_info']);
        $_SESSION['billing_portal_flash_error'] = 'Data invoice tidak valid.';
        header('Location: billing_portal.php');
        exit;
    }
    
    $profile = $billingService->getProfileById((int)$customer['profile_id']);

    $db = getDBConnection();
    
    // Determine owner prefix for payment settings
    $ownerId = (int)($customer['owner_id'] ?? 0);
    $prefix = ($ownerId > 1) ? "owner_{$ownerId}_" : "";
    $pattern = $prefix . 'payment_%';
    
    $agentSettingsStmt = $db->prepare("SELECT setting_key, setting_value FROM agent_settings WHERE setting_key LIKE :pattern");
    $agentSettingsStmt->execute([':pattern' => $pattern]);
    
    $agentPaymentSettings = [];
    if ($agentSettingsStmt) {
        while ($row = $agentSettingsStmt->fetch(PDO::FETCH_ASSOC)) {
            $key = $row['setting_key'];
            // Remove prefix if present so downstream code uses standard keys
            if ($prefix !== '' && strpos($key, $prefix) === 0) {
                $key = substr($key, strlen($prefix));
            }
            $agentPaymentSettings[$key] = $row['setting_value'];
        }
    }

    $banks = [];
    $banksSettingRaw = (string)($agentPaymentSettings['payment_bank_accounts'] ?? '');
    if ($banksSettingRaw !== '') {
        $decoded = json_decode($banksSettingRaw, true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
            $banks = $decoded;
        }
    }
    if (empty($banks)) {
        $legacyName = (string)($agentPaymentSettings['payment_bank_name'] ?? '');
        $legacyNumber = (string)($agentPaymentSettings['payment_account_number'] ?? '');
        $legacyOwner = (string)($agentPaymentSettings['payment_account_name'] ?? '');
        if ($legacyName !== '' || $legacyNumber !== '' || $legacyOwner !== '') {
            $banks[] = [
                'bank_name' => $legacyName,
                'account_number' => $legacyNumber,
                'account_name' => $legacyOwner,
            ];
        }
    }

    $ewallets = [];
    $ewalletSettingRaw = (string)($agentPaymentSettings['payment_ewallet_accounts'] ?? '');
    if ($ewalletSettingRaw !== '') {
        $decoded = json_decode($ewalletSettingRaw, true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
            $ewallets = $decoded;
        }
    }
    
} catch (Throwable $e) {
    $_SESSION['billing_portal_flash_error'] = 'Terjadi kesalahan: ' . htmlspecialchars($e->getMessage());
    header('Location: billing_portal.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_manual_paid'])) {
    $confirmKey = 'billing_manual_confirmed_' . (int)($payment_info['invoice_id'] ?? 0);

    if (!isset($_SESSION[$confirmKey])) {
        try {
            $notifier = new ActivityNotifier();
            $notifier->notify(
                'billing_manual_payment_confirm',
                'Konfirmasi pembayaran dari portal pelanggan',
                [
                    'Customer' => (string)($customer['name'] ?? ''),
                    'Nomor layanan' => (string)($customer['service_number'] ?? ''),
                    'Metode' => (string)($payment_info['method_name'] ?? ''),
                    'Kode metode' => (string)($payment_info['method_code'] ?? ''),
                    'Nomor referensi' => (string)($payment_info['payment_reference'] ?? ''),
                    'Total bayar' => 'Rp ' . number_format((float)($payment_info['total_amount'] ?? 0), 0, ',', '.'),
                    'Instruksi' => 'Mohon cek mutasi pada ' . (string)($payment_info['method_name'] ?? 'rekening terkait') . ' sebelum konfirmasi.',
                ],
                [
                    'Sumber' => 'public/billing_payment_instructions.php',
                    'Via' => 'Portal Pelanggan',
                ],
                [
                    'invoice_id' => (int)($payment_info['invoice_id'] ?? 0),
                    'customer_id' => (int)($customer['id'] ?? 0),
                ]
            );
        } catch (Throwable $e) {
        }

        $_SESSION[$confirmKey] = 1;
    }

    header('Location: billing_payment_status.php');
    exit;
}

$theme = 'default';
$themecolor = '#3a4149';
if (file_exists(__DIR__ . '/../include/theme.php')) {
    include(__DIR__ . '/../include/theme.php');
}
$themeAsset = ($theme === 'darkgreen') ? 'dark' : $theme;
$methodCode = (string)($payment_info['method_code'] ?? '');
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Instruksi Pembayaran - <?= htmlspecialchars($customer['name']); ?></title>
    <meta name="theme-color" content="<?= $themecolor; ?>" />
    <link rel="stylesheet" type="text/css" href="../css/font-awesome/css/font-awesome.min.css" />
    <link rel="stylesheet" href="../css/mikrobil-ui.<?= $themeAsset; ?>.min.css">
    <link rel="stylesheet" href="../css/theme-darkgreen.css">
    <link rel="icon" href="../img/favicon.svg" type="image/svg+xml" sizes="any" />
    <link rel="icon" href="../img/favicon.png" type="image/png" sizes="32x32" />
    <link rel="apple-touch-icon" href="../img/favicon.png" />
    <style>
        :root {
            --dg-text: #f8fafc;
            --dg-muted: #94a3b8;
            --dg-panel: rgba(15, 23, 42, 0.78);
            --dg-panel-strong: rgba(15, 23, 42, 0.92);
            --dg-border: rgba(148, 163, 184, 0.18);
            --dg-border-strong: rgba(148, 163, 184, 0.28);
            --dg-accent: #93c5fd;
            --dg-accent-2: #1e293b;
            --dg-accent-3: #334155;
            --dg-col-bg: rgba(51, 65, 85, 0.35);
            --primary-color: #334155;
            --primary-dark: rgba(51, 65, 85, 0.85);
            --info-color: #334155;
            --bg-color: radial-gradient(1100px 650px at 18% 8%, rgba(51, 65, 85, 0.18), transparent 60%), radial-gradient(900px 500px at 88% 12%, rgba(30, 41, 59, 0.14), transparent 60%), linear-gradient(135deg, #050816, #0f172a 35%, #111827);
        }
        body { 
            background: var(--bg-color); 
            font-family: 'Source Sans Pro', Arial, sans-serif; 
            color: var(--dg-text);
        }
        .wrapper { 
            max-width: 940px; 
            margin: 0 auto; 
            padding: 20px; 
        }
        .card { 
            background: var(--dg-panel); 
            border-radius: 14px; 
            box-shadow: var(--dg-shadow); 
            border: 1px solid var(--dg-border);
            margin-bottom: 20px; 
        }
        .card-header { 
            padding: 16px 20px; 
            border-bottom: 1px solid var(--dg-border); 
            display:flex; 
            flex-wrap:wrap; 
            align-items:center; 
            justify-content:space-between; 
            gap:10px; 
        }
        .card-header .header-info { 
            flex:1 1 auto; 
        }
        .card-body { 
            padding: 20px; 
        }
        .summary-grid { 
            display: grid; 
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); 
            gap: 15px; 
            margin-bottom: 20px; 
        }
        .box { 
            border-radius: 4px; 
            padding: 18px; 
            color: #fff; 
            min-height: 110px; 
        }
        .box h2 { 
            margin: 0 0 6px; 
            font-size: 26px; 
        }
        .alert {
            padding: 12px 16px;
            border-radius: 10px;
            margin-bottom: 18px;
            border: 1px solid var(--dg-border);
            background: var(--dg-panel);
            line-height: 1.55;
            position: relative;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            max-width: min(100%, 560px);
            box-sizing: border-box;
            flex-wrap: wrap;
        }
        .alert::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 4px;
            border-radius: 10px 0 0 10px;
        }
        .alert-info {
            color: var(--dg-text);
        }
        .alert-info::before {
            background: var(--info-color);
        }
        .alert-warning {
            color: #92400e;
        }
        .alert-warning::before {
            background: #d97706;
        }
        .alert-success {
            color: #166534;
        }
        .alert-success::before {
            background: #22c55e;
        }
        .payment-instructions {
            background: var(--dg-panel);
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: var(--dg-shadow);
            border: 1px solid var(--dg-border);
        }
        
        .payment-detail {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid var(--dg-border);
        }
        
        .payment-detail:last-child {
            border-bottom: none;
        }
        
        .payment-detail .label {
            font-weight: 600;
            color: var(--dg-text);
        }
        
        .payment-detail .value {
            text-align: right;
            color: var(--dg-muted);
        }
        
        .qr-code {
            text-align: center;
            margin: 20px 0;
        }
        
        .qr-code img {
            max-width: 200px;
            height: auto;
        }
        
        .virtual-account {
            text-align: center;
            font-size: 24px;
            font-weight: bold;
            margin: 20px 0;
            padding: 15px;
            background: var(--dg-panel-strong);
            border-radius: 8px;
            border: 2px dashed var(--primary-color);
        }
        
        .back-link {
            display: inline-block;
            margin-bottom: 20px;
            color: var(--dg-accent);
            text-decoration: none;
        }
        
        .back-link:hover {
            text-decoration: underline;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--dg-accent-2) 0%, var(--dg-accent-3) 100%);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            margin-top: 10px;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, #334155 0%, #475569 100%);
        }
    </style>
</head>
<body>
<div class="wrapper">
    <a href="billing_portal.php" class="back-link">
        <i class="fa fa-arrow-left"></i> Kembali ke Portal
    </a>
    
    <div class="card">
        <div class="card-header">
            <div class="header-info">
                <h2><i class="fa fa-info-circle"></i> Instruksi Pembayaran</h2>
                <p style="margin:0; color:var(--dg-muted);">Pelanggan: <?= htmlspecialchars($customer['name']); ?></p>
                <p style="margin:0; color:var(--dg-muted); font-size:13px;">Nomor layanan: <?= htmlspecialchars($customer['service_number']); ?></p>
            </div>
        </div>
        <div class="card-body">
            <div class="summary-grid">
                <div class="box" style="background:linear-gradient(135deg, #1e293b 0%, #334155 100%);">
                    <h2><?= htmlspecialchars($profile['profile_name'] ?? 'Tidak diketahui'); ?></h2>
                    <p style="margin:0;">Harga: Rp <?= number_format($profile['price_monthly'] ?? 0, 0, ',', '.'); ?>/bulan</p>
                </div>
                <div class="box" style="background:#00a65a;">
                    <h2>Rp <?= number_format($payment_info['amount'], 0, ',', '.'); ?></h2>
                    <p style="margin:0;">Jumlah Tagihan</p>
                </div>
                <div class="box" style="background:#f39c12;">
                    <h2>Rp <?= number_format($payment_info['admin_fee'], 0, ',', '.'); ?></h2>
                    <p style="margin:0;">Biaya Admin</p>
                </div>
                <div class="box" style="background:#dd4b39;">
                    <h2>Rp <?= number_format($payment_info['total_amount'], 0, ',', '.'); ?></h2>
                    <p style="margin:0;">Total Bayar</p>
                </div>
            </div>
            
            <div class="alert alert-info">
                <strong>Informasi:</strong> Silakan ikuti instruksi di bawah ini untuk menyelesaikan pembayaran tagihan Anda.
            </div>
        </div>
    </div>
    
    <div class="payment-instructions">
        <h3><i class="fa fa-credit-card"></i> Detail Pembayaran</h3>
        
        <div class="payment-detail">
            <span class="label">Metode Pembayaran:</span>
            <span class="value"><?= htmlspecialchars($payment_info['method_name']); ?></span>
        </div>
        
        <div class="payment-detail">
            <span class="label">Nomor Referensi:</span>
            <span class="value"><?= htmlspecialchars($payment_info['payment_reference']); ?></span>
        </div>
        
        <div class="payment-detail">
            <span class="label">Tanggal Kadaluarsa:</span>
            <span class="value"><?= htmlspecialchars(date('d M Y H:i', strtotime($payment_info['expired_at']))); ?></span>
        </div>

        <?php if ($methodCode === 'bank_transfer'): ?>
            <?php $waConfirm = (string)($agentPaymentSettings['payment_wa_confirm'] ?? ''); ?>
            <div class="alert alert-info" style="margin-top: 14px;">
                <strong>Transfer Manual:</strong>
                Transfer sesuai total bayar, lalu kirim bukti transfer + nomor referensi ke admin.
            </div>
            <?php if (!empty($banks)): ?>
                <?php foreach ($banks as $bank): ?>
                    <?php
                    $bankName = trim((string)($bank['bank_name'] ?? ''));
                    $accountNumber = trim((string)($bank['account_number'] ?? ''));
                    $accountName = trim((string)($bank['account_name'] ?? ''));
                    $label = 'Rekening Transfer';
                    if ($bankName !== '') {
                        $label .= ' (' . $bankName . ')';
                    }
                    $value = $accountNumber !== '' ? $accountNumber : '-';
                    if ($accountName !== '') {
                        $value .= ' (a.n. ' . $accountName . ')';
                    }
                    ?>
                    <div class="payment-detail">
                        <span class="label"><?= htmlspecialchars($label); ?>:</span>
                        <span class="value"><?= htmlspecialchars($value); ?></span>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="payment-detail">
                    <span class="label">Rekening Transfer:</span>
                    <span class="value">-</span>
                </div>
            <?php endif; ?>
            <?php if ($waConfirm !== ''): ?>
                <div class="payment-detail">
                    <span class="label">Konfirmasi WA:</span>
                    <span class="value"><?= htmlspecialchars($waConfirm); ?></span>
                </div>
            <?php endif; ?>
        <?php elseif ($methodCode === 'manual_ewallet'): ?>
            <?php $waConfirm = (string)($agentPaymentSettings['payment_wa_confirm'] ?? ''); ?>
            <div class="alert alert-info" style="margin-top: 14px;">
                <strong>E-Wallet Manual:</strong>
                Transfer sesuai total bayar.
                <br><br>
                <strong>PENTING:</strong> Cantumkan <u>Nomor Referensi</u> di dalam Berita/Catatan Transfer untuk memudahkan pengecekan.
                <br>
                Setelah itu, kirim bukti transfer ke admin.
            </div>
            <?php if (!empty($ewallets)): ?>
                <?php foreach ($ewallets as $ewallet): ?>
                    <?php
                    $provider = trim((string)($ewallet['provider'] ?? ''));
                    $accountNumber = trim((string)($ewallet['account_number'] ?? ''));
                    $accountName = trim((string)($ewallet['account_name'] ?? ''));
                    $label = 'E-Wallet';
                    if ($provider !== '') {
                        $label .= ' (' . $provider . ')';
                    }
                    $value = $accountNumber !== '' ? $accountNumber : '-';
                    if ($accountName !== '') {
                        $value .= ' (a.n. ' . $accountName . ')';
                    }
                    ?>
                    <div class="payment-detail">
                        <span class="label"><?= htmlspecialchars($label); ?>:</span>
                        <span class="value"><?= htmlspecialchars($value); ?></span>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="payment-detail">
                    <span class="label">E-Wallet:</span>
                    <span class="value">-</span>
                </div>
            <?php endif; ?>
            <?php if ($waConfirm !== ''): ?>
                <div class="payment-detail">
                    <span class="label">Konfirmasi WA:</span>
                    <span class="value"><?= htmlspecialchars($waConfirm); ?></span>
                </div>
            <?php endif; ?>
        <?php elseif ($methodCode === 'cash'): ?>
            <?php $waConfirm = (string)($agentPaymentSettings['payment_wa_confirm'] ?? ''); ?>
            <div class="alert alert-info" style="margin-top: 14px;">
                <strong>Pembayaran Tunai:</strong>
                Silakan lakukan pembayaran tunai ke admin/teknisi. Sertakan nomor referensi saat konfirmasi.
            </div>
            <?php if ($waConfirm !== ''): ?>
                <div class="payment-detail">
                    <span class="label">Konfirmasi WA:</span>
                    <span class="value"><?= htmlspecialchars($waConfirm); ?></span>
                </div>
            <?php endif; ?>
        <?php endif; ?>
        
        <?php if (!empty($payment_info['qr_url'])): ?>
        <div class="qr-code">
            <p><strong>Scan QR Code di bawah ini:</strong></p>
            <img src="<?= htmlspecialchars($payment_info['qr_url']); ?>" alt="QR Code Pembayaran">
        </div>
        <?php endif; ?>
        
        <?php if (!empty($payment_info['virtual_account'])): ?>
        <div class="virtual-account">
            <?= htmlspecialchars($payment_info['virtual_account']); ?>
        </div>
        <p style="text-align: center; color: var(--dg-muted);">
            Gunakan nomor virtual account di atas untuk melakukan pembayaran melalui ATM, Mobile Banking, atau Internet Banking.
        </p>
        <?php endif; ?>
        
        <div style="text-align: center; margin-top: 30px;">
            <form method="post" style="display:inline;" onsubmit="return confirmPayment(this);">
                <input type="hidden" name="confirm_manual_paid" value="1">
                <button type="submit" class="btn-primary" id="btn-confirm">
                    <i class="fa fa-check"></i> Saya Sudah Bayar
                </button>
            </form>
        </div>
    </div>
</div>

<script>
(function(){
    if (!window.showAlert || !window.showConfirm) {
        var dialogEl = null;
        function ensureDialog() {
            if (dialogEl) return dialogEl;
            dialogEl = document.createElement('div');
            dialogEl.id = 'appDialog';
            dialogEl.style.cssText = 'display:none; position:fixed; inset:0; background:rgba(0,0,0,0.5); z-index:1100;';
            var panel = document.createElement('div');
            panel.style.cssText = 'background:var(--dg-panel-strong,#ffffff); color:var(--dg-text,#0f172a); width:86%; max-width:520px; margin:60px auto; padding:20px; border-radius:14px; box-shadow:0 10px 30px rgba(0,0,0,0.25);';
            var titleEl = document.createElement('h3');
            titleEl.id = 'appDialogTitle';
            titleEl.style.margin = '0 0 12px';
            var msgEl = document.createElement('div');
            msgEl.id = 'appDialogMessage';
            msgEl.style.marginBottom = '16px';
            var actions = document.createElement('div');
            actions.style.cssText = 'display:flex; gap:10px; justify-content:flex-end;';
            var okBtn = document.createElement('button');
            okBtn.id = 'appDialogOk';
            okBtn.className = 'btn btn-primary';
            okBtn.textContent = 'Oke';
            var cancelBtn = document.createElement('button');
            cancelBtn.id = 'appDialogCancel';
            cancelBtn.className = 'btn btn-secondary';
            cancelBtn.textContent = 'Batal';
            actions.appendChild(cancelBtn);
            actions.appendChild(okBtn);
            panel.appendChild(titleEl);
            panel.appendChild(msgEl);
            panel.appendChild(actions);
            dialogEl.appendChild(panel);
            document.body.appendChild(dialogEl);
            return dialogEl;
        }
        function openDialog(title, message, mode, resolve) {
            var el = ensureDialog();
            var t = document.getElementById('appDialogTitle');
            var m = document.getElementById('appDialogMessage');
            var ok = document.getElementById('appDialogOk');
            var cancel = document.getElementById('appDialogCancel');
            t.textContent = title || (mode === 'confirm' ? 'Konfirmasi' : 'Informasi');
            m.textContent = message || '';
            cancel.style.display = mode === 'confirm' ? '' : 'none';
            el.style.display = 'block';
            el.style.opacity = '1';
            function cleanup() {
                el.style.opacity = '0';
                setTimeout(function(){ el.style.display = 'none'; }, 200);
                ok.onclick = null;
                cancel.onclick = null;
            }
            ok.onclick = function(){ cleanup(); resolve(true); };
            cancel.onclick = function(){ cleanup(); resolve(false); };
            el.addEventListener('click', function(e){
                if (e.target === el && mode !== 'alert') { cleanup(); resolve(false); }
            }, { once: true });
        }
        window.showAlert = function(message, title){
            return new Promise(function(res){ openDialog(title || 'Informasi', message, 'alert', res); });
        };
        window.showConfirm = function(message, title){
            return new Promise(function(res){ openDialog(title || 'Konfirmasi', message, 'confirm', res); });
        };
    }
})();
function confirmPayment(form) {
    var msg = 'Apakah Anda yakin sudah melakukan pembayaran? Admin akan melakukan pengecekan mutasi rekening.';
    showConfirm(msg, 'Konfirmasi').then(function(yes){
        if (!yes) return;
        var btn = document.getElementById('btn-confirm');
        btn.disabled = true;
        btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Memproses...';
        form.submit();
    });
    return false;
}
</script>

</body>
</html>
