<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('include/header.php');
$page_title = WEB_NAME . " | Logs Transactions";

try {
    $stmt = $pdo->query("
        SELECT p.*, s.service_name, c.category_name,
               u.username, u.full_name, u.email AS user_email
        FROM sm_purchases p
        LEFT JOIN sm_services s   ON p.service_id = s.id
        LEFT JOIN sm_categories c ON s.category_id = c.id
        LEFT JOIN users u         ON p.user_id = u.id
        ORDER BY p.id DESC
    ");
    $purchases = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $purchases = [];
    error_log("Logs Transactions fetch error: " . $e->getMessage());
}
?>
<title>Logs Transactions - <?php echo $site_data['web_name']; ?></title>

<link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">

<style>
  .btn-group { white-space: nowrap; }
  .dropdown-item { cursor: pointer; }
  .dropdown-item i { width: 20px; margin-right: 5px; }
</style>

<div class="container-fluid" id="container-wrapper">
  <div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">Logs Transactions</h1>
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
      <li class="breadcrumb-item active" aria-current="page">Logs Transactions</li>
    </ol>
  </div>

  <div class="row">
    <div class="col-lg-12">
      <div class="card mb-4">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
          <h6 class="m-0 font-weight-bold text-primary">
            <i class="fas fa-receipt mr-2"></i>All Logs Transactions (<?php echo count($purchases); ?> records)
          </h6>
        </div>
        <div class="table-responsive p-3">
          <table class="table align-items-center table-flush table-hover" id="dataTable">
            <thead class="thead-light">
              <tr>
                <th>#</th>
                <th>User</th>
                <th>Category</th>
                <th>Service</th>
                <th>Amount</th>
                <th>Date</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php $i = 1; foreach ($purchases as $data):
                switch ($data['status']) {
                  case 'completed':     $sbadge = 'badge-success';   $stext = 'Completed';     break;
                  case 'cancelled':     $sbadge = 'badge-secondary'; $stext = 'Cancelled';     break;
                  case 'refund_pending':$sbadge = 'badge-warning';   $stext = 'Refund Pending';break;
                  case 'refunded':      $sbadge = 'badge-info';      $stext = 'Refunded';      break;
                  default:              $sbadge = 'badge-secondary'; $stext = ucfirst($data['status']);
                }
                $display_name = !empty($data['full_name']) ? $data['full_name'] : ($data['username'] ?? '—');
              ?>
              <tr>
                <td><strong>#<?php echo $data['id']; ?></strong></td>
                <td>
                  <strong><?php echo htmlspecialchars($display_name); ?></strong><br>
                  <small class="text-muted"><?php echo htmlspecialchars($data['user_email'] ?? '—'); ?></small>
                </td>
                <td><?php echo htmlspecialchars($data['category_name'] ?? '—'); ?></td>
                <td><?php echo htmlspecialchars($data['service_name'] ?? '—'); ?></td>
                <td><strong>NGN<?php echo number_format($data['amount'], 2); ?></strong></td>
                <td>
                  <small><?php echo date('M d, Y', strtotime($data['purchase_date'])); ?></small><br>
                  <small class="text-muted"><?php echo date('h:i A', strtotime($data['purchase_date'])); ?></small>
                </td>
                <td><span class="badge <?php echo $sbadge; ?>"><?php echo $stext; ?></span></td>
                <td>
                  <div class="btn-group" role="group">
                    <button type="button" class="btn btn-sm btn-primary dropdown-toggle"
                            data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                      <i class="fas fa-cog"></i> Actions
                    </button>
                    <div class="dropdown-menu">
                      <?php if ($data['status'] === 'refund_pending'): ?>
                        <a class="dropdown-item" href="#"
                           onclick="approveRefund(<?php echo $data['id']; ?>, '<?php echo number_format($data['amount'], 2); ?>', '<?php echo htmlspecialchars($display_name, ENT_QUOTES); ?>')">
                          <i class="fas fa-check-circle text-success"></i> Approve Refund
                        </a>
                        <div class="dropdown-divider"></div>
                      <?php endif; ?>

                      <?php if ($data['status'] !== 'refunded'): ?>
                        <a class="dropdown-item" href="#"
                           onclick="changeStatus(<?php echo $data['id']; ?>, '<?php echo $data['status']; ?>')">
                          <i class="fas fa-edit text-primary"></i> Change Status
                        </a>
                      <?php endif; ?>

                      <?php if (!empty($data['refund_reason'])): ?>
                        <a class="dropdown-item" href="#"
                           onclick="showRefundReason('<?php echo htmlspecialchars(addslashes($data['refund_reason'])); ?>')">
                          <i class="fas fa-info-circle text-info"></i> View Reason
                        </a>
                      <?php endif; ?>
                    </div>
                  </div>
                </td>
              </tr>
              <?php $i++; endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Change Status Modal -->
<div class="modal fade" id="statusModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title"><i class="fas fa-edit mr-2"></i>Change Transaction Status</h5>
        <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="status_txn_id">
        <div class="form-group">
          <label class="font-weight-bold">New Status</label>
          <select class="form-control" id="new_status_val">
            <option value="completed">Completed</option>
            <option value="cancelled">Cancelled</option>
            <option value="refund_pending">Refund Pending</option>
            <option value="refunded">Refunded</option>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" onclick="submitStatusChange()">
          <i class="fas fa-save mr-1"></i> Update Status
        </button>
      </div>
    </div>
  </div>
</div>

<script src="vendor/datatables/jquery.dataTables.min.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(document).ready(function() {
  $('#dataTable').DataTable({ ordering: true, pageLength: 25, order: [[0, 'desc']] });
});

function approveRefund(id, amount, userName) {
  Swal.fire({
    title: 'Approve Refund?',
    html: `Refund <strong>NGN${amount}</strong> to <strong>${userName}</strong>?<br>
           <small class="text-muted">Amount will be credited to user's main balance.</small>`,
    icon: 'question', showCancelButton: true,
    confirmButtonColor: '#1cc88a', cancelButtonColor: '#858796',
    confirmButtonText: 'Yes, Approve Refund'
  }).then(r => {
    if (r.isConfirmed) smAjax({ action: 'approve_sm_refund', id: id });
  });
}

function changeStatus(id, currentStatus) {
  document.getElementById('status_txn_id').value  = id;
  document.getElementById('new_status_val').value  = currentStatus;
  $('#statusModal').modal('show');
}

function submitStatusChange() {
  var id     = document.getElementById('status_txn_id').value;
  var status = document.getElementById('new_status_val').value;
  $('#statusModal').modal('hide');
  smAjax({ action: 'change_sm_status', id: id, new_status: status });
}

function showRefundReason(reason) {
  Swal.fire({ title: 'Refund Reason', text: reason, icon: 'info', confirmButtonText: 'Close' });
}

function smAjax(data, onSuccess) {
  Swal.fire({ title: 'Processing...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
  $.ajax({
    url: 'ajax/sm_handler.php', type: 'POST', data: data, dataType: 'json',
    success: function(res) {
      Swal.close();
      if (res.status == '1') {
        Swal.fire({ title: 'Success!', text: res.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
          .then(() => { if (onSuccess) onSuccess(); location.reload(); });
      } else { Swal.fire('Error!', res.msg, 'error'); }
    },
    error: function() { Swal.close(); Swal.fire('Error!', 'An error occurred. Please try again.', 'error'); }
  });
}
</script>

<?php include('include/footer.php'); ?>