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

$fee = $udata['dlFindfee'];
checkServiceStatus($udata, 'dlFindfee_status');

if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['TNG'] ?? '')==='thenextgenapi') {

    $name = trim($_POST['Name'] ?? '');
    $dob  = trim($_POST['dob'] ?? '');

    $user   = $udata['phone'];
    $wallet = $udata['balance'];
    $after_balance = $wallet - $fee;

    // ❌ WALLET LOW
    if ($wallet < $fee) {
        echo "<script>
            Swal.fire('Wallet Low','Please recharge wallet','error')
            .then(()=>window.location='wallet.php');
        </script>";
        exit;
    }

    // API CALL
    $request = [
        'name' => urlencode($name),
        'dob'  => $dob
    ];

    $resdata = dl_find_verification_api_run($request);
    $sampleCode = $resdata['sampleCode'] ?? '';
    $errorMsg   = $resdata['error'] ?? '';

    // ❌ API ERROR
    if (!empty($errorMsg)) {
        echo "<script>
            Swal.fire('Failed','".addslashes($errorMsg)."','error');
        </script>";
        exit;
    }

    // ✅ SUCCESS
    if ($sampleCode === "200") {

        // Wallet debit
        mysqli_query($tng_conn,
            "UPDATE users SET balance = balance - $fee WHERE phone='$user'"
        );

        // Commission
        addCommission(
            $tng_conn,
            $user,
            $fee,
            $udata['parent'] ?? null,
            'DL Find (Name & DOB)'
        );

        // Wallet history
        mysqli_query($tng_conn,
            "INSERT INTO wallethistory
            (userid,amount,balance,purpose,status,type)
            VALUES(
                '$user','$fee','$after_balance',
                'DL Find (Name & DOB)','1','Debit'
            )"
        );

        // Base64 JSON save
        $jsonBase64 = base64_encode(
            json_encode($resdata, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)
        );

        mysqli_query($tng_conn,
            "INSERT INTO all_pdf_records
            (service_name,name,username,number,pdf,date)
            VALUES(
                'DL_FIND_NAME_DOB',
                '".mysqli_real_escape_string($tng_conn,$name)."',
                '$user',
                '".mysqli_real_escape_string($tng_conn,$dob)."',
                '".mysqli_real_escape_string($tng_conn,$jsonBase64)."',
                NOW()
            )"
        );

        echo "<script>
            Swal.fire({
                icon:'success',
                title:'DL Found Successfully',
                text:'Details saved to history',
                timer:2200,
                showConfirmButton:false
            }).then(()=>window.location='all_history.php');
        </script>";
        exit;
    }
}
?>

<!-- ===================== LUXURY CENTER UI ===================== -->
<style>
body{
  background:linear-gradient(135deg,#eef2ff,#f9fafb);
}
.lux-card{
  background:rgba(255,255,255,0.85);
  backdrop-filter:blur(14px);
  border-radius:22px;
  box-shadow:0 25px 50px rgba(0,0,0,.1);
  padding:28px;
}
.lux-title{
  font-weight:700;
  color:#4338ca;
}
.back-btn{
  text-decoration:none;
  font-weight:600;
}
.btn-glow{
  border-radius:40px;
  font-weight:600;
}
</style>

<div class="page-wrapper">
<div class="page-content">

<div class="container">
<div class="row justify-content-center align-items-center" style="min-height:80vh;">
<div class="col-lg-5 col-md-7 col-sm-10">

<div class="lux-card">

<div class="mb-3">
  <a href="javascript:history.back()" class="back-btn text-primary">
    <i class="bi bi-arrow-left-circle"></i> Back
  </a>
</div>

<h4 class="lux-title text-center mb-3">
  🚗 Driving Licence Find
</h4>
<p class="text-center text-muted mb-4">
  Find DL using <strong>Name & DOB</strong>
</p>

<form method="post" id="dlForm">
<input type="hidden" name="TNG" value="thenextgenapi">

<div class="mb-3">
  <label class="fw-semibold">Full Name</label>
  <input type="text" name="Name" class="form-control"
         placeholder="Enter full name" required>
</div>

<div class="mb-3">
  <label class="fw-semibold">Date of Birth</label>
  <input type="text" name="dob" class="form-control"
         placeholder="DD-MM-YYYY" required>
</div>

<div class="row align-items-center mt-4">
  <div class="col-6">
    <input class="form-control fw-bold text-primary"
           value="Fee ₹ <?php echo $fee; ?>" readonly>
  </div>
  <div class="col-6 text-end">
    <button type="submit" id="submitBtn"
            class="btn btn-success btn-glow px-4">
      <i class="fa fa-check-circle"></i> Submit
    </button>
  </div>
</div>

</form>

</div>

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

</div>
</div>

<!-- ===================== JS ===================== -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
let locked=false;
document.getElementById('dlForm').addEventListener('submit',function(e){
  e.preventDefault();
  if(locked) return;

  Swal.fire({
    title:'Are you sure?',
    text:'Wallet balance will be deducted',
    icon:'question',
    showCancelButton:true,
    confirmButtonText:'Yes, Continue',
    cancelButtonText:'Cancel'
  }).then(r=>{
    if(r.isConfirmed){
      locked=true;
      document.getElementById('submitBtn').disabled=true;
      this.submit();
    }
  });
});
</script>

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