<?php $this->load->view('templates/header'); ?>
<?php $this->load->view('templates/sidebar'); ?>
<?php $this->load->view('templates/topbar'); ?>

<div class="container-fluid">
  <h1 class="h3 mb-4 text-gray-800">Pembayaran_pelatihan / Detail</h1>

  <?php if ($this->session->flashdata('success')): ?>
    <div class="alert alert-success"><?= $this->session->flashdata('success'); ?></div>
  <?php endif; ?>
  <?php if ($this->session->flashdata('error')): ?>
    <div class="alert alert-danger"><?= $this->session->flashdata('error'); ?></div>
  <?php endif; ?>

  <!-- Biodata -->
  <div class="card shadow mb-4">
    <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Biodata Siswa</h6></div>
    <div class="card-body">
      <div class="row">
        <div class="col-md-6">
          <p><strong>Nama:</strong> <?= html_escape($siswa->NamaLengkap ?? '-'); ?></p>
          <p><strong>Email:</strong> <?= html_escape($siswa->Email ?? '-'); ?></p>
          <p><strong>No HP:</strong> <?= html_escape($siswa->Phone ?? '-'); ?></p>
        </div>
        <div class="col-md-6">
          <p><strong>SiswaID:</strong> <?= !empty($siswa->SiswaID) ? html_escape($siswa->SiswaID) : '— (calon)'; ?></p>
          <p><strong>Status:</strong> <?= html_escape($siswa->NamaStatus ?? 'Calon'); ?></p>
        </div>
      </div>
    </div>
  </div>

  <!-- Riwayat -->
  <div class="card shadow" id="pending">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
      <h6 class="m-0 font-weight-bold text-primary">Riwayat Transaksi</h6>
      <a href="<?= base_url('pembayaran_pelatihan/admin'); ?>" class="btn btn-sm btn-outline-secondary">&larr; Kembali ke Ringkasan</a>
    </div>

    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-hover mb-0">
          <thead class="thead-light">
          <tr>
            <th>Tanggal</th>
            <th>Jumlah</th>
            <th>Metode</th>
            <th>Bukti Transfer</th>
            <th>Status</th>
            <th style="width:220px">Aksi</th>
            <th style="width:240px">Cetak</th>
          </tr>
          </thead>
          <tbody>
          <?php $fmt = function($n){ return 'Rp '.number_format((float)$n,0,',','.'); }; ?>

          <?php if (!empty($transaksi)): foreach ($transaksi as $t):
            $id_bayar  = (int)($t->PembayaranID ?? 0);
            $tgl       = !empty($t->TanggalBayar) ? date('Y-m-d H:i:s', strtotime($t->TanggalBayar)) : '-';
            $jumlah    = $t->JumlahBayar ?? 0;
            $metode    = $t->MetodeBayar ?? '-';
            $status    = strtolower($t->StatusBayar ?? '');
            $bukti     = $t->BuktiTransfer ?? null;

            $bukti_url = $bukti ? base_url('uploads/bukti_transfer/'.$bukti) : null;
            $is_img    = $bukti_url && preg_match('/\.(jpe?g|png|gif)$/i', $bukti_url);
            $is_pdf    = $bukti_url && preg_match('/\.pdf$/i', $bukti_url);
          ?>
            <tr>
              <td><?= html_escape($tgl); ?></td>
              <td><?= $fmt($jumlah); ?></td>
              <td><?= html_escape($metode); ?></td>
              <td>
                <?php if ($bukti_url): ?>
                  <?php if ($is_img): ?>
                    <a href="<?= $bukti_url; ?>" class="preview-link" data-toggle="modal" data-target="#imgPreviewModal" data-bs-toggle="modal" data-bs-target="#imgPreviewModal" data-img="<?= $bukti_url ?>">
                      <img src="<?= $bukti_url; ?>" alt="bukti" class="img-thumbnail" style="width:90px;height:60px;object-fit:cover;">
                    </a>
                  <?php elseif ($is_pdf): ?>
                    <a class="btn btn-sm btn-outline-secondary" target="_blank" href="<?= $bukti_url; ?>">PDF</a>
                  <?php else: ?>
                    <a target="_blank" href="<?= $bukti_url; ?>">Lihat</a>
                  <?php endif; ?>
                <?php else: ?><em>-</em><?php endif; ?>
              </td>
              <td>
                <?php if ($status === 'approved'): ?>
                  <span class="badge badge-success">Approved</span>
                <?php elseif ($status === 'rejected'): ?>
                  <span class="badge badge-danger">Rejected</span>
                <?php else: ?>
                  <span class="badge badge-warning">Pending</span>
                <?php endif; ?>
              </td>

              <td>
                <?php if ($status === 'pending'): ?>
                  <a href="<?= base_url('pembayaran_pelatihan/approve/'.$id_bayar); ?>"
                     class="btn btn-sm btn-primary"
                     onclick="return confirm('Approve pembayaran ini?');">Approve</a>

                  <button type="button"
                          class="btn btn-sm btn-outline-danger btn-reject"
                          data-id="<?= $id_bayar; ?>"
                          data-action="<?= base_url('pembayaran_pelatihan/reject/'.$id_bayar); ?>"
                          data-toggle="modal" data-target="#rejectModal"
                          data-bs-toggle="modal" data-bs-target="#rejectModal">
                    Reject
                  </button>
                <?php else: ?>
                  <em class="text-muted">—</em>
                <?php endif; ?>
              </td>

              <td>
                <a class="btn btn-sm btn-outline-secondary" target="_blank" href="<?= site_url('pembayaran_pelatihan/print_invoice/'.$id_bayar) ?>">Print Invoice</a>
                <?php if ($status === 'approved'): ?>
                  <a class="btn btn-sm btn-outline-success" target="_blank" href="<?= site_url('pembayaran_pelatihan/print_kwitansi/'.$id_bayar) ?>">Print Kwitansi</a>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="7" class="text-center text-muted">Belum ada transaksi</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- Modal Preview Gambar -->
