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

$fee = $udata['Lerning_Licence_pdf_fee'] ?? 30;
checkServiceStatus($udata, 'Lerning_Licence_pdf_fee_status');



if (!empty($_POST['value']) && !empty($_POST['type'])) {
    $value = trim($_POST['value']);
    $type = trim($_POST['type']);
    $dob = trim($_POST['dob'] ?? '');
    $appliedby = $udata['phone'];
    $debit_fee = $udata['balance'] - $fee;

    if ($udata['balance'] >= $fee) {
        $request = [
            'value' => $value,
            'type'  => $type,
            'dob'   => $dob
        ];

        $resdata = Lerning_license_to_pdf_verification_api_run($request);

        if (isset($resdata['Message']) && $resdata['Message'] === 'Failed') {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({
                    icon: 'error',
                    title: 'Verification Failed',
                    text: '".htmlspecialchars($resdata['error'] ?? 'Unknown Error')."',
                    timer: 4000
                });
                setTimeout(() => { window.location = ''; }, 4000);
            </script>";
        } elseif (isset($resdata['sampleCode']) && $resdata['sampleCode'] === "200") {
            date_default_timezone_set('Asia/Kolkata');
            $timestamp = date("Y-m-d H:i:s");
            $parentPhone = $udata['parent'] ?? null;

            addCommission($tng_conn, $appliedby, $fee, $parentPhone, "$value Learning Licence PDF Verification");

            mysqli_query($tng_conn, "INSERT INTO `Lerning_Licence_pdf`
                (`name`, `username`, `aadhar`, `pdf`, `date`)
                VALUES (
                    '".mysqli_real_escape_string($tng_conn, $resdata['fullname'] ?? '')."',
                    '".mysqli_real_escape_string($tng_conn, $udata['phone'])."',
                    '".mysqli_real_escape_string($tng_conn, $resdata['licNum'] ?? $resdata['applNum'] ?? '')."',
                    '".mysqli_real_escape_string($tng_conn, $resdata['pdf'] ?? '')."',
                    '$timestamp'
                )");

            mysqli_query($tng_conn, "UPDATE users SET balance=balance-$fee WHERE phone='$appliedby'");
            mysqli_query($tng_conn, "INSERT INTO wallethistory
                (`userid`, `amount`, `balance`, `purpose`, `status`, `type`)
                VALUES ('$appliedby','$fee','$debit_fee','$value Learning Licence PDF Verification','1','Debit')");
        } else {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({
                    icon: 'error',
                    title: 'Error 404',
                    text: 'Unexpected response from server. Please try again.',
                    timer: 4000
                });
                setTimeout(() => { window.location = ''; }, 4000);
            </script>";
        }
    } else {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({
                icon: 'warning',
                title: 'Low Wallet Balance!',
                text: 'Please recharge your wallet to continue.',
                timer: 2000
            });
            setTimeout(() => { window.location = 'wallet.php'; }, 1200);
        </script>";
    }
}
?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<div class="content-wrap">
 <div class="main">
  <div class="page-wrapper">
   <div class="page-content">
    <div class="mobile-menu-overlay"></div>
    <div class="main-container">
     <div class="col-lg-12">
      <div class="card shadow" style="margin-left:10px; padding:30px;">
       <div class="stat-widget-two">
        <div class="stat-content">
         <div class="container-fluid">
          <div class="row">
           <div class="col-lg-4 col-md-6 col-sm-6">
            <div class="card">
             <div class="card-body">
              <div class="mb-4">
               <a href="javascript:history.back()" class="back-btn">
                <i class="bi bi-arrow-left-circle"></i> Go Back
               </a>
              </div>

              <div class="alert alert-info" role="alert">
               Learning Licence PDF Verification
              </div>

              <form action="" method="POST" class="row g-3">
               <div class="col-md-12">
                <div class="form-group">
                 <label for="value">Enter Licence, Application Number or Mobile Number</label>
                 <input name="value" type="text" id="value" placeholder="Enter Value" class="form-control" required>
                </div>

                <div class="form-group mt-2">
                 <label for="type">Select Type</label>
                 <select name="type" class="form-control" id="typeSelect" required onchange="toggleFields()">
                  <option value="">Select Type</option>
                  <option value="licnum">Licence Number</option>
                  <option value="applnum">Application Number</option>
                  <option value="mobile">Mobile Number</option>
                 </select>
                </div>

                <div class="form-group mt-2" id="dobField" style="display: none;">
                 <label for="dob">Date of Birth</label>
                 <input name="dob" type="text" id="dob" placeholder="DD-MM-YYYY (e.g., 19-11-1983)" class="form-control">
                </div>

                <hr>
                <div class="row mt-3">
                 <div class="col-md-6">
                  <input class="form-control" value="Fee ₹ <?php echo $fee; ?>" readonly>
                 </div>
                 <div class="col-md-6 text-end">
                  <button class="btn btn-primary" name="submit" id="submit">
                   <i class="fa fa-check-circle"></i> Submit
                  </button>
                 </div>
                </div>
               </div>
              </form>
             </div>
            </div>
           </div>

           <?php if (!empty($resdata['sampleCode']) && $resdata['sampleCode'] === "200") { ?>
           <div class="col-lg-8 col-md-6 col-sm-6">
            <div class="card bg-light">
             <div class="card-body">
              <h5>
               Learning Licence to PDF Verification
               <a href="Lerning_License_To_Pdf_list.php" style="font-size:14px; margin-left:10px; text-decoration:none; color:blue;">
                (View List)
               </a>
              </h5>
              <table class="table table-bordered table-striped">
               <tbody>
                <tr><th><?php echo htmlspecialchars(ucfirst($type)); ?></th><td><?php echo htmlspecialchars($value); ?></td></tr>
                <?php if($type === 'mobile'){ ?>
                <tr><th>Date of Birth</th><td><?php echo htmlspecialchars($dob); ?></td></tr>
                <?php } ?>
                <tr><th>Message</th><td><?php echo htmlspecialchars($resdata['message'] ?? ''); ?></td></tr>
                <tr><th>Licence Number</th><td><?php echo htmlspecialchars($resdata['licNum'] ?? ''); ?></td></tr>
                <tr><th>Application Number</th><td><?php echo htmlspecialchars($resdata['applNum'] ?? ''); ?></td></tr>
                <tr><th>Date of Birth</th><td><?php echo htmlspecialchars($resdata['dob'] ?? ''); ?></td></tr>
                <tr><th>PDF</th>
                 <td>
                  <form action="view_pdf.php" method="POST" target="_blank" style="display:inline;">
                   <input type="hidden" name="pdf" value="<?= htmlspecialchars($resdata['pdf']) ?>">
                   <input type="hidden" name="filename" value="Learning_Licence_<?= htmlspecialchars($value) ?>.pdf">
                   <button type="submit" class="btn btn-success btn-sm">Download</button>
                  </form>
                 </td>
                </tr>
               </tbody>
              </table>
             </div>
            </div>
           </div>
           <?php } ?>
          </div>
         </div>
        </div>
       </div>
      </div>
     </div>
    </div>
   </div>
  </div>
 </div>
</div>

<script>
function toggleFields() {
    const typeSelect = document.getElementById('typeSelect');
    const dobField = document.getElementById('dobField');
    const dobInput = document.getElementById('dob');
    if(typeSelect.value === 'mobile'){
        dobField.style.display = 'block';
        dobInput.required = true;
    } else {
        dobField.style.display = 'none';
        dobInput.required = false;
        dobInput.value = '';
    }
}
document.addEventListener("DOMContentLoaded", function () {
    toggleFields();
    const form = document.querySelector("form");
    const submitBtn = document.getElementById("submit");
    let isSubmitting = false;

    form.addEventListener("submit", function (e) {
        if(isSubmitting){
            e.preventDefault();
            return;
        }
        isSubmitting = true;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Processing...';
    });
});
</script>

<?php include('../template/tngweb/footer.php'); ?>
<script src="../template/tngweb/assets/js/bootstrap.bundle.min.js"></script>
<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>
</html>
