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

$fee = $udata['driving_licence_to_mobile_find_fee'] ?? 20;
checkServiceStatus($udata, 'driving_licence_to_mobile_find_fee_status');

if ($_SERVER['REQUEST_METHOD']==='POST' && !empty($_POST['dlno'])) {

    $dlno = trim($_POST['dlno']);
    $dob = trim($_POST['dob']);
    $user      = $udata['phone'];
    $wallet    = $udata['balance'];
    $afterBal  = $wallet - $fee;

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

    // API CALL
    $resdata = dl_to_mobile_find_verification_api_run([
        'dlno' => $dlno,
        'dob' => $dob
    ]);

    $sampleCode = $resdata['sampleCode'] ?? '';
    $errorMsg   = $resdata['error'] ?? '';

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

   
    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 To Mobile Finder'
        );

        // WALLET HISTORY
        mysqli_query($tng_conn,
            "INSERT INTO wallethistory
            (userid,amount,balance,purpose,status,type)
            VALUES(
                '$user','$fee','$afterBal',
                'DL To Mobile Finder','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_TO_MOBILE',
                '".mysqli_real_escape_string($tng_conn,$resdata['fullname'] ?? 'DL Result')."',
                '$user',
                '".mysqli_real_escape_string($tng_conn,$dlno)."',
                '".mysqli_real_escape_string($tng_conn,$jsonBase64)."',
                NOW()
            )"
        );

        // SUCCESS → REDIRECT
        echo "<script>
            Swal.fire({
                icon:'success',
                title:'Success',
                text:'Mobile details fetched & saved',
                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.9);
  backdrop-filter:blur(16px);
  border-radius:22px;
  box-shadow:0 25px 50px rgba(0,0,0,.1);
  padding:28px;
}
.lux-title{
  font-weight:700;
  color:#4338ca;
}
.back-btn{
  font-weight:600;
  text-decoration:none;
}
</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-2">
  🚘 Driving Licence → Mobile Finder
</h4>
<p class="text-muted text-center mb-4">
  Find mobile number using DL number (All States)
</p>

<form method="post" id="dlForm">

<div class="mb-3">
  <label class="fw-semibold">Driving Licence Number</label>
  <input type="text" name="dlno"
         class="form-control form-control-lg"
         placeholder="Enter DL Number" required>
</div>
<div class="mb-3">
  <label class="fw-semibold">Date of Birth</label>
  <input type="text" name="dob"
         class="form-control form-control-lg"
         placeholder="DD-MM-YYYY (e.g. 01-01-1999)"
         maxlength="10"
         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-primary px-4 rounded-pill">
      <i class="fa fa-search"></i> Find
    </button>
  </div>
</div>

</form>

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

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

<!-- ================= CONFIRM + DOUBLE CLICK BLOCK ================= -->
<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>
<script>
document.getElementById('dlForm').addEventListener('submit',function(e){

  let dob = document.querySelector('[name="dob"]').value;
  let pattern = /^\d{2}-\d{2}-\d{4}$/;

  if(!pattern.test(dob)){
    e.preventDefault();
    Swal.fire('Invalid DOB','Format should be DD-MM-YYYY','error');
    return false;
  }

});
</script>

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