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

$fee = $udata['ayushman_pdf_fee'] ?? 20;
checkServiceStatus($udata, 'ayushman_pdf_fee_status');

if ($_POST['aadhar']) {
    $aadhar = $_POST['aadhar'];
    $stateCode = $_POST['stateCode'];
    $appliedby = $udata['phone'];
    $debit_fee = $udata['balance'] - $fee;

    if ($udata['balance'] >= $fee) {
        $request = [
            'aadhar' => $aadhar,
            'stateCode' => $stateCode,
        ];

        $result = ayushman_verification_api_run($request);
        $resdata = json_decode(json_encode($result), true);

        $card_no = $resdata['card_no'] ?? '';
        $image = $resdata['image'] ?? '';
        $sampleCode = $resdata['sampleCode'] ?? '';
        $errore = $resdata['error'] ?? '';
        $parentPhone = $udata['parent'] ?? null;

        if ($errore) {
            echo "<script>$(function(){ Swal.fire('$errore', 'Something went wrong.', 'error') }); setTimeout(() => { window.location=''; }, 4000);</script>";
        } elseif ($sampleCode === "200") {
            $debit = mysqli_query($tng_conn, "UPDATE users SET balance=balance-$fee WHERE phone='$appliedby'");
            addCommission($tng_conn, $appliedby, $fee, $parentPhone, 'Ayushman Print PMJAY');
            $updatehistory = mysqli_query($tng_conn, "INSERT INTO wallethistory(userid, amount, balance, purpose, status, type) VALUES ('$appliedby','$fee','$debit_fee','Ayushman Print PMJAY','1','Debit')");
        }
    } else {
        echo "<script>$(function(){ Swal.fire('Wallet Balance is Low!', 'Please Recharge Now!', 'error') }); setTimeout(() => { window.location='wallet.php'; }, 1200);</script>";
    }
}
?>

<style>
/* ðŸŒˆ Glassmorphic Design */
body {
  background: linear-gradient(135deg, #a3cef1, #f6f9fc);
  font-family: 'Poppins', sans-serif;
  color: #333;
}

h4, h5 {
  font-weight: 700;
}

.card-glass {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(12px);
  border-radius: 20px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 24px rgba(0,0,0,0.1);
  transition: all 0.3s ease-in-out;
}
.card-glass:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 28px rgba(0,0,0,0.15);
}

.btn-modern {
  border-radius: 50px;
  font-weight: 600;
  transition: all 0.3s ease;
}
.btn-modern:hover {
  transform: scale(1.05);
}

.alert {
  border-radius: 12px;
  font-size: 15px;
}

label {
  font-weight: 600;
  color: #1f3b6d;
}

.table th {
  width: 30%;
  color: #0c2d57;
}

.table td, .table th {
  vertical-align: middle !important;
}

img#cardImage {
  border-radius: 10px;
  box-shadow: 0 3px 12px rgba(0,0,0,0.15);
  transition: all 0.3s ease;
}
img#cardImage:hover {
  transform: scale(1.03);
}

/* Animation */
.fade-in {
  animation: fadeIn 0.7s ease-in-out;
}
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(15px); }
  to { opacity: 1; transform: translateY(0); }
}

/* Responsive */
@media (max-width:768px){
  .card-glass { margin-bottom: 25px; }
}
</style>

