<?php session_start(); include"../connect/db.php" ?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Virtual Card Applications — Admin Panel</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="../plugins/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="../plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
  <link rel="stylesheet" href="../dist/css/adminlte.min.css">
  <style>
    .nav-header { padding: 10px 16px 4px; font-size: 0.65rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; color: rgba(255,255,255,0.3); }
    .nav-sidebar .nav-link.active { background-color: rgba(255,255,255,0.1); color: #fff; }
    .content-header h1 { font-size: 1.4rem; font-weight: 600; }
    .btn-primary { background-color: #033d75; border-color: #033d75; }
    .btn-success { background-color: #1ee0ac; border-color: #1ee0ac; color:#000; }
    .btn-warning { background-color: #f4bd0e; border-color: #f4bd0e; color:#000; }
    .btn-danger { background-color: #d13636; border-color: #d13636; }
    .btn-info { background-color: #09c2de; border-color: #09c2de; }
    .badge-pending { background: #f4bd0e; color: #000; }
    .badge-approved { background: #1ee0ac; color: #000; }
    .badge-rejected { background: #e85347; color: #fff; }
    .badge-cancelled { background: #6c757d; color: #fff; }
    .btn-group-actions { display:flex; gap:4px; flex-wrap:wrap; }
    .btn-group-actions .btn { padding:2px 8px; font-size:0.7rem; }
  </style>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
  <nav class="main-header navbar navbar-expand navbar-white navbar-light">
    <ul class="navbar-nav"><li class="nav-item"><a class="nav-link" data-widget="pushmenu" href="#"><i class="fas fa-bars"></i></a></li></ul>
    <ul class="navbar-nav ml-auto"><li class="nav-item"><a class="nav-link" href="../apps/login/logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li></ul>
  </nav>
  <aside class="main-sidebar sidebar-dark-primary elevation-4">
    <a href="main.php" class="brand-link"><img src="../logo.png" alt="Logo" class="brand-image" style="height:28px;opacity:.9"><span class="brand-text font-weight-light">Admin Panel</span></a>
    <?php include"includes/sidebar.php" ?>
  </aside>
  <div class="content-wrapper">
    <div class="content-header"><div class="container-fluid"><h1>Virtual Card Applications</h1></div></div>
    <section class="content"><div class="container-fluid">
      <div class="card">
        <div class="card-body">
          <table id="cardsTable" class="table table-bordered table-striped">
            <thead><tr><th>ID</th><th>Applicant</th><th>Email</th><th>Card Type</th><th>Status</th><th>Card Number</th><th>Applied</th><th>Actions</th></tr></thead>
            <tbody>
            <?php
            $result = $mysqli->query("SELECT * FROM virtualcard ORDER BY id DESC");
            if ($result):
            while ($r = $result->fetch_assoc()):
              $badgeMap = ['pending'=>'badge-pending','approved'=>'badge-approved','Completed'=>'badge-approved','rejected'=>'badge-rejected','cancelled'=>'badge-cancelled'];
              $badge = $badgeMap[$r['status']] ?? 'badge-secondary';
              $masked = !empty($r['card_number']) ? '•••• ' . substr($r['card_number'], -4) : '—';
            ?>
              <tr>
                <td><?=$r['id']?></td>
                <td><?=htmlspecialchars($r['fullname'])?></td>
                <td><?=htmlspecialchars($r['email'])?></td>
                <td><span class="text-uppercase"><?=htmlspecialchars($r['card_type'])?></span></td>
                <td><span class="badge <?=$badge?>"><?=ucfirst($r['status'])?></span></td>
                <td><code><?=$masked?></code></td>
                <td><?=$r['application_date'] ?? $r['created_at'] ?? '—'?></td>
                <td>
                  <div class="btn-group-actions">
                    <?php if ($r['status'] === 'pending'): ?>
                      <button class="btn btn-success approve-btn" data-id="<?=$r['id']?>" data-name="<?=htmlspecialchars($r['fullname'])?>"><i class="fas fa-check"></i></button>
                      <button class="btn btn-danger reject-btn" data-id="<?=$r['id']?>" data-name="<?=htmlspecialchars($r['fullname'])?>"><i class="fas fa-times"></i></button>
                      <button class="btn btn-warning cancel-btn" data-id="<?=$r['id']?>" data-name="<?=htmlspecialchars($r['fullname'])?>"><i class="fas fa-ban"></i></button>
                    <?php endif; ?>
                    <?php if ($r['status'] === 'approved' || $r['status'] === 'Completed'): ?>
                      <button class="btn btn-info edit-btn" data-id="<?=$r['id']?>" data-fullname="<?=htmlspecialchars($r['fullname'])?>" data-cardnumber="<?=htmlspecialchars($r['card_number'])?>" data-expiry="<?=htmlspecialchars($r['expiration_date'])?>" data-cvv="<?=htmlspecialchars($r['cvv'])?>"><i class="fas fa-edit"></i></button>
                    <?php endif; ?>
                    <button class="btn btn-danger delete-btn" data-id="<?=$r['id']?>" data-name="<?=htmlspecialchars($r['fullname'])?>"><i class="fas fa-trash"></i></button>
                  </div>
                </td>
              </tr>
            <?php endwhile; ?>
            <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div></section>
  </div>
</div>

<!-- Reject Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1">
  <div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title">Reject Application</h5><button type="button" class="close" data-dismiss="modal">&times;</button></div>
    <div class="modal-body">
      <p>Rejecting: <strong id="rejectName"></strong></p>
      <div class="form-group"><label>Reason <span class="text-danger">*</span></label><textarea id="rejectReason" class="form-control" rows="3"></textarea></div>
    </div>
    <div class="modal-footer"><button class="btn btn-secondary" data-dismiss="modal">Cancel</button><button class="btn btn-danger" id="confirmReject">Reject</button></div>
  </div></div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title">Edit Card</h5><button type="button" class="close" data-dismiss="modal">&times;</button></div>
    <div class="modal-body">
      <input type="hidden" id="editId">
      <div class="form-group"><label>Cardholder Name</label><input type="text" id="editName" class="form-control"></div>
      <div class="form-group"><label>Card Number</label><input type="text" id="editNumber" class="form-control"></div>
      <div class="row"><div class="col-6"><div class="form-group"><label>Expiry</label><input type="text" id="editExpiry" class="form-control" placeholder="MM/YY"></div></div><div class="col-6"><div class="form-group"><label>CVV</label><input type="text" id="editCvv" class="form-control"></div></div></div>
    </div>
    <div class="modal-footer"><button class="btn btn-secondary" data-dismiss="modal">Cancel</button><button class="btn btn-primary" id="confirmEdit">Save Changes</button></div>
  </div></div>
</div>

<script src="../plugins/jquery/jquery.min.js"></script>
<script src="../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../plugins/datatables/jquery.dataTables.min.js"></script>
<script src="../plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="../dist/js/adminlte.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(function(){
  $('#cardsTable').DataTable({ order: [[0, 'desc']], pageLength: 25 });

  function showToast(icon, title){
    Swal.fire({ toast:true, position:'top-end', showConfirmButton:false, timer:2000, icon:icon, title:title });
  }

  // Reject
  var rejectId = null;
  $('.reject-btn').click(function(){ rejectId = $(this).data('id'); $('#rejectName').text($(this).data('name')); $('#rejectReason').val(''); $('#rejectModal').modal('show'); });
  $('#confirmReject').click(function(){
    var r = $('#rejectReason').val().trim();
    if(!r){ Swal.fire({icon:'warning',title:'Reason Required',text:'Please provide a rejection reason.'}); return; }
    Swal.fire({title:'Rejecting...',text:'Please wait',allowOutsideClick:false,didOpen:function(){Swal.showLoading()}});
    $.post('../apps/man/rejectcard.php',{id:rejectId,reason:r},function(d){
      if(d.trim()==='success'){ Swal.fire({icon:'success',title:'Rejected',text:'Application has been rejected.',timer:1500,showConfirmButton:false}).then(function(){location.reload()}); }
      else{ Swal.fire({icon:'error',title:'Error',text:d}); }
    });
  });

  // Approve
  $('.approve-btn').click(function(){
    var id=$(this).data('id'), n=$(this).data('name');
    Swal.fire({title:'Approve Card?',text:'Approve virtual card for '+n+'?',icon:'question',showCancelButton:true,confirmButtonText:'Yes, Approve',confirmButtonColor:'#1ee0ac',cancelButtonText:'Cancel'}).then(function(r){
      if(!r.isConfirmed) return;
      Swal.fire({title:'Approving...',allowOutsideClick:false,didOpen:function(){Swal.showLoading()}});
      $.post('../apps/man/approvecard.php',{id:id},function(d){
        if(d.trim()==='success'){ Swal.fire({icon:'success',title:'Approved!',text:'Card has been approved.',timer:1500,showConfirmButton:false}).then(function(){location.reload()}); }
        else{ Swal.fire({icon:'error',title:'Error',text:d}); }
      });
    });
  });

  // Cancel
  $('.cancel-btn').click(function(){
    var id=$(this).data('id'), n=$(this).data('name');
    Swal.fire({title:'Cancel Application?',text:'Cancel application for '+n+'?',icon:'warning',showCancelButton:true,confirmButtonText:'Yes, Cancel',confirmButtonColor:'#f4bd0e',cancelButtonText:'No'}).then(function(r){
      if(!r.isConfirmed) return;
      $.post('../apps/man/cancelcard.php',{id:id},function(d){
        if(d.trim()==='success'){ showToast('success','Cancelled.'); setTimeout(function(){location.reload()},1500); }
        else{ Swal.fire({icon:'error',title:'Error',text:d}); }
      });
    });
  });

  // Delete
  $('.delete-btn').click(function(){
    var id=$(this).data('id'), n=$(this).data('name');
    Swal.fire({title:'Delete Permanently?',text:'Delete card/application for '+n+'? This cannot be undone.',icon:'warning',showCancelButton:true,confirmButtonText:'Yes, Delete',confirmButtonColor:'#d13636',cancelButtonText:'Cancel'}).then(function(r){
      if(!r.isConfirmed) return;
      $.post('../apps/man/deletecard.php',{id:id},function(d){
        if(d.trim()==='success'){ showToast('success','Deleted.'); setTimeout(function(){location.reload()},1500); }
        else{ Swal.fire({icon:'error',title:'Error',text:d}); }
      });
    });
  });

  // Edit
  $('.edit-btn').click(function(){
    $('#editId').val($(this).data('id'));
    $('#editName').val($(this).data('fullname'));
    $('#editNumber').val($(this).data('cardnumber'));
    $('#editExpiry').val($(this).data('expiry'));
    $('#editCvv').val($(this).data('cvv'));
    $('#editModal').modal('show');
  });
  $('#confirmEdit').click(function(){
    var data = { id: $('#editId').val(), fullname: $('#editName').val(), card_number: $('#editNumber').val(), expiration_date: $('#editExpiry').val(), cvv: $('#editCvv').val() };
    Swal.fire({title:'Saving...',allowOutsideClick:false,didOpen:function(){Swal.showLoading()}});
    $.post('../apps/man/updatecard.php', data, function(d){
      if(d.trim()==='success'){ Swal.fire({icon:'success',title:'Updated',timer:1500,showConfirmButton:false}).then(function(){location.reload()}); }
      else{ Swal.fire({icon:'error',title:'Error',text:d}); }
    });
  });
});
</script>
</body>
</html>
