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

echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>';

// Handle form POST for checking status (always hit API)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['check_status'], $_POST['order_id'])) {
    $order_id = mysqli_real_escape_string($tng_conn, $_POST['order_id']);
    $request = [
        'order_id' => $order_id,
        ];

        $resdata = ration_to_uid_all_details_verification_api_run($request);

    $status  = $resdata['Message'] ?? 'Unknown';
    $message = $resdata['message'] ?? ($resdata['error'] ?? 'No message from API');

    // DB update only if API says Success
    if ($status === 'Success') {
        mysqli_query($tng_conn, "UPDATE ration_to_aadhar_requests SET status='Success' WHERE order_id='$order_id'");
    }

    // Prepare member list HTML
    $member_html = '';
    if (!empty($resdata['memberDetailsList']) && is_array($resdata['memberDetailsList'])) {
        $member_html .= '<div style="max-height:300px;overflow:auto;font-size:14px">';
        $member_html .= '<table border="1" cellspacing="0" cellpadding="5" style="width:100%;border-collapse:collapse;text-align:left;font-size:14px">';
        $member_html .= '<tr style="background:#f2f2f2"><th>SL</th><th>Name</th><th>Member ID</th><th>Aadhaar</th><th>Relationship</th></tr>';
        foreach ($resdata['memberDetailsList'] as $member) {
            $member_html .= '<tr>
                <td>' . htmlspecialchars($member['sl_no']) . '</td>
                <td>' . htmlspecialchars($member['memberName']) . '</td>
                <td>' . htmlspecialchars($member['memberId']) . '</td>
                <td>' . htmlspecialchars($member['aadhaar']) . '</td>
                <td>' . htmlspecialchars($member['releationship_name']) . '</td>
            </tr>';
        }
        $member_html .= '</table></div>';
    }

    // Final HTML for Swal (with a wrapper for capture)
    $swal_html = "
    <div id='swalContent' style='padding:10px;text-align:left'>
        <h3 style='margin-top:0;color:#333;'>Status: " . htmlspecialchars($status) . "</h3>
        <p><b>Message:</b> " . htmlspecialchars($message) . "</p>
        $member_html
    </div>";

    echo "
<script>
Swal.fire({
    html: `$swal_html`,
    width: 750,
    showCloseButton: true,
    showCancelButton: true,
    cancelButtonText: 'Download PDF',
    confirmButtonText: 'OK'
}).then((result) => {
    if (result.dismiss === Swal.DismissReason.cancel) {
        let target = document.querySelector('#swalContent');
        if (target) {
            var opt = {
                margin: 0.3,
                filename: 'ration_uid_status.pdf',
                image: { type: 'jpeg', quality: 1 },
                html2canvas: { scale: 3, backgroundColor: '#fff' },
                jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' }
            };
            html2pdf().set(opt).from(target).save();
        }
    } else if (result.isConfirmed) {
        window.location.href = 'ration_2_uid_all_submit_list.php';
    }
});
</script>";
}
?>

<!--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 Ration To Uid History</h5>
        </div>
        <hr>

        <div class="table-responsive">
          <table id="walletTable" class="table table-hover table-striped align-middle text-center">
            <thead class="table-dark">
              <tr>
                            <th>SL.</th>
                            <th>Ration No</th>
                            <th>Order ID</th>
                            <th>Status</th>
                            <th>Request Time</th>
                            <th>View</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if ($udata['type'] == 'admin') {
                            $res = mysqli_query($tng_conn, "SELECT * FROM ration_to_aadhar_requests ORDER BY request_time DESC");
                        } else {
                            $res = mysqli_query($tng_conn, "SELECT * FROM ration_to_aadhar_requests WHERE userid='" . $udata['phone'] . "' ORDER BY request_time DESC");
                        }

                        $x = 0;
                        $refresh_after = 999999;

                        while ($row = mysqli_fetch_assoc($res)) {
                            $x++;

                            $request_time = strtotime($row['request_time']);
                            $current_time = time();
                            $elapsed = $current_time - $request_time;

                            if ($elapsed < 180) {
                                $remaining = 180 - $elapsed;
                                if ($remaining < $refresh_after) {
                                    $refresh_after = $remaining;
                                }
                            }

                            if ($row['status'] !== 'Success' && $elapsed >= 180) {
                                mysqli_query($tng_conn, "UPDATE ration_to_aadhar_requests SET status='Success' WHERE order_id='" . $row['order_id'] . "'");
                                $row['status'] = 'Success';
                            }
                            ?>
                            <tr>
                                <td><?php echo $x; ?></td>
                                <td><?php echo htmlspecialchars($row['ration_no']); ?></td>
                                <td><?php echo htmlspecialchars($row['order_id']); ?></td>
                                <td><?php echo htmlspecialchars($row['status']); ?></td>
                                <td><?php echo $row['request_time']; ?></td>
                                <td>
                                    <?php
                                    $remainingCountdown = 180 - $elapsed;
                                    if ($remainingCountdown > 0 && $row['status'] !== 'Success') {
                                        echo "<span class='countdown badge bg-warning text-dark' data-remaining='{$remainingCountdown}' data-orderid='" . htmlspecialchars($row['order_id']) . "'></span>";
                                    } else {
                                        ?>
                                        <form method="post">
                                            <input type="hidden" name="order_id" value="<?php echo htmlspecialchars($row['order_id']); ?>">
                                            <button type="submit" name="check_status" class="btn btn-primary btn-sm">View</button>
                                        </form>
                                        <?php
                                    }
                                    ?>
                                </td>
                            </tr>
                            <?php
                        }
                        ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
<!--end page wrapper -->

<?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>
<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>
<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>
<script>
$(document).ready(function() {
    var table = $('#example2').DataTable({
        lengthChange: false,
        buttons: [ 'copy', 'excel', 'pdf', 'print', 'colvis' ]
    });
    table.buttons().container().appendTo('#example2_wrapper .col-md-6:eq(0)');

    var refreshAfter = <?php echo ($refresh_after < 999999) ? $refresh_after : 0; ?>;
    if (refreshAfter > 0) {
        setTimeout(function() {
            location.reload();
        }, refreshAfter * 1000);
    }

    function startCountdown() {
        $(".countdown").each(function () {
            var el = $(this);
            var remaining = parseInt(el.data("remaining"));

            if (remaining > 0) {
                var timer = setInterval(function () {
                    if (remaining <= 0) {
                        clearInterval(timer);
                        el.replaceWith(
                            '<form method="post">' +
                            '<input type="hidden" name="order_id" value="' + el.data("orderid") + '">' +
                            '<button type="submit" name="check_status" class="btn btn-primary btn-sm">View</button>' +
                            '</form>'
                        );
                    } else {
                        var minutes = Math.floor(remaining / 60);
                        var seconds = remaining % 60;
                        el.text('Wait ' + minutes + ':' + (seconds < 10 ? '0' : '') + seconds);
                        remaining--;
                    }
                }, 1000);
            }
        });
    }
    startCountdown();
});
</script>
