<?php
require_once __DIR__.'/../inc/config.php';
require_once __DIR__.'/../inc/db.php';
require_once __DIR__.'/../inc/helpers.php';
require_once __DIR__.'/../inc/csrf.php';

// ... require_once ...
if(empty($_SESSION['admin_id'])){ header('Location: login.php'); exit; } // 1. Semak login dahulu
if ($_SESSION['admin_role'] !== 'admin') { // 2. Kemudian baru semak role
    exit('Akses disekat. Anda tiada kebenaran untuk melihat halaman ini.');
}

// Pastikan hanya admin yang log masuk boleh akses halaman ini
if(empty($_SESSION['admin_id'])){ header('Location: login.php'); exit; }

$feedback_msg = '';
$feedback_type = 'success';

// Fungsi untuk menguruskan muat naik imej QR
function handle_qr_code_upload(string $file_input_name) {
    if (isset($_FILES[$file_input_name]) && $_FILES[$file_input_name]['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES[$file_input_name];
        $upload_dir = __DIR__ . '/../public/uploads/';
        $upload_url = PUBLIC_URL . 'uploads/';
        $max_size = 2 * 1024 * 1024; // 2MB had saiz

        if ($file['size'] > $max_size) { return 'Ralat: Saiz imej QR melebihi 2MB.'; }
        
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        if (!in_array($file['type'], $allowed_types)) { return 'Ralat: Jenis fail tidak dibenarkan.'; }
        
        $filename = preg_replace('/[^a-zA-Z0-9-_\.]/', '', basename($file['name']));
        $unique_filename = 'qr_code_' . uniqid() . '_' . $filename;
        $destination = $upload_dir . $unique_filename;

        if (move_uploaded_file($file['tmp_name'], $destination)) {
            set_setting('QR_CODE_IMAGE_URL', $upload_url . $unique_filename);
            return null; // Tiada ralat
        } else { 
            return 'Ralat: Gagal memindahkan fail.'; 
        }
    }
    return null; // Tiada fail dimuat naik, bukan satu ralat
}

// Proses borang apabila dihantar
if($_SERVER['REQUEST_METHOD']==='POST'){
  if(!csrf_verify()) {
      $feedback_msg = 'CSRF Gagal. Sila cuba lagi.';
      $feedback_type = 'error';
  } else {
      // Simpan tetapan teks
      set_setting('BANK_NAME', $_POST['bank_name'] ?? '');
      set_setting('BANK_ACCOUNT_NAME', $_POST['bank_account_name'] ?? '');
      set_setting('BANK_ACCOUNT_NO', $_POST['bank_account_no'] ?? '');

      // Uruskan muat naik imej QR
      $upload_error = handle_qr_code_upload('qr_code_file');
      if ($upload_error) {
          $feedback_msg = $upload_error;
          $feedback_type = 'error';
      } else {
          $feedback_msg = 'Tetapan bank telah berjaya disimpan!';
      }
  }
}
?>
<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../public/assets/css/style.css"><title>Tetapan Bank</title>
<style>
    .admin-wrapper { display: flex; align-items: flex-start; gap: 24px; } 
    .admin-sidebar { width: 220px; flex-shrink: 0; } 
    .admin-content { flex-grow: 1; } 
    .feedback { padding: 12px; border-radius: 12px; margin-bottom: 20px; } 
    .feedback.success { background-color: #dcfce7; color: #166534; } 
    .feedback.error { background-color: #fee2e2; color: #991b1b; }
    .form-group label { display: block; margin-bottom: 16px; font-weight: 600; } 
    .form-group input, .form-group textarea { width: 100%; padding: 10px; border: 1px solid #d1d5db; border-radius: 8px; margin-top: 6px; box-sizing: border-box; }
    .image-preview { margin-top: 10px; }
    .image-preview img { max-width: 200px; height: auto; border: 1px solid #e5e7eb; border-radius: 8px; padding: 5px; }
</style>
</head><body><div class="container">
<div class="admin-wrapper">
    <aside class="admin-sidebar"><?php require_once '_menu.php'; ?></aside>
    <main class="admin-content">
        <h1>Tetapan Bank & Pembayaran Manual</h1>
        <p>Uruskan maklumat akaun bank yang akan dipaparkan kepada pelanggan untuk pembayaran manual atau COD.</p>

        <?php if ($feedback_msg): ?><div class="feedback <?= $feedback_type ?>"><?= e($feedback_msg) ?></div><?php endif; ?>

        <div class="card">
            <form method="post" enctype="multipart/form-data">
                <?= csrf_field() ?>
                <div class="form-group">
                    <label>Nama Bank
                        <input name="bank_name" value="<?= e(setting('BANK_NAME')) ?>" placeholder="cth: Maybank">
                    </label>
                </div>
                <div class="form-group">
                    <label>Nama Akaun
                        <input name="bank_account_name" value="<?= e(setting('BANK_ACCOUNT_NAME')) ?>" placeholder="cth: Syarikat ABC Sdn Bhd">
                    </label>
                </div>
                <div class="form-group">
                    <label>Nombor Akaun
                        <input name="bank_account_no" value="<?= e(setting('BANK_ACCOUNT_NO')) ?>" placeholder="cth: 552189xxxxxx">
                    </label>
                </div>
                <hr style="margin: 20px 0;">
                <div class="form-group">
                    <label>Imej Kod QR (DuitNow/Lain-lain)
                        <input type="file" name="qr_code_file">
                    </label>
                    <?php $current_qr = setting('QR_CODE_IMAGE_URL'); ?>
                    <?php if ($current_qr): ?>
                        <div class="image-preview">
                            <p>Kod QR Semasa:</p>
                            <img src="<?= e($current_qr) ?>" alt="Kod QR semasa">
                        </div>
                    <?php endif; ?>
                </div>

                <button type="submit" class="cta" style="margin-top:20px;">Simpan Tetapan</button>
            </form>
        </div>
    </main>
</div>
</div></body></html>