<?php
/**
 * settings-payment.php — Tetapan QR & Akaun Bank
 * Akses: Admin sahaja
 * Guna layout.php untuk wrapper (sidebar/topbar).
 */
session_start();
require_once __DIR__ . '/db.php';

if (!isset($_SESSION['user']) || ($_SESSION['user']['role'] ?? '') !== 'admin') {
    header('Location: dashboard.php'); exit;
}

// CSRF
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function detect_mime($tmp){
    if (function_exists('finfo_open')) {
        $f = finfo_open(FILEINFO_MIME_TYPE);
        $m = finfo_file($f, $tmp);
        finfo_close($f);
        return $m;
    }
    return mime_content_type($tmp);
}

// Ambil rekod aktif terkini
$setting = [
    'id' => 0,
    'bank_name' => '',
    'account_number' => '',
    'account_name' => '',
    'note' => '',
    'qr_image_path' => ''
];
$res = $conn->query("SELECT * FROM payment_settings WHERE active=1 ORDER BY updated_at DESC, id DESC LIMIT 1");
if ($res && $res->num_rows) { $setting = $res->fetch_assoc(); }

// Proses POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (!hash_equals($csrf, $token)) {
        http_response_code(400);
        die('Invalid CSRF token.');
    }

    $bank_name    = trim($_POST['bank_name'] ?? '');
    $account_no   = trim($_POST['account_number'] ?? '');
    $account_name = trim($_POST['account_name'] ?? '');
    $note         = trim($_POST['note'] ?? '');
    $updated_by   = (int)($_SESSION['user']['id'] ?? 0);

    // QR handle
    $qr_path = $setting['qr_image_path'] ?? null;

    // Padam QR jika dipilih
    if (!empty($_POST['remove_qr']) && !empty($qr_path)) {
        $old = __DIR__ . '/' . ltrim($qr_path, '/');
        if (is_file($old)) { @unlink($old); }
        $qr_path = null;
    }

    // Muat naik QR baharu (optional)
    if (!empty($_FILES['qr_image']['name']) && is_uploaded_file($_FILES['qr_image']['tmp_name'])) {
        $f = $_FILES['qr_image'];
        $allowed = ['image/png','image/jpeg','image/jpg','image/webp'];
        $mime = detect_mime($f['tmp_name']);

        if (!in_array($mime, $allowed, true)) {
            die('Fail QR mesti imej PNG/JPG/WEBP.');
        }
        if ($f['size'] > 3 * 1024 * 1024) {
            die('Saiz imej QR melebihi 3MB.');
        }

        $dir = __DIR__ . '/assets/payments/qr/';
        if (!is_dir($dir)) { @mkdir($dir, 0775, true); }

        $extMap = ['image/png'=>'png','image/jpeg'=>'jpg','image/jpg'=>'jpg','image/webp'=>'webp'];
        $ext = $extMap[$mime] ?? (pathinfo($f['name'], PATHINFO_EXTENSION) ?: 'png');
        $fname = 'qr_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . strtolower($ext);

        if (!move_uploaded_file($f['tmp_name'], $dir . $fname)) {
            die('Gagal memuat naik imej QR.');
        }

        $qr_path = 'assets/payments/qr/' . $fname;

        // Jika ada QR lama & bukan kes remove_qr, buang
        if (!empty($setting['qr_image_path']) && empty($_POST['remove_qr'])) {
            $old = __DIR__ . '/' . ltrim($setting['qr_image_path'], '/');
            if (is_file($old)) { @unlink($old); }
        }
    }

    // Simpan DB (kekalkan satu rekod aktif)
    if (empty($setting['id'])) {
        $stmt = $conn->prepare("INSERT INTO payment_settings
            (bank_name, account_number, account_name, note, qr_image_path, active, updated_by)
            VALUES (?,?,?,?,?,1,?)");
        $stmt->bind_param('sssssi', $bank_name, $account_no, $account_name, $note, $qr_path, $updated_by);
        $ok = $stmt->execute();
        $stmt->close();
    } else {
        $stmt = $conn->prepare("UPDATE payment_settings
            SET bank_name=?, account_number=?, account_name=?, note=?, qr_image_path=?, updated_by=?, updated_at=NOW()
            WHERE id=?");
        $id = (int)$setting['id'];
        $stmt->bind_param('ssssssi', $bank_name, $account_no, $account_name, $note, $qr_path, $updated_by, $id);
        $ok = $stmt->execute();
        $stmt->close();
    }

    if ($ok) {
        header('Location: settings-payment.php?success=1'); exit;
    }
    die('Kemaskini gagal. Sila cuba lagi.');
}

$success = isset($_GET['success']);

// ---------- Page Content (inject ke layout) ----------
ob_start();
?>
<style>
/* ===== Scoped styles untuk halaman ini sahaja ===== */
.sp-wrap{max-width: 900px;margin: 0 auto;}
.sp-card{background:#fff;border:1px solid #e5e7eb;border-radius:14px;box-shadow:0 6px 18px rgba(0,0,0,.06);overflow:hidden}
.sp-head{padding:16px 18px;border-bottom:1px solid #eef1f5;background:#f9fafb}
.sp-head h3{margin:0;font-size:1.1rem}
.sp-head .sub{color:#667085;font-size:.92rem;margin-top:4px}
.sp-body{padding:18px}
.sp-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
@media (max-width: 700px){ .sp-grid{grid-template-columns:1fr} }
.sp-field label{font-weight:600;margin-bottom:6px;display:flex;justify-content:space-between;align-items:center}
.sp-field input[type=text], .sp-field input[type=file]{width:100%;padding:10px;border:1px solid #d0d5dd;border-radius:10px;background:#fff}
.sp-help{color:#6b7280;font-size:.85rem;margin-top:4px}
.hr{height:1px;background:#eef1f5;margin:18px 0}
.btn{display:inline-flex;align-items:center;gap:6px;border:1px solid #d0d5dd;background:#fff;border-radius:10px;padding:8px 12px;cursor:pointer}
.btn-primary{background:#0d6efd;border-color:#0d6efd;color:#fff}
.btn-ghost{background:#fff}
.btn:active{transform:translateY(1px)}
.btn-sm{padding:6px 10px;font-size:.9rem;border-radius:8px}
.row-2{display:grid;grid-template-columns:1fr 1fr;gap:16px}
@media (max-width: 700px){ .row-2{grid-template-columns:1fr} }
.qr-box{border:1px solid #e5e7eb;border-radius:12px;padding:10px;background:#fafafa;display:inline-block}
.qr-box img{max-width:220px;border-radius:8px;display:block}
.badge-hint{background:#f2f4f7;border:1px solid #e5e7eb;border-radius:999px;padding:2px 8px;font-size:.78rem;color:#475467}
.actions{display:flex;gap:10px;margin-top:10px}

/* --- QR existing block (kemas) --- */
.sp-qr-exist{display:flex;align-items:flex-start;gap:16px;flex-wrap:wrap}
.sp-qr-card{margin:0;padding:12px;border:1px solid #e5e7eb;border-radius:12px;background:#fff;box-shadow:0 2px 6px rgba(0,0,0,.04)}
.sp-qr-img{display:block;max-width:220px;border-radius:10px}
.sp-qr-meta{min-width:220px}
.sp-check{display:flex;align-items:center;gap:8px;font-weight:600}
.sp-actions{display:flex;gap:8px;margin-top:8px}
.sp-actions .btn{padding:6px 10px;border-radius:8px}

/* ===== Flash (centered message + close) ===== */
.flash{
  position:relative;
  display:flex; align-items:flex-start; gap:10px;
  padding:12px 40px 12px 12px; border-radius:12px; margin:0 0 14px;
  border:1px solid; box-shadow:0 2px 8px rgba(2,6,23,.06);
}
.flash.success{ background:#ecfdf5; border-color:#a7f3d0; color:#065f46; }
.flash .msg{ flex:1; text-align:center; }
.flash .close{
  position:absolute; top:8px; right:10px;
  border:0; background:transparent; font-size:18px; cursor:pointer; line-height:1;
}
</style>

<?php if ($success): ?>
  <div class="flash success" id="flashBox" role="alert" aria-live="polite">
    <div class="msg"><strong>Success:</strong> <span>Tetapan pembayaran berjaya dikemaskini.</span></div>
    <button class="close" aria-label="Close" onclick="this.parentElement.remove()">×</button>
  </div>
<?php endif; ?>

<div class="sp-wrap">
  <div class="sp-card">
    <div class="sp-head">
      <h3>🏦 Tetapan Pembayaran <span class="badge-hint">QR & Akaun Bank</span></h3>
      <div class="sub">Konfigurasi ini akan dipaparkan pada halaman pendaftaran ahli.</div>
    </div>

    <div class="sp-body">
      <form method="post" enctype="multipart/form-data" id="payForm">
        <input type="hidden" name="csrf_token" value="<?=h($csrf)?>">

        <div class="sp-grid">
          <div class="sp-field">
            <label>Nama Bank</label>
            <input type="text" name="bank_name" value="<?=h($setting['bank_name'])?>" placeholder="Contoh: Maybank" required>
            <div class="sp-help">Nama institusi kewangan.</div>
          </div>

          <div class="sp-field">
            <label>
              <span>No. Akaun</span>
              <button type="button" class="btn btn-sm btn-ghost" data-copy="#accNo">Copy</button>
            </label>
            <input type="text" id="accNo" name="account_number" value="<?=h($setting['account_number'])?>" placeholder="123456789012" required>
            <div class="sp-help">Elakkan ruang/format pelik jika tak perlu (contoh: 123456789012).</div>
          </div>

          <div class="sp-field">
            <label>
              <span>Nama Akaun</span>
              <button type="button" class="btn btn-sm btn-ghost" data-copy="#accName">Copy</button>
            </label>
            <input type="text" id="accName" name="account_name" value="<?=h($setting['account_name'])?>" placeholder="Contoh: KOPERASI PENGGUNA SAJ" required>
            <div class="sp-help">Nama pemegang akaun seperti tertera pada bank.</div>
          </div>

          <div class="sp-field">
            <label>Nota (dipapar di halaman pendaftaran)</label>
            <input type="text" name="note" maxlength="255"
                   placeholder="Contoh: Yuran keahlian RM10. Sila muat naik resit."
                   value="<?=h($setting['note'])?>">
            <div class="sp-help">Contoh mesej: amaun yuran, tarikh sah, atau arahan ringkas.</div>
          </div>
        </div>

        <div class="hr"></div>

        <div class="row-2">
          <div class="sp-field">
            <label>Imej QR <span class="sp-help" style="margin-left:6px">(PNG/JPG/WEBP, maks 3MB)</span></label>
            <input type="file" name="qr_image" id="qrInput" accept=".png,.jpg,.jpeg,.webp">
            <div class="sp-help">Sebaiknya gunakan QR rasmi (DuitNow/FPX) dan resolusi minimum 600×600.</div>

            <!-- Live preview -->
            <div id="qrPreviewWrap" class="qr-box" style="margin-top:10px; display:none;">
              <img id="qrPreview" src="" alt="QR Preview">
            </div>
            <div id="qrPreviewNote" class="sp-help" style="display:none;">Pratonton QR yang baru dipilih (belum disimpan).</div>
          </div>

          <div class="sp-field">
            <label>QR Sedia Ada</label>
            <?php if (!empty($setting['qr_image_path'])): ?>
              <div class="sp-qr-exist">
                <figure class="sp-qr-card">
                  <img class="sp-qr-img" src="<?=h($setting['qr_image_path'])?>?v=<?=time()?>" alt="QR semasa">
                </figure>
                <div class="sp-qr-meta">
                  <label class="sp-check">
                    <input type="checkbox" name="remove_qr" value="1"
                           onclick="if(this.checked && !confirm('Padam QR sedia ada? Tindakan ini tidak boleh diundur.')) this.checked=false;">
                    <span>Padam QR sedia ada</span>
                  </label>
                  <div class="sp-actions">
                    <a class="btn btn-ghost" target="_blank" href="<?=h($setting['qr_image_path'])?>">Buka saiz penuh</a>
                    <a class="btn btn-ghost" download href="<?=h($setting['qr_image_path'])?>">Muat turun</a>
                  </div>
                </div>
              </div>
            <?php else: ?>
              <div class="sp-help">Tiada QR disimpan. Anda boleh muat naik satu imej QR untuk rujukan pemohon.</div>
            <?php endif; ?>
          </div>
        </div>

        <div class="actions">
          <button class="btn btn-primary" type="submit">Simpan Tetapan</button>
          <a class="btn btn-ghost" href="dashboard.php">Batal</a>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
// Copy helper
document.querySelectorAll('[data-copy]').forEach(btn=>{
  btn.addEventListener('click', ()=>{
    const target = document.querySelector(btn.getAttribute('data-copy'));
    if (!target) return;
    navigator.clipboard.writeText(target.value || '').then(()=>{
      btn.textContent = 'Copied';
      setTimeout(()=>btn.textContent='Copy', 1200);
    });
  });
});

// Client-side size/type guard + live preview
const qrInput = document.getElementById('qrInput');
if (qrInput) {
  const wrap = document.getElementById('qrPreviewWrap');
  const img  = document.getElementById('qrPreview');
  const note = document.getElementById('qrPreviewNote');
  qrInput.addEventListener('change', (e)=>{
    const file = e.target.files?.[0];
    if (!file) { wrap.style.display='none'; note.style.display='none'; return; }
    if (file.size > 3 * 1024 * 1024) { alert('Saiz imej melebihi 3MB.'); e.target.value=''; wrap.style.display='none'; note.style.display='none'; return; }
    const ok = ['image/png','image/jpeg','image/jpg','image/webp'];
    if (!ok.includes(file.type)) { alert('Fail mesti PNG/JPG/WEBP.'); e.target.value=''; wrap.style.display='none'; note.style.display='none'; return; }
    const reader = new FileReader();
    reader.onload = ev => { img.src = ev.target.result; wrap.style.display='inline-block'; note.style.display='block'; };
    reader.readAsDataURL(file);
  });
}

// Auto-hide flash + scroll to top
(function(){
  const fb = document.getElementById('flashBox');
  if (fb){
    window.scrollTo({top:0,behavior:'smooth'});
    setTimeout(()=>{ if(fb){ fb.style.transition='opacity .4s'; fb.style.opacity='0'; setTimeout(()=>fb.remove(), 400); } }, 4000);
  }
})();
</script>
<?php
$content = ob_get_clean();
$title = "Tetapan Pembayaran";
$page_title = "Tetapan Pembayaran";
include __DIR__ . "/layout.php";
