<?php
include 'header.php';

$error = $msg = "";

// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] && isset($_POST['sub-upd'])) {
    $amount = text_input($_POST['amount']);
    $dtype = text_input($_POST['dtype']);
    $tranxId = uniqid('DEP');

    // Validate inputs
    if (empty($amount) || empty($dtype)) {
        $error = "All fields are required!";
    } elseif (!is_numeric($amount) || $amount <= 0) {
        $error = "Please enter a valid deposit amount!";
    }

    // Validate payment method
    if (!isset($payMethods[$dtype])) {
        $error = "Invalid payment method selected!";
    }

    // If no errors, insert deposit record into the database
    if (empty($error)) {
        $stmt = mysqli_prepare($conn, "INSERT INTO deposits (method, userId, tranxId, amount, status, date) VALUES (?, ?, ?, ?, 'pending', NOW())");
        mysqli_stmt_bind_param($stmt, "ssss", $dtype, $userId, $tranxId, $amount);

        if (mysqli_stmt_execute($stmt)) {
            $lastInsertId = mysqli_insert_id($conn);
            $msg = "Attach Proof to Process Deposit";
        } else {
            $error = "Database error: " . mysqli_error($conn);
        }

        mysqli_stmt_close($stmt);
    }
}


?>

<script>
document.addEventListener("DOMContentLoaded", function () {
    <?php if (!empty($error)) { ?>
        Swal.fire({
            icon: 'error',
            title: 'Oops...',
            text: '<?php echo $error; ?>',
            confirmButtonColor: '#d33'
        });
    <?php } ?>

    <?php if (!empty($msg)) { ?>
        Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: '<?php echo $msg; ?>',
            confirmButtonColor: '#28a745'
        }).then((result) => {
            if (result.isConfirmed || result.isDismissed) {
                window.location.href = 'deposit-payment.php?id=<?php echo $lastInsertId ?>&tx=<?php echo $tranxId ?>&option=confirm'; // Change to your dashboard or home page
            }
        });
    <?php } ?>
});
</script>
<main class="main-content w-full px-[var(--margin-x)] pb-8">


      <div class="flex items-center space-x-4 py-5 lg:py-6">
        <h2 class="text-xl font-medium text-slate-800 dark:text-navy-50 lg:text-2xl">
          Deposit
        </h2>
        <div class="hidden h-full py-1 sm:flex">
          <div class="h-full w-px bg-slate-300 dark:bg-navy-600"></div>
        </div>
        <ul class="hidden flex-wrap items-center space-x-2 sm:flex">
          <li class="flex items-center space-x-2">
            <a class="text-primary transition-colors hover:text-primary-focus dark:text-accent-light dark:hover:text-accent"
              href="#">User</a>
            <svg x-ignore xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24"
              stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
            </svg>
          </li>
          <li>Deposit</li>
        </ul>
      </div>








      <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-5 lg:grid-cols-6 lg:gap-6">
        <div class="card px-4 pb-4 sm:px-5">

          <div class="flex items-center justify-between py-3 font-medium text-slate-700 dark:text-white">
            <h2 class="text-sm+ font-medium tracking-wide">Available Balance</h2>
            <div x-data="usePopper({placement:'bottom-end',offset:4})"
              @click.outside="if(isShowPopper) isShowPopper = false" class="inline-flex">
              <button x-ref="popperRef" @click="isShowPopper = !isShowPopper"
                class="btn -mr-1.5 h-8 w-8 rounded-full p-0 hover:bg-white/20 focus:bg-white/20 active:bg-white/25">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24"
                  stroke="currentColor" stroke-width="2">
                  <path stroke-linecap="round" stroke-linejoin="round"
                    d="M5 12h.01M12 12h.01M19 12h.01M6 12a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0z">
                  </path>
                </svg>
              </button>

            </div>
          </div>
          <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-5 lg:gap-6">
            <div>

              <div class=" text-3xl font-semibold text-slate-700 dark:text-white ">
              $<?=number_format($balance,2)?>
              </div>
              <p class="mt-3 text-xs+ text-slate-700 dark:text-white"><?php echo number_format( getCryptoValueByShortCode("BTC", $balance),4) ; ?> BTC</p>
            </div>

            <div class="grid grid-cols-6 gap-4 sm:gap-5 lg:gap-6">


              <div>
                <div x-data="{showModal:false}">
                  <button @click="showModal = true"
                    class="btn mt-3 space-x-2 bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90">
                    <i class="fa fa-credit-card"></i>
                    <span> Fund Account </span>
                  </button>






                  <template x-teleport="#x-teleport-target">
                    <div
                      class="fixed inset-0 z-[100] flex flex-col items-center backdrop-blur justify-center overflow-hidden px-4 py-6 sm:px-5"
                      x-show="showModal" role="dialog" @keydown.window.escape="showModal = false">
                      <div class="absolute inset-0 bg-slate-900/60 transition-opacity duration-300"
                        @click="showModal = false" x-show="showModal" x-transition:enter="ease-out"
                        x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100"
                        x-transition:leave="ease-in" x-transition:leave-start="opacity-100"
                        x-transition:leave-end="opacity-0"></div>
                      <div
                        class="relative w-full max-w-lg origin-top rounded-lg bg-white transition-all duration-300 dark:bg-navy-700"
                        x-show="showModal" x-transition:enter="easy-out" x-transition:enter-start="opacity-0 scale-95"
                        x-transition:enter-end="opacity-100 scale-100" x-transition:leave="easy-in"
                        x-transition:leave-start="opacity-100 scale-100" x-transition:leave-end="opacity-0 scale-95">
                        <div class="flex justify-between rounded-t-lg bg-slate-200 px-4 py-3 dark:bg-navy-800 sm:px-5">
                          <h3 class="text-base font-medium text-slate-700 dark:text-navy-100">
                            Deposit Funds
                          </h3>
                          <button @click="showModal = !showModal"
                            class="btn -mr-1.5 h-7 w-7 rounded-full p-0 hover:bg-slate-300/20 focus:bg-slate-300/20 active:bg-slate-300/25 dark:hover:bg-navy-300/20 dark:focus:bg-navy-300/20 dark:active:bg-navy-300/25">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4.5 w-4.5" fill="none" viewBox="0 0 24 24"
                              stroke="currentColor" stroke-width="2">
                              <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                          </button>
                        </div>
                        <div class="px-4 py-4 sm:px-5">



                          <form action="deposit.php" method="post">
                            <div class="mt-4 space-y-4">

                              <label class="block">
                                <span>Enter Amount ($)</span>
                                <input
                                  class="form-input mt-1.5 h-12 w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 placeholder:text-slate-400/70 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent"
                                  placeholder="Enter Amount" required type="number" name="amount" />
                              </label>

                              <label class="block">
                                <span>Select Payment Method</span>
                                <select
                                  class="form-select mt-1.5 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 hover:border-slate-400 focus:border-primary dark:border-navy-450 dark:bg-navy-700 dark:hover:border-navy-400 dark:focus:border-accent"
                                  name="dtype">
                                    <?php 
                                        foreach ($payMethods as $name => $address) {
                                      ?>
                                        <option value="<?php echo $name ?>"><?php echo $name ?></option>
                                    <?php } ?>
                                </select>
                              </label>

                              <div class="space-x-2 text-right">
                                <button @click="showModal = false"
                                  class="btn min-w-[7rem] rounded-full border border-slate-300 font-medium text-slate-800 hover:bg-slate-150 focus:bg-slate-150 active:bg-slate-150/80 dark:border-navy-450 dark:text-navy-50 dark:hover:bg-navy-500 dark:focus:bg-navy-500 dark:active:bg-navy-500/90">
                                  Close
                                </button>
                                <button @click="showModal = false"
                                  class="btn min-w-[7rem] rounded-full bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90"
                                  type="submit" name="sub-upd">
                                  Proceed to Payment
                                </button>
                              </div>

                            </div>
                          </form>
                        </div>
                      </div>
                    </div>
                  </template>
                </div>



















              </div>
            </div>
          </div>
          <div class="absolute bottom-0 right-0 overflow-hidden rounded-lg">
            <img class="w-12 translate-x-1/4 translate-y-1/4 opacity-50" src="images/illustrations/the-dollar.svg"
              alt="image">
          </div>
        </div>


      </div>
      <!-- Hoverable Rows -->








      <div class="card px-4 pb-4 mt-4 sm:px-5">
        <div class="mt-3 flex h-8 items-center justify-between ">
          <div
            class=" mt-2 text-base  rounded-full  border-slate-300 text-slate-800 dark:border-navy-450 dark:text-navy-50">
            Pending Deposits
          </div>
          <div
            class=" mt-2 text-base  rounded-full  border-slate-300 text-slate-800 dark:border-navy-450 dark:text-navy-50">
            <a href="history.php"
              class="btn h-8 px-4 text-xs+ font-medium  bg-info/10 font-medium text-info hover:bg-info/20 focus:bg-info/20 active:bg-info/25">
              View History
            </a>
          </div>


        </div>


        <div class="mt-6">
          <div x-data x-init="$el._x_grid =  new Gridjs.Grid({
                from: $refs.table,
                sort: false,
                search: true,
                pagination: {
    limit: 7
  },
              }).render($refs.wrapper);">
            <div class="is-scrollbar-hidden min-w-full overflow-x-auto">
              <table x-ref="table" class="w-full text-left">
                <thead>
                  <tr>

                    <th
                      class="whitespace-nowrap rounded-l-lg bg-slate-200 px-2 py-3 font-semibold text-slate-800 dark:bg-navy-800 dark:text-navy-100">
                      Date/Time</th>
                    <th
                      class="whitespace-nowrap bg-slate-200  px-2 py-3 font-semibold text-slate-800 dark:bg-navy-800 dark:text-navy-100">
                      Trans. ID</th>
                    <th
                      class="whitespace-nowrap bg-slate-200 px-2 py-3 font-semibold text-slate-800 dark:bg-navy-800 dark:text-navy-100">
                      Amount</th>
                    <th
                      class="whitespace-nowrap bg-slate-200 px-2 py-3 font-semibold text-slate-800 dark:bg-navy-800 dark:text-navy-100">
                      Coin</th>
                    <th
                      class="whitespace-nowrap bg-slate-200 px-2 py-3 font-semibold text-slate-800 dark:bg-navy-800 dark:text-navy-100">
                      Status</th>
                    <th
                      class="whitespace-nowrap bg-slate-200 px-2 py-3 font-semibold text-slate-800 dark:bg-navy-800 dark:text-navy-100">
                      Control</th>

                  </tr>
                </thead>
                <tbody>
                <?php
                    $q = mysqli_query($link, "SELECT * FROM deposits WHERE userId = '$userId' ");
                    if(mysqli_num_rows($q) > 0){
                        while($row = mysqli_fetch_assoc($q)){
                            $method = $row['method'];
                            $img = $payMethods[$method];
                ?>
                  <tr>
                    <td class="whitespace-nowrap px-3 py-3"><?php echo date("D, j M Y", strtotime($row['date'])); ?></td>
                    <td class="whitespace-nowrap px-3 py-3"><?php echo $row['tranxId'] ?></td>
                    <td class="whitespace-nowrap px-3 py-3">$<?php echo $row['amount'] ?></td>
                    <td class="whitespace-nowrap px-3 py-3 inline ">
                      <p><img style='display:inline' src='<?php echo $img['image'] ?>' width='24'> <?php echo getCryptoValueByShortCode($payMethods[$method]['short_code'], $row['amount']); ?> </p>
                    </td>


                    <td class="whitespace-nowrap px-3 py-3"> <button type="button "
                        class="btn btn-rounded btn-sm btn-outline-warning">
                        <i class="bx bx-hourglass bx-spin font-size-16 align-middle me-2"></i>
                        <?php echo ucfirst($row['status']) ?>
                      </button></td>

                    <td> <a
                        href="deposit-payment.php?id=<?php echo $row['id'] ?>&tx=<?php echo $row['tranxId'] ?>&option=confirm"
                        class="btn space-x-2 border border-warning/30 bg-warning/10 text-xs+ rounded-full font-medium text-warning hover:bg-warning/20 focus:bg-warning/20 active:bg-warning/25"><i
                          class="fa fa-paperclip mr-1"> </i> Attach Proof</a></td>
                  </tr>
                <?php } } ?>
                </tbody>
              </table>
            </div>
            <div>
              <div x-ref="wrapper"></div>
            </div>
          </div>
        </div>
      </div>

    </main>

<?php
include 'footer.php'
?>