<div class="modal fade" id="imgPreviewModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
    <div class="modal-content"><div class="modal-body p-0"><img id="imgPreviewTag" src="" alt="Preview" style="width:100%;height:auto;display:block"></div></div>
  </div>
</div>

<!-- Modal Reject (POST) -->
<div class="modal fade" id="rejectModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <form method="post" id="rejectForm">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Tolak Pembayaran</h5>
          <button type="button" class="close" data-dismiss="modal" data-bs-dismiss="modal"><span>&times;</span></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="alasan" id="rejectReasonHidden">
          <div class="form-group">
            <label>Alasan penolakan (opsional)</label>
            <textarea id="rejectReason" class="form-control" rows="3" placeholder="Contoh: Bukti transfer tidak jelas / nominal tidak sesuai"></textarea>
          </div>
          <p class="mb-0 text-danger small">Status akan diubah ke <b>Rejected</b>.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal" data-bs-dismiss="modal">Batal</button>
          <button type="submit" class="btn btn-danger">Tolak</button>
        </div>
      </div>
    </form>
  </div>
</div>

<script>
  // preview gambar
  document.addEventListener('click', function(e){
    const link = e.target.closest('.preview-link');
    if(!link) return;
    const img = link.getAttribute('data-img');
    const tag = document.getElementById('imgPreviewTag');
    if(tag && img){ tag.src = img; }
  });

  // wire tombol Reject -> set action + kirim alasan
  (function(){
    const modalEl = document.getElementById('rejectModal');
    const form    = document.getElementById('rejectForm');
    let actionUrl = '';

    // Ketika tombol reject di klik, simpan action
    document.addEventListener('click', function(e){
      const btn = e.target.closest('.btn-reject');
      if(!btn) return;
      actionUrl = btn.getAttribute('data-action') || '';
      if(actionUrl) form.setAttribute('action', actionUrl);
    });

    // copy alasan ke hidden saat submit
    form.addEventListener('submit', function(){
      document.getElementById('rejectReasonHidden').value =
        document.getElementById('rejectReason').value || '';
    });

    // Fallback buka modal (kalau data-* tidak bekerja)
    document.addEventListener('click', function(e){
      const btn = e.target.closest('.btn-reject');
      if(!btn) return;
      if (window.bootstrap && bootstrap.Modal) {
        new bootstrap.Modal(modalEl).show();
      }
      // (BS4 akan ditangani oleh data-toggle, jadi tidak perlu jQuery)
    });
  })();
</script>

<?php $this->load->view('templates/footer'); ?>
