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

$fee = $udata['mobile_2_lpg'];
checkServiceStatus($udata,'mobile_2_lpg_status');

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

    $mobile = trim($_POST['mobileNumber']);
    $user   = $udata['phone'];
    $wallet = $udata['balance'];

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

    /* API CALL */
    $resdata = mobile_number_to_lpg_verification_api_run([
        'mobileNumber' => $mobile
    ]);

    $sampleCode = $resdata['sampleCode'] ?? '';
    $errorMsg   = $resdata['error'] ?? 'Mobile to LPG verification failed';

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

    /* ✅ SUCCESS FLOW */

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

    // Commission
    addCommission(
        $tng_conn,
        $user,
        $fee,
        $udata['parent'] ?? null,
        'MOBILE TO LPG'
    );

    // Wallet History
    mysqli_query(
        $tng_conn,
        "INSERT INTO wallethistory
        (userid,amount,balance,purpose,status,type)
        VALUES(
            '$user',
            '$fee',
            '".($wallet-$fee)."',
            'MOBILE TO LPG',
            '1',
            'Debit'
        )"
    );

    // BASE64 JSON SAVE
    $base64Json = 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(
            'MOBILE_TO_LPG',
            '".$resdata['data'][0]['name']."',
            '$user',
            '$mobile',
            '".mysqli_real_escape_string($tng_conn,$base64Json)."',
            NOW()
        )"
    );

    /* SUCCESS + REDIRECT */
    echo "<script>
      Swal.fire({
        icon:'success',
        title:'LPG Details Found',
        text:'Data saved successfully',
        timer:2200,
        showConfirmButton:false
      }).then(()=>window.location='all_history.php');
    </script>";
    exit;
}
?>

<!-- ================= UI ================= -->
<style>
body{
  background:linear-gradient(135deg,#fff7ed,#f0f9ff);
}
.glass{
  background:rgba(255,255,255,.97);
  backdrop-filter:blur(18px);
  border-radius:26px;
  box-shadow:0 30px 50px rgba(0,0,0,.12);
  padding:34px;
}
.title{
  font-weight:700;
  color:#7c2d12;
}
.back-btn{
  text-decoration:none;
  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="glass">

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

<h4 class="title text-center mb-1">
🔥 Mobile → LPG Verification
</h4>

<p class="text-muted text-center mb-4">
Check LPG connection details using mobile number
</p>

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

<div class="mb-3">
  <label class="fw-semibold">Mobile Number</label>
  <input type="text"
         name="mobileNumber"
         maxlength="10"
         minlength="10"
         class="form-control form-control-lg"
         placeholder="Enter 10 digit mobile number"
         required>
</div>

<div class="row mt-4 align-items-center">
  <div class="col-6">
    <input class="form-control fw-bold text-success"
           value="Fee ₹ <?= $fee ?>" readonly>
  </div>
  <div class="col-6 text-end">
    <button type="submit"
            id="submitBtn"
            class="btn btn-danger px-4 rounded-pill">
      <i class="fa fa-fire"></i> Verify LPG
    </button>
  </div>
</div>

</form>

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

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

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

  Swal.fire({
    title:'Confirm?',
    text:'Proceed with Mobile to LPG verification?',
    icon:'question',
    showCancelButton:true,
    confirmButtonText:'Yes',
    cancelButtonText:'Cancel'
  }).then(r=>{
    if(r.isConfirmed){
      locked=true;
      document.getElementById('submitBtn').disabled=true;
      this.submit();
    }
  });
});
</script>

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