<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');

$message = '';
$userfound = false;
$userdata = [];


$senderIdentifier = '';
if(!empty($udata)){
    $senderIdentifier = $udata['phone'] ?? $udata['mobileno'] ?? $udata['email'] ?? '';
}
if(empty($senderIdentifier) && !empty($_SESSION)){
    $senderIdentifier = $_SESSION['phone'] ?? $_SESSION['mobileno'] ?? $_SESSION['email'] ?? '';
}

$senderRole = strtolower($udata['type'] ?? '');


$mysqli = function_exists('ahkConn') ? ahkConn() : ($tng_conn instanceof mysqli ? $tng_conn : null);

if($senderRole === 'retailer'){
    echo "<h3 class='text-danger'>Retailer is not allowed to access this page.</h3>";
    include('../template/tngweb/footer.php');
    exit;
}

if(isset($_POST['username']) && !empty($_POST['username'])){
    $username = getSafe($_POST['username']);
    $userfound = ahkRows("SELECT * FROM users WHERE phone='$username' OR email='$username'") == 1;
    $userdata = $userfound ? fetchRow("SELECT * FROM users WHERE phone='$username' OR email='$username'") : [];
    $message = $userfound ? 'User Fetched Successfully!' : 'No user found with this Email or Phone';

    if($userfound && isset($_POST['txn_type'], $_POST['purpose'], $_POST['amount']) && !empty($_POST['amount'])){
        $amount = (float) str_replace(',', '', getSafe($_POST['amount']));
        $txn_type = getSafe($_POST['txn_type']);
        $purpose = getSafe($_POST['purpose']);

        $result = walletTransaction($username, $txn_type, $amount, $purpose);
        ?>
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script>
            Swal.fire({
                icon: '<?php echo $result['success'] ? "success" : "error"; ?>',
                title: '<?php echo $result['success'] ? "Success!" : "Failed!"; ?>',
                text: '<?php echo $result['message']; ?>',
                confirmButtonText: 'OK'
            }).then((res)=>{
                if(res.isConfirmed && <?php echo $result['success'] ? "true" : "false"; ?>){
                    window.location.href = 'BalanceTransfer.php'; 
                }
            });
        </script>
        <?php
    }
}
?>
<!--start page wrapper -->
<div class="page-wrapper">
  <div class="page-content">
    <div class="card radius-15 shadow-lg border-0">
      <div class="card-body">
        <!-- Back Button -->
        <div class="d-flex align-items-center justify-content-between mb-3">
          <a href="javascript:void(0);" onclick="window.history.back();" class="btn btn-outline-primary rounded-pill px-4 py-2 fw-semibold">
            <i class="bi bi-arrow-left-circle me-2"></i> Go Back
          </a>
          <h5 class="mb-0 fw-bold text-primary">💰 All Balance Transfer </h5>
        </div>


<?php if($userfound === false){ ?>

                <?php if($message != ''){ echo "<h5 class='text-danger'>$message</h5><br>"; } ?>
                <form action="" method="POST" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Email or Phone</label>
                        <input name="username" type="text" placeholder="Email or Phone" class="form-control">
                    </div>
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary px-5">Fetch Details</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<?php } ?>

<?php if($userfound === true){ ?>
<div class="row">
    <div class="col-xl-10 mx-auto">
        <h6 class="mb-0 text-uppercase">Beneficiary Details</h6><hr/>
        <div class="card border-top border-0 border-4 border-primary">
            <div class="card-body p-5">
                <?php if($message != ''){ echo "<h5 class='text-success'>$message</h5><br>"; } ?>
                <form action="" method="POST" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Email or Phone</label>
                        <input name="username" value="<?php echo $_POST['username'];?>" type="text" readonly class="form-control">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Customer Name</label>
                        <input name="name" value="<?php echo $userdata['name'];?>" type="text" readonly class="form-control">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Current Balance</label>
                        <input name="balance" value="<?php echo $userdata['balance'];?>" type="text" readonly class="form-control">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Transaction Type</label>
                        <select class="form-control" name="txn_type">
                            <option value="">Please Select</option>
                            <?php if($senderRole == 'admin'){ ?>
                                <option value="credit">Credit</option>
                                <option value="debit">Debit</option>
                            <?php } else { ?>
                                <option value="credit">Credit</option>
                            <?php } ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Purpose</label>
                        <select class="form-control" name="purpose">
                            <option value="">Please Select</option>
                            <option value="deposit">Deposit</option>
                            <option value="refund">Refund</option>
                            <option value="penalty">Penalty</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Amount</label>
                        <input name="amount" type="text" placeholder="TXN Amount" class="form-control">
                    </div>
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary px-5">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<?php } ?>

</div>
</div>

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

<!-- ✅ DataTables CDN & Scripts -->
<script src="../template/tngweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/tngweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/tngweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/tngweb/assets/js/app.js"></script>


<script>
  $(document).ready(function() {
    $('#walletTable').DataTable({
      lengthChange: false,
      pageLength: 10,
      order: [[0, "desc"]],
      buttons: ['copy', 'excel', 'pdf', 'print'],
      dom: '<"d-flex justify-content-between align-items-center mb-3"Bf>rt<"d-flex justify-content-between align-items-center"ip>'
    });
  });
</script>

<style>
  /* 🌟 Stylish Table */
  .table thead th {
    vertical-align: middle;
    font-weight: 600;
    letter-spacing: 0.3px;
  }

  .table tbody tr:hover {
    background: #f5f8ff;
    transition: 0.2s ease;
  }

  .card {
    background: #fff;
    border-radius: 15px;
  }

  .btn-outline-primary {
    border-color: #0055ff;
    color: #0055ff;
  }

  .btn-outline-primary:hover {
    background-color: #0055ff;
    color: #fff;
  }

  .dataTables_wrapper .dataTables_filter input {
    border-radius: 8px;
    padding: 5px 10px;
  }

  .dataTables_wrapper .dataTables_paginate .paginate_button {
    border-radius: 5px;
  }

  .dataTables_wrapper .dt-buttons .btn {
    border-radius: 20px !important;
    font-size: 0.85rem;
    margin-right: 6px;
  }

  .badge {
    font-size: 0.8rem;
    padding: 6px 10px;
  }
</style>