<div class="page-wrapper">
  <div class="page-content fade-in">
    <div class="container py-5">

      <div class="text-center mb-5">
        <h4 class="fw-bold text-primary">
          <i class="fa fa-id-card text-warning me-2"></i> Ayushman Card Finder (All States)
        </h4>
        <p class="text-muted mb-0">Find your <strong>Ayushman PMJAY Card</strong> details quickly using Aadhaar number.</p>
      </div>

      <div class="row justify-content-center align-items-start g-4">
        
        <!-- Left: Form -->
        <div class="col-lg-4 col-md-6">
          <div class="card card-glass shadow-lg p-4">
            <div class="alert alert-primary text-center fw-bold mb-4">
              AYUSHMAN CARD FIND - ALL STATES
            </div>
            <form method="POST" novalidate>
              <div class="mb-3">
                <label for="stateCode">Select State</label>
                <select name="stateCode" id="stateCode" class="form-select shadow-sm" required>
                  <option value="">Select State</option>
                </select>
              </div>
              <div class="mb-3">
                <label for="aadhar">Enter Aadhaar Number</label>
                <input type="text" name="aadhar" id="aadhar" maxlength="12" minlength="12" class="form-control shadow-sm" placeholder="Enter 12-digit Aadhaar Number" required>
              </div>

              <div class="d-flex justify-content-between align-items-center mt-4">
                <input type="text" class="form-control w-50 text-center fw-bold text-primary" value="Fee â‚¹ <?php echo $fee; ?>" readonly>
                <button type="submit" class="btn btn-success btn-modern px-4">
                  <i class="fa fa-check-circle me-1"></i> Submit
                </button>
              </div>
            </form>
          </div>
        </div>

        <!-- Right: Result -->
        <?php if (!empty($sampleCode) && $sampleCode === "200") { ?>
        <div class="col-lg-8 col-md-6">
          <div class="card card-glass p-4 fade-in">
            <h5 class="fw-bold text-dark mb-3"><i class="fa fa-user-circle me-2 text-success"></i> Applicant Details</h5>
            <table class="table table-bordered table-striped">
              <tbody>
                <tr>
                  <th>Application Number</th>
                  <td><?php echo htmlspecialchars($resdata['application_no']); ?></td>
                </tr>
                <tr>
                  <th>Aadhaar Number</th>
                  <td><?php echo htmlspecialchars($aadhar); ?></td>
                </tr>
                <tr>
                  <th>PMJAY ID</th>
                  <td><?php echo htmlspecialchars($card_no); ?></td>
                </tr>
                <tr>
                  <th>Card Image</th>
                  <td class="text-center">
                    <?php if (!empty($image)) { ?>
                      <img id="cardImage" src="<?php echo $image; ?>" alt="Ayushman Card" class="img-fluid mb-3" style="max-width: 320px;">
                      <div class="d-flex justify-content-center gap-3">
                        <button class="btn btn-primary btn-modern btn-sm" onclick="printImage()">
                          <i class="fa fa-print me-1"></i> Print
                        </button>
                        <button class="btn btn-warning btn-modern btn-sm" onclick="downloadImage('<?php echo $image; ?>')">
                          <i class="fa fa-download me-1"></i> Download
                        </button>
                      </div>
                    <?php } else { ?>
                      <span class="text-muted">No image available</span>
                    <?php } ?>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <?php } ?>

      </div>
    </div>
  </div>
</div>

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

<!-- Populate States -->
<script>
document.addEventListener("DOMContentLoaded", function () {
  const states = [
    { code: "35", name: "ANDAMAN AND NICOBAR ISLANDS" },
    { code: "28", name: "ANDHRA PRADESH" },
    { code: "12", name: "ARUNACHAL PRADESH" },
    { code: "18", name: "ASSAM" },
    { code: "10", name: "BIHAR" },
    { code: "4", name: "CHANDIGARH" },
    { code: "22", name: "CHHATTISGARH" },
    { code: "26", name: "DADRA AND NAGAR HAVELI AND DAMAN AND DIU" },
    { code: "7", name: "DELHI" },
    { code: "30", name: "GOA" },
    { code: "24", name: "GUJARAT" },
    { code: "6", name: "HARYANA" },
    { code: "2", name: "HIMACHAL PRADESH" },
    { code: "1", name: "JAMMU AND KASHMIR" },
    { code: "20", name: "JHARKHAND" },
    { code: "29", name: "KARNATAKA" },
    { code: "32", name: "KERALA" },
    { code: "37", name: "LADAKH" },
    { code: "31", name: "LAKSHADWEEP" },
    { code: "23", name: "MADHYA PRADESH" },
    { code: "27", name: "MAHARASHTRA" },
    { code: "14", name: "MANIPUR" },
    { code: "17", name: "MEGHALAYA" },
    { code: "15", name: "MIZORAM" },
    { code: "13", name: "NAGALAND" },
    { code: "21", name: "ODISHA" },
    { code: "34", name: "PUDUCHERRY" },
    { code: "3", name: "PUNJAB" },
    { code: "8", name: "RAJASTHAN" },
    { code: "11", name: "SIKKIM" },
    { code: "33", name: "TAMIL NADU" },
    { code: "36", name: "TELANGANA" },
    { code: "16", name: "TRIPURA" },
    { code: "9", name: "UTTAR PRADESH" },
    { code: "5", name: "UTTARAKHAND" },
    { code: "19", name: "WEST BENGAL" }
  ];
  const select = document.getElementById("stateCode");
  states.forEach(st => {
    const opt = document.createElement("option");
    opt.value = st.code;
    opt.textContent = st.name;
    select.appendChild(opt);
  });
});
</script>

<!-- Print & Download -->
<script>
function printImage() {
  const img = document.getElementById("cardImage").src;
  const win = window.open('', '_blank');
  win.document.write('<html><head><title>Print Ayushman Card</title></head><body style="text-align:center;">');
  win.document.write('<img src="' + img + '" style="max-width:100%;border-radius:8px;"/>');
  win.document.write('</body></html>');
  win.document.close();
  win.focus();
  win.print();
}
function downloadImage(dataUrl) {
  let a = document.createElement("a");
  a.href = dataUrl;
  a.download = "Ayushman_Card.png";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}
</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>
</html>
